3 * @copyright Copyright (C) 2010-2023, the Friendica project
5 * @license GNU AGPL version 3 or any later version
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU Affero General Public License as
9 * published by the Free Software Foundation, either version 3 of the
10 * License, or (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU Affero General Public License for more details.
17 * You should have received a copy of the GNU Affero General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
22 namespace Friendica\Model;
24 use Friendica\Contact\LocalRelationship\Entity\LocalRelationship;
25 use Friendica\Content\Post\Collection\PostMedias;
26 use Friendica\Content\Post\Entity\PostMedia;
27 use Friendica\Content\Text\BBCode;
28 use Friendica\Content\Text\HTML;
29 use Friendica\Core\Hook;
30 use Friendica\Core\Logger;
31 use Friendica\Core\Protocol;
32 use Friendica\Core\Renderer;
33 use Friendica\Core\System;
34 use Friendica\Core\Worker;
35 use Friendica\Database\DBA;
37 use Friendica\Model\Post\Category;
38 use Friendica\Network\HTTPException\InternalServerErrorException;
39 use Friendica\Network\HTTPException\ServiceUnavailableException;
40 use Friendica\Protocol\Activity;
41 use Friendica\Protocol\ActivityPub;
42 use Friendica\Protocol\Delivery;
43 use Friendica\Protocol\Diaspora;
44 use Friendica\Util\DateTimeFormat;
45 use Friendica\Util\Map;
46 use Friendica\Util\Network;
47 use Friendica\Util\Proxy;
48 use Friendica\Util\Strings;
49 use Friendica\Util\Temporal;
50 use GuzzleHttp\Psr7\Uri;
51 use LanguageDetection\Language;
55 // Posting types, inspired by https://www.w3.org/TR/activitystreams-vocabulary/#object-types
62 const PT_DOCUMENT = 19;
65 const PT_PERSONAL_NOTE = 128;
67 // Posting reasons (Why had a post been stored for a user?)
74 const PR_FOLLOWER = 69;
75 const PR_ANNOUNCEMENT = 70;
76 const PR_COMMENT = 71;
80 const PR_FETCHED = 75;
81 const PR_COMPLETION = 76;
83 const PR_ACTIVITY = 78;
84 const PR_DISTRIBUTE = 79;
87 const PR_AUDIENCE = 82;
89 // system.accept_only_sharer setting values
90 const COMPLETION_NONE = 1;
91 const COMPLETION_COMMENT = 0;
92 const COMPLETION_LIKE = 2;
94 // Field list that is used to display the items
95 const DISPLAY_FIELDLIST = [
96 'uid', 'id', 'parent', 'guid', 'network', 'gravity',
97 'uri-id', 'uri', 'thr-parent-id', 'thr-parent', 'parent-uri-id', 'parent-uri', 'conversation',
98 'commented', 'created', 'edited', 'received', 'verb', 'object-type', 'postopts', 'plink',
99 'wall', 'private', 'starred', 'origin', 'parent-origin', 'title', 'body', 'language',
100 'content-warning', 'location', 'coord', 'app', 'rendered-hash', 'rendered-html', 'object',
101 'quote-uri', 'quote-uri-id', 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid', 'mention', 'global',
102 'author-id', 'author-link', 'author-alias', 'author-name', 'author-avatar', 'author-network', 'author-updated', 'author-gsid', 'author-baseurl', 'author-addr', 'author-uri-id',
103 'owner-id', 'owner-link', 'owner-alias', 'owner-name', 'owner-avatar', 'owner-network', 'owner-contact-type', 'owner-updated', 'owner-gsid',
104 'causer-id', 'causer-link', 'causer-alias', 'causer-name', 'causer-avatar', 'causer-contact-type', 'causer-network', 'causer-gsid',
105 'contact-id', 'contact-uid', 'contact-link', 'contact-name', 'contact-avatar',
106 'writable', 'self', 'cid', 'alias',
107 'event-created', 'event-edited', 'event-start', 'event-finish',
108 'event-summary', 'event-desc', 'event-location', 'event-type',
109 'event-nofinish', 'event-ignore', 'event-id',
110 'question-id', 'question-multiple', 'question-voters', 'question-end-time',
111 'has-categories', 'has-media',
112 'delivery_queue_count', 'delivery_queue_done', 'delivery_queue_failed'
115 // Field list that is used to deliver items via the protocols
116 const DELIVER_FIELDLIST = [
117 'uid', 'id', 'parent', 'uri-id', 'uri', 'thr-parent', 'parent-uri', 'guid',
118 'parent-guid', 'conversation', 'received', 'created', 'edited', 'verb', 'object-type', 'object', 'target',
119 'private', 'title', 'body', 'raw-body', 'location', 'coord', 'app',
120 'inform', 'deleted', 'extid', 'post-type', 'post-reason', 'gravity',
121 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid',
122 'author-id', 'author-addr', 'author-link', 'author-name', 'author-avatar', 'owner-id', 'owner-link', 'contact-uid',
123 'signed_text', 'network', 'wall', 'contact-id', 'plink', 'origin',
124 'thr-parent-id', 'parent-uri-id', 'quote-uri', 'quote-uri-id', 'postopts', 'pubmail',
125 'event-created', 'event-edited', 'event-start', 'event-finish',
126 'event-summary', 'event-desc', 'event-location', 'event-type',
127 'event-nofinish', 'event-ignore', 'event-id'
130 // All fields in the item table
131 const ITEM_FIELDLIST = [
132 'id', 'uid', 'parent', 'uri', 'parent-uri', 'thr-parent',
133 'guid', 'uri-id', 'parent-uri-id', 'thr-parent-id', 'conversation', 'vid',
134 'quote-uri', 'quote-uri-id', 'contact-id', 'wall', 'gravity', 'extid', 'psid',
135 'created', 'edited', 'commented', 'received', 'changed', 'verb',
136 'postopts', 'plink', 'resource-id', 'event-id', 'inform',
137 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid', 'post-type', 'post-reason',
138 'private', 'pubmail', 'visible', 'starred',
139 'unseen', 'deleted', 'origin', 'mention', 'global', 'network',
140 'title', 'content-warning', 'body', 'location', 'coord', 'app',
141 'rendered-hash', 'rendered-html', 'object-type', 'object', 'target-type', 'target',
142 'author-id', 'author-link', 'author-name', 'author-avatar', 'author-network',
143 'owner-id', 'owner-link', 'owner-name', 'owner-avatar', 'causer-id'
146 // List of all verbs that don't need additional content data.
147 // Never reorder or remove entries from this list. Just add new ones at the end, if needed.
149 Activity::LIKE, Activity::DISLIKE,
150 Activity::ATTEND, Activity::ATTENDNO, Activity::ATTENDMAYBE,
160 // Item weight for query ordering
161 const GRAVITY_PARENT = 0;
162 const GRAVITY_ACTIVITY = 3;
163 const GRAVITY_COMMENT = 6;
164 const GRAVITY_UNKNOWN = 9;
167 * Update existing item entries
169 * @param array $fields The fields that are to be changed
170 * @param array $condition The condition for finding the item entries
172 * In the future we may have to change permissions as well.
173 * Then we had to add the user id as third parameter.
175 * A return value of "0" doesn't mean an error - but that 0 rows had been changed.
177 * @return integer|boolean number of affected rows - or "false" if there was an error
178 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
180 public static function update(array $fields, array $condition)
182 if (empty($condition) || empty($fields)) {
186 if (isset($fields['extid'])) {
187 $fields['external-id'] = ItemURI::getIdByURI($fields['extid']);
190 if (!empty($fields['verb'])) {
191 $fields['vid'] = Verb::getID($fields['verb']);
194 if (!empty($fields['edited'])) {
195 $previous = Post::selectFirst(['edited'], $condition);
198 $rows = Post::update($fields, $condition);
199 if (is_bool($rows)) {
203 // We only need to call the line by line update for specific fields
205 empty($fields['body']) && empty($fields['file']) &&
206 empty($fields['attach']) && empty($fields['edited'])
211 Logger::info('Updating per single row method', ['fields' => $fields, 'condition' => $condition]);
213 $items = Post::select(['id', 'origin', 'uri-id', 'uid', 'author-network', 'quote-uri-id'], $condition);
217 while ($item = DBA::fetch($items)) {
218 if (!empty($fields['body'])) {
219 if (!empty($item['quote-uri-id'])) {
220 $fields['body'] = BBCode::removeSharedData($fields['body']);
222 if (!empty($fields['raw-body'])) {
223 $fields['raw-body'] = BBCode::removeSharedData($fields['raw-body']);
227 $content_fields = ['raw-body' => trim($fields['raw-body'] ?? $fields['body'])];
229 // Remove all media attachments from the body and store them in the post-media table
230 // @todo On shared postings (Diaspora style and commented reshare) don't fetch content from the shared part
231 $content_fields['raw-body'] = Post\Media::insertFromBody($item['uri-id'], $content_fields['raw-body']);
232 $content_fields['raw-body'] = self::setHashtags($content_fields['raw-body']);
234 Post\Media::insertFromRelevantUrl($item['uri-id'], $content_fields['raw-body'], $fields['body'], $item['author-network']);
236 Post\Media::insertFromAttachmentData($item['uri-id'], $fields['body']);
237 $content_fields['raw-body'] = BBCode::removeAttachment($content_fields['raw-body']);
239 Post\Content::update($item['uri-id'], $content_fields);
242 if (!empty($fields['file'])) {
243 Post\Category::storeTextByURIId($item['uri-id'], $item['uid'], $fields['file']);
246 if (!empty($fields['attach'])) {
247 Post\Media::insertFromAttachment($item['uri-id'], $fields['attach']);
250 // We only need to notify others when it is an original entry from us.
251 // Only call the notifier when the item had been edited and records had been changed.
252 if ($item['origin'] && !empty($fields['edited']) && ($previous['edited'] != $fields['edited'])) {
253 $notify_items[] = $item['id'];
259 foreach ($notify_items as $notify_item) {
260 $post = Post::selectFirst([], ['id' => $notify_item]);
262 if ($post['gravity'] != self::GRAVITY_PARENT) {
263 $signed = Diaspora::createCommentSignature($post);
264 if (!empty($signed)) {
265 DBA::replace('diaspora-interaction', ['uri-id' => $post['uri-id'], 'interaction' => json_encode($signed)]);
269 Worker::add(Worker::PRIORITY_HIGH, 'Notifier', Delivery::POST, (int)$post['uri-id'], (int)$post['uid']);
276 * Delete an item and notify others about it - if it was ours
278 * @param array $condition The condition for finding the item entries
279 * @param integer $priority Priority for the notification
281 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
283 public static function markForDeletion(array $condition, int $priority = Worker::PRIORITY_HIGH)
285 $items = Post::select(['id'], $condition);
286 while ($item = Post::fetch($items)) {
287 self::markForDeletionById($item['id'], $priority);
293 * Delete an item for an user and notify others about it - if it was ours
295 * @param array $condition The condition for finding the item entries
296 * @param integer $uid User who wants to delete this item
298 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
300 public static function deleteForUser(array $condition, int $uid)
306 $items = Post::select(['id', 'uid', 'uri-id'], $condition);
307 while ($item = Post::fetch($items)) {
308 if (in_array($item['uid'], [$uid, 0])) {
309 Post\User::update($item['uri-id'], $uid, ['hidden' => true], true);
310 Post\ThreadUser::update($item['uri-id'], $uid, ['hidden' => true], true);
313 if ($item['uid'] == $uid) {
314 self::markForDeletionById($item['id'], Worker::PRIORITY_HIGH);
315 } elseif ($item['uid'] != 0) {
316 Logger::warning('Wrong ownership. Not deleting item', ['id' => $item['id']]);
323 * Mark an item for deletion, delete related data and notify others about it - if it was ours
325 * @param integer $item_id
326 * @param integer $priority Priority for the notification
327 * @return boolean success
328 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
330 public static function markForDeletionById(int $item_id, int $priority = Worker::PRIORITY_HIGH): bool
332 Logger::info('Mark item for deletion by id', ['id' => $item_id, 'callstack' => System::callstack()]);
333 // locate item to be deleted
335 'id', 'uri', 'uri-id', 'uid', 'parent', 'parent-uri-id', 'origin',
336 'deleted', 'resource-id', 'event-id',
337 'verb', 'object-type', 'object', 'target', 'contact-id', 'psid', 'gravity'
339 $item = Post::selectFirst($fields, ['id' => $item_id]);
340 if (!DBA::isResult($item)) {
341 Logger::info('Item not found.', ['id' => $item_id]);
345 if ($item['deleted']) {
346 Logger::info('Item has already been marked for deletion.', ['id' => $item_id]);
350 $parent = Post::selectFirst(['origin'], ['id' => $item['parent']]);
351 if (!DBA::isResult($parent)) {
352 $parent = ['origin' => false];
355 // clean up categories and tags so they don't end up as orphans
356 Post\Category::deleteByURIId($item['uri-id'], $item['uid']);
359 * If item is a link to a photo resource, nuke all the associated photos
360 * (visitors will not have photo resources)
361 * This only applies to photos uploaded from the photos page. Photos inserted into a post do not
362 * generate a resource-id and therefore aren't intimately linked to the item.
364 /// @TODO: this should first check if photo is used elsewhere
365 if ($item['resource-id']) {
366 Photo::delete(['resource-id' => $item['resource-id'], 'uid' => $item['uid']]);
369 // If item is a link to an event, delete the event.
370 if (intval($item['event-id'])) {
371 Event::delete($item['event-id']);
374 // If item has attachments, drop them
375 $attachments = Post\Media::getByURIId($item['uri-id'], [Post\Media::DOCUMENT]);
376 foreach ($attachments as $attachment) {
377 if (preg_match('|attach/(\d+)|', $attachment['url'], $matches)) {
378 Attach::delete(['id' => $matches[1], 'uid' => $item['uid']]);
382 // Set the item to "deleted"
383 $item_fields = ['deleted' => true, 'edited' => DateTimeFormat::utcNow(), 'changed' => DateTimeFormat::utcNow()];
384 Post::update($item_fields, ['id' => $item['id']]);
386 Post\Category::storeTextByURIId($item['uri-id'], $item['uid'], '');
388 if (!Post::exists(["`uri-id` = ? AND `uid` != 0 AND NOT `deleted`", $item['uri-id']])) {
389 self::markForDeletion(['uri-id' => $item['uri-id'], 'uid' => 0, 'deleted' => false], $priority);
392 Post\DeliveryData::delete($item['uri-id']);
394 // If it's the parent of a comment thread, kill all the kids
395 if ($item['gravity'] == self::GRAVITY_PARENT) {
396 self::markForDeletion(['parent' => $item['parent'], 'deleted' => false], $priority);
399 // Is it our comment and/or our thread?
400 if (($item['origin'] || $parent['origin']) && ($item['uid'] != 0)) {
401 // When we delete the original post we will delete all existing copies on the server as well
402 self::markForDeletion(['uri-id' => $item['uri-id'], 'deleted' => false], $priority);
404 // send the notification upstream/downstream
406 Worker::add(['priority' => $priority, 'dont_fork' => true], 'Notifier', Delivery::DELETION, (int)$item['uri-id'], (int)$item['uid']);
408 } elseif ($item['uid'] != 0) {
409 Post\User::update($item['uri-id'], $item['uid'], ['hidden' => true]);
410 Post\ThreadUser::update($item['uri-id'], $item['uid'], ['hidden' => true]);
413 DI::notify()->deleteForItem($item['uri-id']);
414 DI::notification()->deleteForItem($item['uri-id']);
416 Logger::info('Item has been marked for deletion.', ['id' => $item_id]);
422 * Get guid from given item record
424 * @param array $item Item record
425 * @param bool Whether to notify (?)
426 * @return string Guid
428 public static function guid(array $item, bool $notify): string
430 if (!empty($item['guid'])) {
431 return trim($item['guid']);
435 // We have to avoid duplicates. So we create the GUID in form of a hash of the plink or uri.
436 // We add the hash of our own host because our host is the original creator of the post.
437 $prefix_host = DI::baseUrl()->getHost();
441 // We are only storing the post so we create a GUID from the original hostname.
442 if (!empty($item['author-link'])) {
443 $parsed = parse_url($item['author-link']);
444 if (!empty($parsed['host'])) {
445 $prefix_host = $parsed['host'];
449 if (empty($prefix_host) && !empty($item['plink'])) {
450 $parsed = parse_url($item['plink']);
451 if (!empty($parsed['host'])) {
452 $prefix_host = $parsed['host'];
456 if (empty($prefix_host) && !empty($item['uri'])) {
457 $parsed = parse_url($item['uri']);
458 if (!empty($parsed['host'])) {
459 $prefix_host = $parsed['host'];
463 // Is it in the format data@host.tld? - Used for mail contacts
464 if (empty($prefix_host) && !empty($item['author-link']) && strstr($item['author-link'], '@')) {
465 $mailparts = explode('@', $item['author-link']);
466 $prefix_host = array_pop($mailparts);
470 if (!empty($item['plink'])) {
471 $guid = self::guidFromUri($item['plink'], $prefix_host);
472 } elseif (!empty($item['uri'])) {
473 $guid = self::guidFromUri($item['uri'], $prefix_host);
475 $guid = System::createUUID(hash('crc32', $prefix_host));
482 * Returns contact id from given item record
484 * @param array $item Item record
485 * @return int Contact id
487 private static function contactId(array $item): int
489 if ($item['uid'] == 0) {
490 return $item['owner-id'];
493 if ($item['origin']) {
494 $owner = User::getOwnerDataById($item['uid']);
499 $user_contact_id = 0;
500 foreach (['group-link', 'causer-link', 'owner-link', 'author-link'] as $field) {
501 if (empty($item[$field])) {
504 if (!$user_contact_id && Contact::isSharingByURL($item[$field], $item['uid'], true)) {
505 $user_contact_id = Contact::getIdForURL($item[$field], $item['uid']);
506 } elseif (!$contact_id) {
507 $contact_id = Contact::getIdForURL($item[$field]);
511 if ($user_contact_id) {
512 return $user_contact_id;
515 if (!empty($item['causer-id']) && Contact::isSharing($item['causer-id'], $item['uid'], true)) {
516 $cdata = Contact::getPublicAndUserContactID($item['causer-id'], $item['uid']);
517 if (!empty($cdata['user'])) {
518 return $cdata['user'];
526 Logger::warning('contact-id could not be fetched, using self contact instead.', ['uid' => $item['uid'], 'item' => $item]);
527 $self = Contact::selectFirst(['id'], ['self' => true, 'uid' => $item['uid']]);
532 * Write an item array into a spool file to be inserted later.
533 * This command is called whenever there are issues storing an item.
535 * @param array $item The item fields that are to be inserted
538 private static function spool(array $item)
540 // Now we store the data in the spool directory
541 // We use "microtime" to keep the arrival order and "mt_rand" to avoid duplicates
542 $file = 'item-' . round(microtime(true) * 10000) . '-' . mt_rand() . '.msg';
544 $spoolpath = System::getSpoolPath();
545 if ($spoolpath != '') {
546 $spool = $spoolpath . '/' . $file;
548 file_put_contents($spool, json_encode($item));
549 Logger::warning("Item wasn't stored - Item was spooled into file", ['file' => $file]);
554 * Check if the item array is a duplicate
556 * @param array $item Item record
557 * @return boolean is it a duplicate?
559 private static function isDuplicate(array $item): bool
561 // Checking if there is already an item with the same guid
562 $condition = ['guid' => $item['guid'], 'network' => $item['network'], 'uid' => $item['uid']];
563 if (Post::exists($condition)) {
564 Logger::notice('Found already existing item', $condition);
569 'uri-id' => $item['uri-id'], 'uid' => $item['uid'],
570 'network' => [$item['network'], Protocol::DFRN]
572 if (Post::exists($condition)) {
573 Logger::notice('duplicated item with the same uri found.', $condition);
577 // On Friendica and Diaspora the GUID is unique
578 if (in_array($item['network'], [Protocol::DFRN, Protocol::DIASPORA])) {
579 $condition = ['guid' => $item['guid'], 'uid' => $item['uid']];
580 if (Post::exists($condition)) {
581 Logger::notice('duplicated item with the same guid found.', $condition);
584 } elseif ($item['network'] == Protocol::OSTATUS) {
585 // Check for an existing post with the same content. There seems to be a problem with OStatus.
587 "`body` = ? AND `network` = ? AND `created` = ? AND `contact-id` = ? AND `uid` = ?",
588 $item['body'], $item['network'], $item['created'], $item['contact-id'], $item['uid']
590 if (Post::exists($condition)) {
591 Logger::notice('duplicated item with the same body found.', $item);
597 * Check for already added items.
598 * There is a timing issue here that sometimes creates double postings.
599 * An unique index would help - but the limitations of MySQL (maximum size of index values) prevent this.
601 if (($item['uid'] == 0) && Post::exists(['uri-id' => $item['uri-id'], 'uid' => 0])) {
602 Logger::notice('Global item already stored.', ['uri-id' => $item['uri-id'], 'network' => $item['network']]);
610 * Check if the item array is valid
612 * @param array $item Item record
613 * @return boolean item is valid
615 public static function isValid(array $item): bool
617 // When there is no content then we don't post it
618 if (($item['body'] . $item['title'] == '') && empty($item['quote-uri-id']) && empty($item['attachments']) && (empty($item['uri-id']) || !Post\Media::existsByURIId($item['uri-id']))) {
619 Logger::notice('No body, no title.');
623 if (!empty($item['uid'])) {
624 $owner = User::getOwnerDataById($item['uid'], false);
626 Logger::warning('Missing item user owner data', ['uid' => $item['uid']]);
630 if ($owner['account_expired'] || $owner['account_removed']) {
631 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']]);
636 if (!empty($item['author-id']) && Contact::isBlocked($item['author-id'])) {
637 Logger::notice('Author is blocked node-wide', ['author-link' => $item['author-link'], 'item-uri' => $item['uri']]);
641 if (!empty($item['author-link']) && Network::isUrlBlocked($item['author-link'])) {
642 Logger::notice('Author server is blocked', ['author-link' => $item['author-link'], 'item-uri' => $item['uri']]);
646 if (!empty($item['owner-id']) && Contact::isBlocked($item['owner-id'])) {
647 Logger::notice('Owner is blocked node-wide', ['owner-link' => $item['owner-link'], 'item-uri' => $item['uri']]);
651 if (!empty($item['owner-link']) && Network::isUrlBlocked($item['owner-link'])) {
652 Logger::notice('Owner server is blocked', ['owner-link' => $item['owner-link'], 'item-uri' => $item['uri']]);
656 if ($item['verb'] == Activity::FOLLOW) {
657 if (!$item['origin'] && ($item['author-id'] == Contact::getPublicIdByUserId($item['uid']))) {
658 // Our own follow request can be relayed to us. We don't store it to avoid notification chaos.
659 Logger::info("Follow: Don't store not origin follow request", ['parent-uri' => $item['parent-uri']]);
664 'verb' => Activity::FOLLOW, 'uid' => $item['uid'],
665 'parent-uri' => $item['parent-uri'], 'author-id' => $item['author-id']
667 if (Post::exists($condition)) {
668 // It happens that we receive multiple follow requests by the same author - we only store one.
669 Logger::info('Follow: Found existing follow request from author', ['author-id' => $item['author-id'], 'parent-uri' => $item['parent-uri']]);
678 * Check if the item array is too old
680 * @param array $item Item record
681 * @return boolean item is too old
683 public static function isTooOld(array $item): bool
685 // check for create date and expire time
686 $expire_interval = DI::config()->get('system', 'dbclean-expire-days', 0);
688 $user = DBA::selectFirst('user', ['expire'], ['uid' => $item['uid']]);
689 if (DBA::isResult($user) && ($user['expire'] > 0) && (($user['expire'] < $expire_interval) || ($expire_interval == 0))) {
690 $expire_interval = $user['expire'];
693 if (($expire_interval > 0) && !empty($item['created'])) {
694 $expire_date = time() - ($expire_interval * 86400);
695 $created_date = strtotime($item['created']);
696 if ($created_date < $expire_date) {
697 Logger::notice('Item created before expiration interval.', [
698 'created' => date('c', $created_date),
699 'expired' => date('c', $expire_date),
710 * Return the id of the given item array if it has been stored before
712 * @param array $item Item record
713 * @return integer Item id or zero on error
715 private static function getDuplicateID(array $item): int
717 if (empty($item['network']) || in_array($item['network'], Protocol::FEDERATED)) {
719 '`uri-id` = ? AND `uid` = ? AND `network` IN (?, ?, ?, ?)',
722 Protocol::ACTIVITYPUB,
727 $existing = Post::selectFirst(['id', 'network'], $condition);
728 if (DBA::isResult($existing)) {
729 // We only log the entries with a different user id than 0. Otherwise we would have too many false positives
730 if ($item['uid'] != 0) {
731 Logger::notice('Item already existed for user', [
732 'uri-id' => $item['uri-id'],
733 'uid' => $item['uid'],
734 'network' => $item['network'],
735 'existing_id' => $existing['id'],
736 'existing_network' => $existing['network']
740 return $existing['id'];
747 * Fetch the uri-id of the parent for the given uri-id
749 * @param integer $uriid
752 public static function getParent(int $uriid): int
754 $thread_parent = Post::selectFirstPost(['thr-parent-id', 'gravity'], ['uri-id' => $uriid]);
755 if (empty($thread_parent)) {
759 if ($thread_parent['gravity'] == Item::GRAVITY_PARENT) {
763 return self::getParent($thread_parent['thr-parent-id']);
767 * Fetch top-level parent data for the given item array
770 * @return array item array with parent data
773 private static function getTopLevelParent(array $item): array
776 'uid', 'uri', 'parent-uri', 'id', 'deleted',
777 'uri-id', 'parent-uri-id',
778 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid',
779 'wall', 'private', 'origin', 'author-id'
781 $condition = ['uri-id' => [$item['thr-parent-id'], $item['parent-uri-id']], 'uid' => $item['uid']];
782 $params = ['order' => ['id' => false]];
783 $parent = Post::selectFirst($fields, $condition, $params);
785 if (!DBA::isResult($parent) && Post::exists(['uri-id' => [$item['thr-parent-id'], $item['parent-uri-id']], 'uid' => 0])) {
786 $stored = Item::storeForUserByUriId($item['thr-parent-id'], $item['uid'], ['post-reason' => Item::PR_COMPLETION]);
787 if (!$stored && ($item['thr-parent-id'] != $item['parent-uri-id'])) {
788 $stored = Item::storeForUserByUriId($item['parent-uri-id'], $item['uid'], ['post-reason' => Item::PR_COMPLETION]);
791 Logger::info('Stored thread parent item for user', ['uri-id' => $item['thr-parent-id'], 'uid' => $item['uid'], 'stored' => $stored]);
792 $parent = Post::selectFirst($fields, $condition, $params);
796 if (!DBA::isResult($parent)) {
797 Logger::notice('item parent was not found - ignoring item', ['uri-id' => $item['uri-id'], 'thr-parent-id' => $item['thr-parent-id'], 'uid' => $item['uid'], 'callstack' => System::callstack(20)]);
801 if ($parent['uri-id'] == $parent['parent-uri-id']) {
806 'uri-id' => $parent['parent-uri-id'],
807 'parent-uri-id' => $parent['parent-uri-id'],
808 'uid' => $parent['uid']
810 $params = ['order' => ['id' => false]];
811 $toplevel_parent = Post::selectFirst($fields, $condition, $params);
813 if (!DBA::isResult($toplevel_parent) && $item['origin']) {
814 $stored = Item::storeForUserByUriId($item['parent-uri-id'], $item['uid'], ['post-reason' => Item::PR_COMPLETION]);
815 Logger::info('Stored parent item for user', ['uri-id' => $item['parent-uri-id'], 'uid' => $item['uid'], 'stored' => $stored]);
816 $toplevel_parent = Post::selectFirst($fields, $condition, $params);
819 if (!DBA::isResult($toplevel_parent)) {
820 Logger::notice('item top level parent was not found - ignoring item', ['parent-uri-id' => $parent['parent-uri-id'], 'uid' => $parent['uid']]);
824 return $toplevel_parent;
828 * Get the gravity for the given item array
831 * @return integer gravity
833 private static function getGravity(array $item): int
835 $activity = DI::activity();
837 if (isset($item['gravity'])) {
838 return intval($item['gravity']);
839 } elseif ($item['parent-uri-id'] === $item['uri-id']) {
840 return self::GRAVITY_PARENT;
841 } elseif ($activity->match($item['verb'], Activity::POST)) {
842 return self::GRAVITY_COMMENT;
843 } elseif ($activity->match($item['verb'], Activity::FOLLOW)) {
844 return self::GRAVITY_ACTIVITY;
845 } elseif ($activity->match($item['verb'], Activity::ANNOUNCE)) {
846 return self::GRAVITY_ACTIVITY;
849 Logger::info('Unknown gravity for verb', ['verb' => $item['verb']]);
850 return self::GRAVITY_UNKNOWN; // Should not happen
853 private static function prepareOriginPost(array $item): array
855 $item = DI::contentItem()->initializePost($item);
856 $item = DI::contentItem()->finalizePost($item);
862 * Inserts item record
864 * @param array $item Item array to be inserted
865 * @param int $notify Notification (type?)
866 * @param bool $post_local (???)
867 * @return int Zero means error, otherwise primary key (id) is being returned
869 public static function insert(array $item, int $notify = 0, bool $post_local = true): int
873 $priority = Worker::PRIORITY_HIGH;
875 // If it is a posting where users should get notifications, then define it as wall posting
877 $item = self::prepareOriginPost($item);
879 if (is_int($notify) && in_array($notify, Worker::PRIORITIES)) {
883 $item['network'] = trim(($item['network'] ?? '') ?: Protocol::PHANTOM);
886 $uid = intval($item['uid']);
888 $item['guid'] = self::guid($item, $notify);
889 $item['uri'] = substr(trim($item['uri'] ?? '') ?: self::newURI($item['guid']), 0, 255);
892 $item['uri-id'] = ItemURI::insert(['uri' => $item['uri'], 'guid' => $item['guid']]);
894 // Backward compatibility: parent-uri used to be the direct parent uri.
895 // If it is provided without a thr-parent, it probably is the old behavior.
896 if (empty($item['thr-parent']) || empty($item['parent-uri'])) {
897 $item['thr-parent'] = trim($item['thr-parent'] ?? $item['parent-uri'] ?? $item['uri']);
898 $item['parent-uri'] = $item['thr-parent'];
901 $item['thr-parent-id'] = ItemURI::getIdByURI($item['thr-parent']);
902 $item['parent-uri-id'] = ItemURI::getIdByURI($item['parent-uri']);
904 // Store conversation data
905 $source = $item['source'] ?? '';
906 unset($item['conversation-uri']);
907 unset($item['conversation-href']);
908 unset($item['source']);
911 * Do we already have this item?
912 * We have to check several networks since Friendica posts could be repeated
913 * via OStatus (maybe Diaspora as well)
915 $duplicate = self::getDuplicateID($item);
920 // Additional duplicate checks
921 /// @todo Check why the first duplication check returns the item number and the second a 0
922 if (self::isDuplicate($item)) {
926 if (!isset($item['post-type'])) {
927 $item['post-type'] = empty($item['title']) ? self::PT_NOTE : self::PT_ARTICLE;
930 $defined_permissions = isset($item['allow_cid']) && isset($item['allow_gid']) && isset($item['deny_cid']) && isset($item['deny_gid']) && isset($item['private']);
932 $item['wall'] = intval($item['wall'] ?? 0);
933 $item['extid'] = trim($item['extid'] ?? '');
934 $item['author-name'] = trim($item['author-name'] ?? '');
935 $item['author-link'] = trim($item['author-link'] ?? '');
936 $item['author-avatar'] = trim($item['author-avatar'] ?? '');
937 $item['owner-name'] = trim($item['owner-name'] ?? '');
938 $item['owner-link'] = trim($item['owner-link'] ?? '');
939 $item['owner-avatar'] = trim($item['owner-avatar'] ?? '');
940 $item['received'] = (isset($item['received']) ? DateTimeFormat::utc($item['received']) : DateTimeFormat::utcNow());
941 $item['created'] = (isset($item['created']) ? DateTimeFormat::utc($item['created']) : $item['received']);
942 $item['edited'] = (isset($item['edited']) ? DateTimeFormat::utc($item['edited']) : $item['created']);
943 $item['changed'] = (isset($item['changed']) ? DateTimeFormat::utc($item['changed']) : $item['created']);
944 $item['commented'] = (isset($item['commented']) ? DateTimeFormat::utc($item['commented']) : $item['created']);
945 $item['title'] = substr(trim($item['title'] ?? ''), 0, 255);
946 $item['location'] = trim($item['location'] ?? '');
947 $item['coord'] = trim($item['coord'] ?? '');
948 $item['visible'] = (isset($item['visible']) ? intval($item['visible']) : 1);
949 $item['deleted'] = 0;
950 $item['verb'] = trim($item['verb'] ?? '');
951 $item['object-type'] = trim($item['object-type'] ?? '');
952 $item['object'] = trim($item['object'] ?? '');
953 $item['target-type'] = trim($item['target-type'] ?? '');
954 $item['target'] = trim($item['target'] ?? '');
955 $item['plink'] = substr(trim($item['plink'] ?? ''), 0, 255);
956 $item['allow_cid'] = trim($item['allow_cid'] ?? '');
957 $item['allow_gid'] = trim($item['allow_gid'] ?? '');
958 $item['deny_cid'] = trim($item['deny_cid'] ?? '');
959 $item['deny_gid'] = trim($item['deny_gid'] ?? '');
960 $item['private'] = intval($item['private'] ?? self::PUBLIC);
961 $item['body'] = trim($item['body'] ?? '');
962 $item['raw-body'] = trim($item['raw-body'] ?? $item['body']);
963 $item['app'] = trim($item['app'] ?? '');
964 $item['origin'] = intval($item['origin'] ?? 0);
965 $item['postopts'] = trim($item['postopts'] ?? '');
966 $item['resource-id'] = trim($item['resource-id'] ?? '');
967 $item['event-id'] = intval($item['event-id'] ?? 0);
968 $item['inform'] = trim($item['inform'] ?? '');
969 $item['file'] = trim($item['file'] ?? '');
971 // Communities aren't working with the Diaspora protocol
972 if (($uid != 0) && ($item['network'] == Protocol::DIASPORA)) {
973 $user = User::getById($uid, ['account-type']);
974 if ($user['account-type'] == Contact::TYPE_COMMUNITY) {
975 Logger::info('Community posts are not supported via Diaspora');
980 // Items cannot be stored before they happen ...
981 if ($item['created'] > DateTimeFormat::utcNow()) {
982 $item['created'] = DateTimeFormat::utcNow();
985 // We haven't invented time travel by now.
986 if ($item['edited'] > DateTimeFormat::utcNow()) {
987 $item['edited'] = DateTimeFormat::utcNow();
990 $item['plink'] = ($item['plink'] ?? '') ?: DI::baseUrl() . '/display/' . urlencode($item['guid']);
992 $item['gravity'] = self::getGravity($item);
995 'url' => $item['author-link'], 'name' => $item['author-name'],
996 'photo' => $item['author-avatar'], 'network' => $item['network']
998 $item['author-id'] = ($item['author-id'] ?? 0) ?: Contact::getIdForURL($item['author-link'], 0, null, $default);
1001 'url' => $item['owner-link'], 'name' => $item['owner-name'],
1002 'photo' => $item['owner-avatar'], 'network' => $item['network']
1004 $item['owner-id'] = ($item['owner-id'] ?? 0) ?: Contact::getIdForURL($item['owner-link'], 0, null, $default);
1006 $item['post-reason'] = self::getPostReason($item);
1008 // Ensure that there is an avatar cache
1009 Contact::checkAvatarCache($item['author-id']);
1010 Contact::checkAvatarCache($item['owner-id']);
1012 $item['contact-id'] = self::contactId($item);
1015 !empty($item['direction']) && in_array($item['direction'], [Conversation::PUSH, Conversation::RELAY]) &&
1016 empty($item['origin']) && self::isTooOld($item)
1018 Logger::info('Item is too old', ['item' => $item]);
1022 if (!self::isValid($item)) {
1026 if ($item['gravity'] !== self::GRAVITY_PARENT) {
1027 $toplevel_parent = self::getTopLevelParent($item);
1028 if (empty($toplevel_parent)) {
1032 $parent_id = $toplevel_parent['id'];
1033 $item['parent-uri'] = $toplevel_parent['uri'];
1034 $item['parent-uri-id'] = $toplevel_parent['uri-id'];
1035 $item['deleted'] = $toplevel_parent['deleted'];
1036 $item['wall'] = $toplevel_parent['wall'];
1038 // Reshares have to keep their permissions to allow groups to work
1039 if (!$defined_permissions && (!$item['origin'] || ($item['verb'] != Activity::ANNOUNCE))) {
1040 $item['allow_cid'] = $toplevel_parent['allow_cid'];
1041 $item['allow_gid'] = $toplevel_parent['allow_gid'];
1042 $item['deny_cid'] = $toplevel_parent['deny_cid'];
1043 $item['deny_gid'] = $toplevel_parent['deny_gid'];
1046 $parent_origin = $toplevel_parent['origin'];
1048 // Don't federate received participation messages
1049 if ($item['verb'] != Activity::FOLLOW) {
1050 $item['wall'] = $toplevel_parent['wall'];
1052 $item['wall'] = false;
1053 // Participations are technical messages, so they are set to "seen" automatically
1054 $item['unseen'] = false;
1058 * If the parent is private, force privacy for the entire conversation
1059 * This differs from the above settings as it subtly allows comments from
1060 * email correspondents to be private even if the overall thread is not.
1062 if (!$defined_permissions && $toplevel_parent['private']) {
1063 $item['private'] = $toplevel_parent['private'];
1066 // If its a post that originated here then tag the thread as "mention"
1067 if ($item['origin'] && $item['uid']) {
1068 DBA::update('post-thread-user', ['mention' => true], ['uri-id' => $item['parent-uri-id'], 'uid' => $item['uid']]);
1069 Logger::info('tagged thread as mention', ['parent' => $parent_id, 'parent-uri-id' => $item['parent-uri-id'], 'uid' => $item['uid']]);
1072 // Update the contact relations
1073 Contact\Relation::store($toplevel_parent['author-id'], $item['author-id'], $item['created']);
1076 $parent_origin = $item['origin'];
1078 if ($item['wall'] && empty($item['conversation'])) {
1079 $item['conversation'] = $item['parent-uri'] . '#context';
1083 if ($item['origin']) {
1085 Photo::setPermissionFromBody($item['body'], $item['uid'], $item['contact-id'], $item['allow_cid'], $item['allow_gid'], $item['deny_cid'], $item['deny_gid'])
1086 && ($item['object-type'] != Activity\ObjectType::EVENT)
1088 $item['object-type'] = Activity\ObjectType::IMAGE;
1091 $item = DI::contentItem()->moveAttachmentsFromBodyToAttach($item);
1094 $item['parent-uri-id'] = ItemURI::getIdByURI($item['parent-uri']);
1095 $item['thr-parent-id'] = ItemURI::getIdByURI($item['thr-parent']);
1097 if (!empty($item['conversation']) && empty($item['conversation-id'])) {
1098 $item['conversation-id'] = ItemURI::getIdByURI($item['conversation']);
1101 // Is this item available in the global items (with uid=0)?
1102 if ($item['uid'] == 0) {
1103 $item['global'] = true;
1105 // Set the global flag on all items if this was a global item entry
1106 Post::update(['global' => true], ['uri-id' => $item['uri-id']]);
1108 $item['global'] = Post::exists(['uid' => 0, 'uri-id' => $item['uri-id']]);
1112 if (!$defined_permissions && !empty($item['allow_cid'] . $item['allow_gid'] . $item['deny_cid'] . $item['deny_gid'])) {
1113 $item['private'] = self::PRIVATE;
1116 if ($notify && $post_local) {
1117 $item['edit'] = false;
1118 $item['parent'] = $parent_id;
1120 // Trigger automatic reactions for addons
1121 if (!isset($item['api_source'])) {
1122 $item['api_source'] = true;
1125 // We have to tell the hooks who we are - this really should be improved
1126 if (!DI::userSession()->getLocalUserId()) {
1127 $_SESSION['authenticated'] = true;
1128 $_SESSION['uid'] = $uid;
1129 $dummy_session = true;
1131 $dummy_session = false;
1134 Hook::callAll('post_local', $item);
1136 if ($dummy_session) {
1137 unset($_SESSION['authenticated']);
1138 unset($_SESSION['uid']);
1140 } elseif (!$notify) {
1141 Hook::callAll('post_remote', $item);
1144 if (!empty($item['cancel'])) {
1145 Logger::notice('post cancelled by addon.');
1149 if (empty($item['vid']) && !empty($item['verb'])) {
1150 $item['vid'] = Verb::getID($item['verb']);
1153 // Creates or assigns the permission set
1154 $item['psid'] = DI::permissionSet()->selectOrCreate(
1155 DI::permissionSetFactory()->createFromString(
1164 if (!empty($item['extid'])) {
1165 $item['external-id'] = ItemURI::getIdByURI($item['extid']);
1168 if ($item['verb'] == Activity::ANNOUNCE) {
1169 self::setOwnerforResharedItem($item);
1172 if (isset($item['attachments'])) {
1173 foreach ($item['attachments'] as $attachment) {
1174 $attachment['uri-id'] = $item['uri-id'];
1175 Post\Media::insert($attachment);
1177 unset($item['attachments']);
1180 if (empty($item['quote-uri-id'])) {
1181 $quote_id = self::getQuoteUriId($item['body']);
1182 if (!empty($quote_id)) {
1183 // This is one of these "should not happen" situations.
1184 // The protocol implementations should already have done this job.
1185 Logger::notice('Quote-uri-id detected in post', ['id' => $quote_id, 'guid' => $item['guid'], 'uri-id' => $item['uri-id'], 'callstack' => System::callstack(20)]);
1186 $item['quote-uri-id'] = $quote_id;
1190 if (!empty($item['quote-uri-id']) && ($item['quote-uri-id'] == $item['uri-id'])) {
1191 Logger::info('Quote-Uri-Id is identical to Uri-Id', ['uri-id' => $item['uri-id'], 'guid' => $item['guid']]);
1192 unset($item['quote-uri-id']);
1195 if (!empty($item['quote-uri-id'])) {
1196 $item['raw-body'] = BBCode::removeSharedData($item['raw-body']);
1197 $item['body'] = BBCode::removeSharedData($item['body']);
1200 // Remove all media attachments from the body and store them in the post-media table
1201 $item['raw-body'] = Post\Media::insertFromBody($item['uri-id'], $item['raw-body']);
1202 $item['raw-body'] = self::setHashtags($item['raw-body']);
1204 $author = Contact::getById($item['author-id'], ['network']);
1205 Post\Media::insertFromRelevantUrl($item['uri-id'], $item['raw-body'], $item['body'], $author['network'] ?? '');
1207 Post\Media::insertFromAttachmentData($item['uri-id'], $item['body']);
1208 $item['body'] = BBCode::removeAttachment($item['body']);
1209 $item['raw-body'] = BBCode::removeAttachment($item['raw-body']);
1211 // Check for hashtags in the body and repair or add hashtag links
1212 $item['body'] = self::setHashtags($item['body']);
1214 $item['language'] = self::getLanguage($item);
1216 $notify_type = Delivery::POST;
1218 // Filling item related side tables
1219 if (!empty($item['attach'])) {
1220 Post\Media::insertFromAttachment($item['uri-id'], $item['attach']);
1223 if (empty($item['event-id'])) {
1224 unset($item['event-id']);
1226 $ev = Event::fromBBCode($item['body']);
1227 if ((!empty($ev['desc']) || !empty($ev['summary'])) && !empty($ev['start'])) {
1228 Logger::info('Event found.');
1229 $ev['cid'] = $item['contact-id'];
1230 $ev['uid'] = $item['uid'];
1231 $ev['uri'] = $item['uri'];
1232 $ev['edited'] = $item['edited'];
1233 $ev['private'] = $item['private'];
1234 $ev['guid'] = $item['guid'];
1235 $ev['plink'] = $item['plink'];
1236 $ev['network'] = $item['network'];
1237 $ev['protocol'] = $item['protocol'] ?? Conversation::PARCEL_UNKNOWN;
1238 $ev['direction'] = $item['direction'] ?? Conversation::UNKNOWN;
1239 $ev['source'] = $item['source'] ?? '';
1241 $event = DBA::selectFirst('event', ['id'], ['uri' => $item['uri'], 'uid' => $item['uid']]);
1242 if (DBA::isResult($event)) {
1243 $ev['id'] = $event['id'];
1246 $event_id = Event::store($ev);
1247 $item = Event::getItemArrayForImportedId($event_id, $item);
1249 Logger::info('Event was stored', ['id' => $event_id]);
1253 if (empty($item['causer-id'])) {
1254 unset($item['causer-id']);
1257 if (in_array($item['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN])) {
1258 $content_warning = BBCode::getAbstract($item['body'], Protocol::ACTIVITYPUB);
1259 if (!empty($content_warning) && empty($item['content-warning'])) {
1260 $item['content-warning'] = BBCode::toPlaintext($content_warning);
1264 $inserted = Post::insert($item['uri-id'], $item);
1266 if ($item['gravity'] == self::GRAVITY_PARENT) {
1267 Post\Thread::insert($item['uri-id'], $item);
1270 // The content of activities normally doesn't matter - except for likes from Misskey
1271 if (!in_array($item['verb'], self::ACTIVITIES) || in_array($item['verb'], [Activity::LIKE, Activity::DISLIKE]) && !empty($item['body']) && (mb_strlen($item['body']) == 1)) {
1272 Post\Content::insert($item['uri-id'], $item);
1275 $item['parent'] = $parent_id;
1277 // Create Diaspora signature
1278 if ($item['origin'] && empty($item['diaspora_signed_text']) && ($item['gravity'] != self::GRAVITY_PARENT)) {
1279 $signed = Diaspora::createCommentSignature($item);
1280 if (!empty($signed)) {
1281 $item['diaspora_signed_text'] = json_encode($signed);
1285 if (!empty($item['diaspora_signed_text'])) {
1286 DBA::replace('diaspora-interaction', ['uri-id' => $item['uri-id'], 'interaction' => $item['diaspora_signed_text']]);
1289 // Attached file links
1290 if (!empty($item['file'])) {
1291 Post\Category::storeTextByURIId($item['uri-id'], $item['uid'], $item['file']);
1294 // Delivery relevant data
1295 $delivery_data = Post\DeliveryData::extractFields($item);
1297 if (!empty($item['origin']) || !empty($item['wall']) || !empty($delivery_data['postopts']) || !empty($delivery_data['inform'])) {
1298 Post\DeliveryData::insert($item['uri-id'], $delivery_data);
1301 // Store tags from the body if this hadn't been handled previously in the protocol classes
1302 if (!Tag::existsForPost($item['uri-id'])) {
1303 Tag::storeFromBody($item['uri-id'], $item['body']);
1306 $condition = ['uri-id' => $item['uri-id'], 'uid' => $item['uid']];
1307 if (Post::exists($condition)) {
1308 Logger::notice('Item is already inserted - aborting', $condition);
1312 $post_user_id = Post\User::insert($item['uri-id'], $item['uid'], $item);
1313 if (!$post_user_id) {
1314 Logger::notice('Post-User is already inserted - aborting', ['uid' => $item['uid'], 'uri-id' => $item['uri-id']]);
1318 if ($item['gravity'] == self::GRAVITY_PARENT) {
1319 $item['post-user-id'] = $post_user_id;
1320 Post\ThreadUser::insert($item['uri-id'], $item['uid'], $item);
1323 Logger::notice('created item', ['post-id' => $post_user_id, 'uid' => $item['uid'], 'network' => $item['network'], 'uri-id' => $item['uri-id'], 'guid' => $item['guid']]);
1325 $posted_item = Post::selectFirst(self::ITEM_FIELDLIST, ['post-user-id' => $post_user_id]);
1326 if (!DBA::isResult($posted_item)) {
1327 // On failure store the data into a spool file so that the "SpoolPost" worker can try again later.
1328 Logger::warning('Could not store item. it will be spooled', ['id' => $post_user_id]);
1329 self::spool($orig_item);
1333 // update the commented timestamp on the parent
1334 if (DI::config()->get('system', 'like_no_comment')) {
1335 // Update when it is a comment
1336 $update_commented = in_array($posted_item['gravity'], [self::GRAVITY_PARENT, self::GRAVITY_COMMENT]);
1338 // Update when it isn't a follow or tag verb
1339 $update_commented = !in_array($posted_item['verb'], [Activity::FOLLOW, Activity::TAG]);
1342 if ($update_commented) {
1343 $fields = ['commented' => DateTimeFormat::utcNow(), 'changed' => DateTimeFormat::utcNow()];
1345 $fields = ['changed' => DateTimeFormat::utcNow()];
1348 Post::update($fields, ['uri-id' => $posted_item['parent-uri-id'], 'uid' => $posted_item['uid']]);
1350 // In that function we check if this is a group post. Additionally we delete the item under certain circumstances
1351 if (self::tagDeliver($posted_item['uid'], $post_user_id)) {
1352 // Get the user information for the logging
1353 $user = User::getById($uid);
1355 Logger::notice('Item had been deleted', ['id' => $post_user_id, 'user' => $uid, 'account-type' => $user['account-type']]);
1360 DI::contentItem()->postProcessPost($posted_item);
1362 Hook::callAll('post_remote_end', $posted_item);
1365 if ($posted_item['gravity'] === self::GRAVITY_PARENT) {
1366 self::addShadow($post_user_id);
1368 self::addShadowPost($post_user_id);
1371 self::updateContact($posted_item);
1373 Post\UserNotification::setNotification($posted_item['uri-id'], $posted_item['uid']);
1375 // Distribute items to users who subscribed to their tags
1376 self::distributeByTags($posted_item);
1378 // Automatically reshare the item if the "remote_self" option is selected
1379 self::autoReshare($posted_item);
1381 $transmit = $notify || ($posted_item['visible'] && ($parent_origin || $posted_item['origin']));
1384 if ($posted_item['uid'] && Contact\User::isBlocked($posted_item['author-id'], $posted_item['uid'])) {
1385 Logger::info('Message from blocked author will not be relayed', ['item' => $posted_item['id'], 'uri' => $posted_item['uri'], 'cid' => $posted_item['author-id']]);
1388 if ($transmit && $posted_item['uid'] && Contact\User::isBlocked($posted_item['owner-id'], $posted_item['uid'])) {
1389 Logger::info('Message from blocked owner will not be relayed', ['item' => $posted_item['id'], 'uri' => $posted_item['uri'], 'cid' => $posted_item['owner-id']]);
1392 if ($transmit && !empty($posted_item['causer-id']) && $posted_item['uid'] && Contact\User::isBlocked($posted_item['causer-id'], $posted_item['uid'])) {
1393 Logger::info('Message from blocked causer will not be relayed', ['item' => $posted_item['id'], 'uri' => $posted_item['uri'], 'cid' => $posted_item['causer-id']]);
1397 // Don't relay participation messages
1398 if (($posted_item['verb'] == Activity::FOLLOW) &&
1399 (!$posted_item['origin'] || ($posted_item['author-id'] != Contact::getPublicIdByUserId($uid)))
1401 Logger::info('Participation messages will not be relayed', ['item' => $posted_item['id'], 'uri' => $posted_item['uri'], 'verb' => $posted_item['verb']]);
1406 if (!empty($source) && ($transmit || DI::config()->get('debug', 'store_source'))) {
1407 Post\Activity::insert($item['uri-id'], $source);
1411 Worker::add(['priority' => $priority, 'dont_fork' => true], 'Notifier', $notify_type, (int)$posted_item['uri-id'], (int)$posted_item['uid']);
1414 // Fill the cache with the rendered content.
1415 if (in_array($posted_item['gravity'], [self::GRAVITY_PARENT, self::GRAVITY_COMMENT]) && ($posted_item['uid'] == 0)) {
1416 self::updateDisplayCache($posted_item['uri-id']);
1420 Post\Engagement::storeFromItem($posted_item);
1423 return $post_user_id;
1427 * Fetch the post reason for a given item array
1429 * @param array $item
1433 public static function getPostReason(array $item): int
1435 $actor = ($item['gravity'] == self::GRAVITY_PARENT) ? $item['owner-id'] : $item['author-id'];
1436 if (empty($item['origin']) && ($item['uid'] != 0) && Contact::isSharing($actor, $item['uid'])) {
1437 return self::PR_FOLLOWER;
1440 if (!empty($item['origin']) && empty($item['post-reason'])) {
1441 return self::PR_LOCAL;
1444 return $item['post-reason'] ?? self::PR_NONE;
1448 * Update the display cache
1450 * @param integer $uri_id
1452 * @throws InternalServerErrorException
1453 * @throws \ImagickException
1455 public static function updateDisplayCache(int $uri_id)
1457 $item = Post::selectFirst(self::DISPLAY_FIELDLIST, ['uri-id' => $uri_id]);
1462 self::prepareBody($item, false, false, true);
1466 * Change the owner of a parent item if it had been shared by a group
1468 * (public) group posts in the new format consist of the regular post by the author
1469 * followed by an announce message sent from the group account.
1470 * Changing the owner helps in grouping group posts.
1472 * @param array $item
1475 private static function setOwnerforResharedItem(array $item)
1477 $parent = Post::selectFirst(
1478 ['id', 'causer-id', 'owner-id', 'author-id', 'author-link', 'origin', 'post-reason'],
1479 ['uri-id' => $item['thr-parent-id'], 'uid' => $item['uid']]
1481 if (!DBA::isResult($parent)) {
1482 Logger::error('Parent not found', ['uri-id' => $item['thr-parent-id'], 'uid' => $item['uid']]);
1486 $author = Contact::selectFirst(['url', 'contact-type', 'network'], ['id' => $item['author-id']]);
1487 if (!DBA::isResult($author)) {
1488 Logger::error('Author not found', ['id' => $item['author-id']]);
1492 $self_contact = Contact::selectFirst(['id'], ['uid' => $item['uid'], 'self' => true]);
1493 $self = !empty($self_contact) ? $self_contact['id'] : 0;
1495 $cid = Contact::getIdForURL($author['url'], $item['uid']);
1496 if (empty($cid) || (!Contact::isSharing($cid, $item['uid']) && ($cid != $self))) {
1497 Logger::info('The resharer is not a following contact: quit', ['resharer' => $author['url'], 'uid' => $item['uid'], 'cid' => $cid]);
1501 if ($author['contact-type'] != Contact::TYPE_COMMUNITY) {
1502 if ($parent['post-reason'] == self::PR_ANNOUNCEMENT) {
1503 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']]);
1507 if (Contact::isSharing($parent['owner-id'], $item['uid'])) {
1508 Logger::info('The resharer is no group: quit', ['resharer' => $item['author-id'], 'owner' => $parent['owner-id'], 'author' => $parent['author-id'], 'uid' => $item['uid']]);
1513 self::update(['post-reason' => self::PR_ANNOUNCEMENT, 'causer-id' => $item['author-id']], ['id' => $parent['id']]);
1514 Logger::info('Set announcement post-reason', ['uri-id' => $item['uri-id'], 'thr-parent-id' => $item['thr-parent-id'], 'uid' => $item['uid']]);
1518 * Distribute the given item to users who subscribed to their tags
1520 * @param array $item Processed item
1522 private static function distributeByTags(array $item)
1524 if (($item['uid'] != 0) || ($item['gravity'] != self::GRAVITY_PARENT) || !in_array($item['network'], Protocol::FEDERATED)) {
1528 foreach (Tag::getUIDListByURIId($item['uri-id']) as $uid => $tags) {
1529 $stored = self::storeForUserByUriId($item['uri-id'], $uid, ['post-reason' => self::PR_TAG]);
1530 Logger::info('Stored item for users', ['uri-id' => $item['uri-id'], 'uid' => $uid, 'stored' => $stored]);
1531 foreach ($tags as $tag) {
1532 $stored = Category::storeFileByURIId($item['uri-id'], $uid, Category::SUBCRIPTION, $tag);
1533 Logger::debug('Stored tag subscription for user', ['uri-id' => $item['uri-id'], 'uid' => $uid, $tag, 'stored' => $stored]);
1539 * Distributes public items to the receivers
1541 * @param integer $itemid Item ID that should be added
1542 * @param string $signed_text Original text (for Diaspora signatures), JSON encoded.
1543 * @throws \Exception
1545 public static function distribute(int $itemid, string $signed_text = '')
1547 $condition = ["`id` IN (SELECT `parent` FROM `post-user-view` WHERE `id` = ?)", $itemid];
1548 $parent = Post::selectFirst(['owner-id'], $condition);
1549 if (!DBA::isResult($parent)) {
1550 Logger::warning('Item not found', ['condition' => $condition]);
1554 // Only distribute public items from native networks
1556 'id' => $itemid, 'uid' => 0,
1557 'network' => array_merge(Protocol::FEDERATED, ['']),
1558 'visible' => true, 'deleted' => false, 'private' => [self::PUBLIC, self::UNLISTED]
1560 $item = Post::selectFirst(array_merge(self::ITEM_FIELDLIST, ['protocol']), $condition);
1561 if (!DBA::isResult($item)) {
1562 Logger::warning('Item not found', ['condition' => $condition]);
1566 $origin = $item['origin'];
1570 /// @todo add a field "pcid" in the contact table that refers to the public contact id.
1571 $owner = DBA::selectFirst('contact', ['url', 'nurl', 'alias'], ['id' => $parent['owner-id']]);
1572 if (!DBA::isResult($owner)) {
1576 $condition = ['nurl' => $owner['nurl'], 'rel' => [Contact::SHARING, Contact::FRIEND]];
1577 $contacts = DBA::select('contact', ['uid'], $condition);
1578 while ($contact = DBA::fetch($contacts)) {
1579 if ($contact['uid'] == 0) {
1583 $users[$contact['uid']] = $contact['uid'];
1585 DBA::close($contacts);
1587 $condition = ['alias' => $owner['url'], 'rel' => [Contact::SHARING, Contact::FRIEND]];
1588 $contacts = DBA::select('contact', ['uid'], $condition);
1589 while ($contact = DBA::fetch($contacts)) {
1590 if ($contact['uid'] == 0) {
1594 $users[$contact['uid']] = $contact['uid'];
1596 DBA::close($contacts);
1598 if (!empty($owner['alias'])) {
1599 $condition = ['nurl' => Strings::normaliseLink($owner['alias']), 'rel' => [Contact::SHARING, Contact::FRIEND]];
1600 $contacts = DBA::select('contact', ['uid'], $condition);
1601 while ($contact = DBA::fetch($contacts)) {
1602 if ($contact['uid'] == 0) {
1606 $users[$contact['uid']] = $contact['uid'];
1608 DBA::close($contacts);
1613 if ($item['uri-id'] != $item['parent-uri-id']) {
1614 $parents = Post::select(['uid', 'origin'], ["`uri-id` = ? AND `uid` != 0", $item['parent-uri-id']]);
1615 while ($parent = Post::fetch($parents)) {
1616 $users[$parent['uid']] = $parent['uid'];
1617 if ($parent['origin'] && !$origin) {
1618 $origin_uid = $parent['uid'];
1621 DBA::close($parents);
1624 foreach ($users as $uid) {
1625 if ($origin_uid == $uid) {
1626 $item['diaspora_signed_text'] = $signed_text;
1628 $item['post-reason'] = self::PR_DISTRIBUTE;
1629 self::storeForUser($item, $uid);
1634 * Store a public item defined by their URI-ID for the given users
1636 * @param integer $uri_id URI-ID of the given item
1637 * @param integer $uid The user that will receive the item entry
1638 * @param array $fields Additional fields to be stored
1639 * @param integer $source_uid User id of the source post
1640 * @return integer stored item id
1642 public static function storeForUserByUriId(int $uri_id, int $uid, array $fields = [], int $source_uid = 0): int
1644 if ($uid == $source_uid) {
1645 Logger::warning('target UID must not be be equal to the source UID', ['uri-id' => $uri_id, 'uid' => $uid]);
1649 $item = Post::selectFirst(array_merge(self::ITEM_FIELDLIST, ['protocol']), ['uri-id' => $uri_id, 'uid' => $source_uid]);
1650 if (!DBA::isResult($item)) {
1651 Logger::warning('Item could not be fetched', ['uri-id' => $uri_id, 'uid' => $source_uid]);
1655 if (($uid != 0) && ($item['gravity'] == self::GRAVITY_PARENT)) {
1656 $owner = User::getOwnerDataById($uid);
1657 if (($owner['contact-type'] == User::ACCOUNT_TYPE_COMMUNITY) && !Tag::isMentioned($uri_id, $owner['url'])) {
1658 Logger::info('Target user is a group but is not mentioned here, thread will not be stored', ['uid' => $uid, 'uri-id' => $uri_id]);
1663 if (($source_uid == 0) && (($item['private'] == self::PRIVATE) || !in_array($item['network'], Protocol::FEDERATED))) {
1664 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']]);
1668 $item['post-reason'] = self::PR_STORED;
1670 $item = array_merge($item, $fields);
1672 if (($uid != 0) && Contact::isSharing(($item['gravity'] == Item::GRAVITY_PARENT) ? $item['owner-id'] : $item['author-id'], $uid)) {
1673 $item['post-reason'] = self::PR_FOLLOWER;
1676 $is_reshare = ($item['gravity'] == self::GRAVITY_ACTIVITY) && ($item['verb'] == Activity::ANNOUNCE);
1678 if (($uid != 0) && (($item['gravity'] == self::GRAVITY_PARENT) || $is_reshare) &&
1679 DI::pConfig()->get($uid, 'system', 'accept_only_sharer') == self::COMPLETION_NONE &&
1680 !in_array($item['post-reason'], [self::PR_FOLLOWER, self::PR_TAG, self::PR_TO, self::PR_CC, self::PR_ACTIVITY, self::PR_AUDIENCE])
1682 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']]);
1686 $causer = $item['causer-id'] ?: $item['author-id'];
1688 if (($uri_id != $item['parent-uri-id']) && ($item['gravity'] == self::GRAVITY_COMMENT) && !Post::exists(['uri-id' => $item['parent-uri-id'], 'uid' => $uid])) {
1689 if (!self::fetchParent($item['parent-uri-id'], $uid, $causer)) {
1690 Logger::info('Parent post had not been added', ['uri-id' => $item['parent-uri-id'], 'uid' => $uid, 'causer' => $causer]);
1693 Logger::info('Fetched parent post', ['uri-id' => $item['parent-uri-id'], 'uid' => $uid, 'causer' => $causer]);
1694 } elseif (($uri_id != $item['thr-parent-id']) && $is_reshare && !Post::exists(['uri-id' => $item['thr-parent-id'], 'uid' => $uid])) {
1695 if (!self::fetchParent($item['thr-parent-id'], $uid, $causer)) {
1696 Logger::info('Thread parent had not been added', ['uri-id' => $item['thr-parent-id'], 'uid' => $uid, 'causer' => $causer]);
1699 Logger::info('Fetched thread parent', ['uri-id' => $item['thr-parent-id'], 'uid' => $uid, 'causer' => $causer]);
1702 $stored = self::storeForUser($item, $uid);
1703 Logger::info('Item stored for user', ['uri-id' => $item['uri-id'], 'uid' => $uid, 'causer' => $causer, 'source-uid' => $source_uid, 'stored' => $stored]);
1708 * Fetch the parent with the given uri-id
1710 * @param integer $uri_id
1711 * @param integer $uid
1712 * @param integer $causer
1716 private static function fetchParent(int $uri_id, int $uid, int $causer): int
1718 // Fetch the origin user for the post
1719 $origin_uid = self::GetOriginUidForUriId($uri_id, $uid);
1720 if (is_null($origin_uid)) {
1721 Logger::info('Origin item was not found', ['uid' => $uid, 'uri-id' => $uri_id]);
1725 return self::storeForUserByUriId($uri_id, $uid, ['causer-id' => $causer, 'post-reason' => self::PR_FETCHED], $origin_uid);
1729 * Returns the origin uid of a post if the given user is allowed to see it.
1735 private static function GetOriginUidForUriId(int $uriid, int $uid)
1737 if (Post::exists(['uri-id' => $uriid, 'uid' => $uid])) {
1741 $post = Post::selectFirst(['uid', 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid', 'private'], ['uri-id' => $uriid, 'origin' => true]);
1742 if (!empty($post)) {
1743 if (in_array($post['private'], [Item::PUBLIC, Item::UNLISTED])) {
1744 return $post['uid'];
1747 $pcid = Contact::getPublicIdByUserId($uid);
1752 foreach (Item::enumeratePermissions($post, true) as $receiver) {
1753 if ($receiver == $pcid) {
1754 return $post['uid'];
1761 if (Post::exists(['uri-id' => $uriid, 'uid' => 0])) {
1765 // When the post belongs to a a group then all group users are allowed to access it
1766 foreach (Tag::getByURIId($uriid, [Tag::MENTION, Tag::EXCLUSIVE_MENTION]) as $tag) {
1767 if (DBA::exists('contact', ['uid' => $uid, 'nurl' => Strings::normaliseLink($tag['url']), 'contact-type' => Contact::TYPE_COMMUNITY])) {
1768 $target_uid = User::getIdForURL($tag['url']);
1769 if (!empty($target_uid)) {
1779 * Store a public item array for the given users
1781 * @param array $item The item entry that will be stored
1782 * @param integer $uid The user that will receive the item entry
1783 * @return integer stored item id
1784 * @throws \Exception
1786 private static function storeForUser(array $item, int $uid): int
1788 $post = Post::selectFirst(['id'], ['uri-id' => $item['uri-id'], 'uid' => $uid]);
1789 if (!empty($post['id'])) {
1790 if (!empty($item['event-id'])) {
1791 $event_post = Post::selectFirst(['event-id'], ['uri-id' => $item['uri-id'], 'uid' => $uid]);
1792 if (!empty($event_post['event-id'])) {
1793 $event = DBA::selectFirst('event', ['edited', 'start', 'finish', 'summary', 'desc', 'location', 'nofinish'], ['id' => $item['event-id']]);
1794 if (!empty($event)) {
1795 // We aren't using "Event::store" here, since we don't want to trigger any further action
1796 $ret = DBA::update('event', $event, ['id' => $event_post['event-id']]);
1797 Logger::info('Event updated', ['uid' => $uid, 'source-event' => $item['event-id'], 'target-event' => $event_post['event-id'], 'ret' => $ret]);
1801 Logger::info('Item already exists', ['uri-id' => $item['uri-id'], 'uid' => $uid, 'id' => $post['id']]);
1805 // Data from the "post-user" table
1807 unset($item['mention']);
1808 unset($item['starred']);
1809 unset($item['unseen']);
1810 unset($item['psid']);
1811 unset($item['pinned']);
1812 unset($item['ignored']);
1813 unset($item['pubmail']);
1814 unset($item['event-id']);
1815 unset($item['hidden']);
1816 unset($item['notification-type']);
1818 // Data from the "post-delivery-data" table
1819 unset($item['postopts']);
1820 unset($item['inform']);
1822 $item['uid'] = $uid;
1823 $item['origin'] = 0;
1827 if ($item['gravity'] == self::GRAVITY_PARENT) {
1828 $contact = DBA::selectFirst('contact', [], ['id' => $item['contact-id'], 'self' => false]);
1829 if (DBA::isResult($contact)) {
1830 $notify = self::isRemoteSelf($contact, $item);
1831 $item['wall'] = (bool)$notify;
1835 $item['contact-id'] = self::contactId($item);
1836 $distributed = self::insert($item, $notify);
1838 if (!$distributed) {
1839 Logger::info("Distributed item wasn't stored", ['uri-id' => $item['uri-id'], 'user' => $uid]);
1841 Logger::info('Distributed item was stored', ['uri-id' => $item['uri-id'], 'user' => $uid, 'stored' => $distributed]);
1843 return $distributed;
1847 * Add a shadow entry for a given item id that is a thread starter
1849 * We store every public item entry additionally with the user id "0".
1850 * This is used for the community page and for the search.
1851 * It is planned that in the future we will store public item entries only once.
1853 * @param integer $itemid Item ID that should be added
1854 * @throws \Exception
1856 private static function addShadow(int $itemid)
1858 $fields = ['uid', 'private', 'visible', 'deleted', 'network', 'uri-id'];
1859 $condition = ['id' => $itemid, 'gravity' => self::GRAVITY_PARENT];
1860 $item = Post::selectFirst($fields, $condition);
1862 if (!DBA::isResult($item)) {
1866 // is it already a copy?
1867 if (($itemid == 0) || ($item['uid'] == 0)) {
1871 // Is it a visible public post?
1872 if (!$item["visible"] || $item["deleted"] || ($item["private"] == self::PRIVATE)) {
1876 // is it an entry from a connector? Only add an entry for natively connected networks
1877 if (!in_array($item["network"], array_merge(Protocol::FEDERATED, ['']))) {
1881 if (Post::exists(['uri-id' => $item['uri-id'], 'uid' => 0])) {
1885 $item = Post::selectFirst(array_merge(self::ITEM_FIELDLIST, ['protocol']), ['id' => $itemid]);
1887 if (DBA::isResult($item)) {
1888 // Preparing public shadow (removing user specific data)
1891 unset($item['parent']);
1892 unset($item['wall']);
1893 unset($item['mention']);
1894 unset($item['origin']);
1895 unset($item['starred']);
1896 unset($item['postopts']);
1897 unset($item['inform']);
1898 unset($item['post-reason']);
1899 if ($item['uri-id'] == $item['parent-uri-id']) {
1900 $item['contact-id'] = $item['owner-id'];
1902 $item['contact-id'] = $item['author-id'];
1905 $public_shadow = self::insert($item);
1907 Logger::info('Stored public shadow', ['thread' => $itemid, 'id' => $public_shadow]);
1912 * Add a shadow entry for a given item id that is a comment
1914 * This function does the same like the function above - but for comments
1916 * @param integer $itemid Item ID that should be added
1917 * @throws \Exception
1919 private static function addShadowPost(int $itemid)
1921 $item = Post::selectFirst(array_merge(self::ITEM_FIELDLIST, ['protocol']), ['id' => $itemid]);
1922 if (!DBA::isResult($item)) {
1926 // Is it a toplevel post?
1927 if ($item['gravity'] == self::GRAVITY_PARENT) {
1928 self::addShadow($itemid);
1932 // Is this a shadow entry?
1933 if ($item['uid'] == 0) {
1937 // Is there a shadow parent?
1938 if (!Post::exists(['uri-id' => $item['parent-uri-id'], 'uid' => 0])) {
1942 // Is there already a shadow entry?
1943 if (Post::exists(['uri-id' => $item['uri-id'], 'uid' => 0])) {
1947 // Save "origin" and "parent" state
1948 $origin = $item['origin'];
1949 $parent = $item['parent'];
1951 // Preparing public shadow (removing user specific data)
1954 unset($item['parent']);
1955 unset($item['wall']);
1956 unset($item['mention']);
1957 unset($item['origin']);
1958 unset($item['starred']);
1959 unset($item['postopts']);
1960 unset($item['inform']);
1961 unset($item['post-reason']);
1962 $item['contact-id'] = Contact::getIdForURL($item['author-link']);
1964 $public_shadow = self::insert($item);
1966 Logger::info('Stored public shadow', ['uri-id' => $item['uri-id'], 'id' => $public_shadow]);
1968 // If this was a comment to a Diaspora post we don't get our comment back.
1969 // This means that we have to distribute the comment by ourselves.
1970 if ($origin && Post::exists(['id' => $parent, 'network' => Protocol::DIASPORA])) {
1971 self::distribute($public_shadow);
1976 * Adds a language specification in a "language" element of given $arr.
1977 * Expects "body" element to exist in $arr.
1979 * @param array $item
1980 * @return string detected language
1981 * @throws \Text_LanguageDetect_Exception
1983 private static function getLanguage(array $item): string
1985 if (!empty($item['language'])) {
1986 return $item['language'];
1989 if (!in_array($item['gravity'], [self::GRAVITY_PARENT, self::GRAVITY_COMMENT]) || empty($item['body'])) {
1993 $languages = self::getLanguageArray(trim($item['title'] . "\n" . $item['body']), 3, $item['uri-id'], $item['author-id']);
1994 if (empty($languages)) {
1998 return json_encode($languages);
2002 * Get a language array from a given text
2004 * @param string $body
2005 * @param integer $count
2006 * @param integer $uri_id
2007 * @param integer $author_id
2010 public static function getLanguageArray(string $body, int $count, int $uri_id = 0, int $author_id = 0): array
2012 $naked_body = BBCode::toSearchText($body, $uri_id);
2014 if ((count(explode(' ', $naked_body)) < 10) && (mb_strlen($naked_body) < 30) && $author_id) {
2015 $author = Contact::selectFirst(['about'], ['id' => $author_id]);
2016 if (!empty($author['about'])) {
2017 $about = BBCode::toSearchText($author['about'], 0);
2018 $about = self::getDominantLanguage($about);
2019 Logger::debug('About field added', ['author' => $author_id, 'body' => $naked_body, 'about' => $about]);
2020 $naked_body .= ' ' . $about;
2024 if (empty($naked_body)) {
2028 $naked_body = self::getDominantLanguage($naked_body);
2030 $availableLanguages = DI::l10n()->getAvailableLanguages(true);
2031 $availableLanguages = DI::l10n()->convertForLanguageDetection($availableLanguages);
2033 $ld = new Language(array_keys($availableLanguages));
2034 $languages = $ld->detect($naked_body)->limit(0, $count)->close() ?: [];
2037 'text' => $naked_body,
2038 'detected' => $languages,
2039 'uri-id' => $uri_id,
2042 Hook::callAll('detect_languages', $data);
2043 $languages = $data['detected'];
2049 * Check if latin or non latin are dominant in the body and only return the dominant one
2051 * @param string $body
2054 private static function getDominantLanguage(string $body): string
2058 for ($i = 0; $i < mb_strlen($body); $i++) {
2059 $character = mb_substr($body, $i, 1);
2060 $ord = mb_ord($character);
2062 // We add the most common characters to both strings.
2063 if (($ord <= 64) || ($ord >= 91 && $ord <= 96) || ($ord >= 123 && $ord <= 191) || in_array($ord, [215, 247]) || ($ord >= 697 && $ord <= 735) || ($ord > 65535)) {
2064 $latin .= $character;
2065 $non_latin .= $character;
2066 } elseif ($ord < 768) {
2067 $latin .= $character;
2069 $non_latin .= $character;
2072 return (mb_strlen($latin) > mb_strlen($non_latin)) ? $latin : $non_latin;
2075 public static function getLanguageMessage(array $item): string
2077 $iso639 = new \Matriphe\ISO639\ISO639;
2079 $used_languages = '';
2080 foreach (json_decode($item['language'], true) as $language => $reliability) {
2081 $used_languages .= $iso639->languageByCode1($language) . ' (' . $language . "): " . number_format($reliability, 5) . '\n';
2083 $used_languages = DI::l10n()->t('Detected languages in this post:\n%s', $used_languages);
2084 return $used_languages;
2088 * Creates an unique guid out of a given uri.
2089 * This function is used for messages outside the fediverse (Connector posts, feeds, Mails, ...)
2090 * Posts that are created on this system are using System::createUUID.
2091 * Received ActivityPub posts are using Processor::getGUIDByURL.
2093 * @param string $uri uri of an item entry
2094 * @param string|null $host hostname for the GUID prefix
2095 * @return string Unique guid
2096 * @throws \Exception
2098 public static function guidFromUri(string $uri, string $host = null): string
2100 // Our regular guid routine is using this kind of prefix as well
2101 // We have to avoid that different routines could accidentally create the same value
2102 $parsed = parse_url($uri);
2104 // Remove the scheme to make sure that "https" and "http" doesn't make a difference
2105 unset($parsed['scheme']);
2107 $hostPart = $host ?: $parsed['host'] ?? '';
2109 Logger::warning('Empty host GUID part', ['uri' => $uri, 'host' => $host, 'parsed' => $parsed, 'callstack' => System::callstack(10)]);
2112 // Glue it together to be able to make a hash from it
2113 if (!empty($parsed)) {
2114 $host_id = implode('/', $parsed);
2119 // Use a mixture of several hashes to provide some GUID like experience
2120 return hash('crc32', $hostPart) . '-' . hash('joaat', $host_id) . '-' . hash('fnv164', $host_id);
2124 * generate an unique URI
2126 * @param string $guid An existing GUID (Otherwise it will be generated)
2129 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2131 public static function newURI(string $guid = ''): string
2134 $guid = System::createUUID();
2137 return DI::baseUrl() . '/objects/' . $guid;
2141 * Set "success_update" and "last-item" to the date of the last time we heard from this contact
2143 * This can be used to filter for inactive contacts.
2144 * Only do this for public postings to avoid privacy problems, since poco data is public.
2145 * Don't set this value if it isn't from the owner (could be an author that we don't know)
2147 * @param array $arr Contains the just posted item record
2148 * @throws \Exception
2150 private static function updateContact(array $arr)
2152 // Unarchive the author
2153 $contact = DBA::selectFirst('contact', [], ['id' => $arr["author-id"]]);
2154 if (DBA::isResult($contact)) {
2155 Contact::unmarkForArchival($contact);
2158 // Unarchive the contact if it's not our own contact
2159 $contact = DBA::selectFirst('contact', [], ['id' => $arr["contact-id"], 'self' => false]);
2160 if (DBA::isResult($contact)) {
2161 Contact::unmarkForArchival($contact);
2164 /// @todo On private posts we could obfuscate the date
2165 $update = ($arr['private'] != self::PRIVATE) || in_array($arr['network'], Protocol::FEDERATED);
2167 // Is it a group? Then we don't care about the rules from above
2168 if (!$update && in_array($arr["network"], [Protocol::ACTIVITYPUB, Protocol::DFRN]) && ($arr["parent-uri-id"] === $arr["uri-id"])) {
2169 if (DBA::exists('contact', ['id' => $arr['contact-id'], 'forum' => true])) {
2175 // The "self" contact id is used (for example in the connectors) when the contact is unknown
2176 // So we have to ensure to only update the last item when it had been our own post,
2177 // or it had been done by a "regular" contact.
2178 if (!empty($arr['wall'])) {
2179 $condition = ['id' => $arr['contact-id']];
2181 $condition = ['id' => $arr['contact-id'], 'self' => false];
2183 Contact::update(['failed' => false, 'local-data' => true, 'success_update' => $arr['received'], 'last-item' => $arr['received']], $condition);
2185 // Now do the same for the system wide contacts with uid=0
2186 if ($arr['private'] != self::PRIVATE) {
2188 ['failed' => false, 'local-data' => true, 'success_update' => $arr['received'], 'last-item' => $arr['received']],
2189 ['id' => $arr['owner-id']]
2192 if ($arr['owner-id'] != $arr['author-id']) {
2194 ['failed' => false, 'local-data' => true, 'success_update' => $arr['received'], 'last-item' => $arr['received']],
2195 ['id' => $arr['author-id']]
2201 public static function setHashtags(string $body): string
2203 $body = BBCode::performWithEscapedTags($body, ['noparse', 'pre', 'code', 'img'], function ($body) {
2204 $tags = BBCode::getTags($body);
2207 if (!count($tags)) {
2211 // This sorting is important when there are hashtags that are part of other hashtags
2212 // Otherwise there could be problems with hashtags like #test and #test2
2213 // Because of this we are sorting from the longest to the shortest tag.
2214 usort($tags, function ($a, $b) {
2215 return strlen($b) <=> strlen($a);
2218 $URLSearchString = "^\[\]";
2220 // All hashtags should point to the home server if "local_tags" is activated
2221 if (DI::config()->get('system', 'local_tags')) {
2222 $body = preg_replace(
2223 "/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
2224 "#[url=" . DI::baseUrl() . "/search?tag=$2]$2[/url]",
2229 // mask hashtags inside of url, bookmarks and attachments to avoid urls in urls
2230 $body = preg_replace_callback(
2231 "/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
2233 return ("[url=" . str_replace("#", "#", $match[1]) . "]" . str_replace("#", "#", $match[2]) . "[/url]");
2238 $body = preg_replace_callback(
2239 "/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism",
2241 return ("[bookmark=" . str_replace("#", "#", $match[1]) . "]" . str_replace("#", "#", $match[2]) . "[/bookmark]");
2246 $body = preg_replace_callback(
2247 "/\[attachment (.*?)\](.*?)\[\/attachment\]/ism",
2249 return ("[attachment " . str_replace("#", "#", $match[1]) . "]" . $match[2] . "[/attachment]");
2254 // Repair recursive urls
2255 $body = preg_replace(
2256 "/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
2261 foreach ($tags as $tag) {
2262 if ((strpos($tag, '#') !== 0) || strpos($tag, '[url=') || strlen($tag) < 2 || $tag[1] == '#') {
2266 $basetag = str_replace('_', ' ', substr($tag, 1));
2267 $newtag = '#[url=' . DI::baseUrl() . '/search?tag=' . $basetag . ']' . $basetag . '[/url]';
2269 $body = str_replace($tag, $newtag, $body);
2272 // Convert back the masked hashtags
2273 $body = str_replace("#", "#", $body);
2282 * look for mention tags and setup a second delivery chain for group/community posts if appropriate
2285 * @param int $item_id
2286 * @return boolean true if item was deleted, else false
2287 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2288 * @throws \ImagickException
2290 private static function tagDeliver(int $uid, int $item_id): bool
2292 $owner = User::getOwnerDataById($uid);
2293 if (!DBA::isResult($owner)) {
2294 Logger::warning('User not found, quitting here.', ['uid' => $uid]);
2298 if ($owner['contact-type'] != User::ACCOUNT_TYPE_COMMUNITY) {
2299 Logger::debug('Owner is no community, quitting here.', ['uid' => $uid, 'id' => $item_id]);
2303 $item = Post::selectFirst(self::ITEM_FIELDLIST, ['id' => $item_id, 'gravity' => [self::GRAVITY_PARENT, self::GRAVITY_COMMENT], 'origin' => false]);
2304 if (!DBA::isResult($item)) {
2305 Logger::debug('Post is an activity or origin or not found at all, quitting here.', ['id' => $item_id]);
2309 if ($item['gravity'] == self::GRAVITY_PARENT) {
2310 if (Tag::isMentioned($item['uri-id'], $owner['url'])) {
2311 Logger::info('Mention found in tag.', ['uri' => $item['uri'], 'uid' => $uid, 'id' => $item_id, 'uri-id' => $item['uri-id'], 'guid' => $item['guid']]);
2313 Logger::info('Top-level post without mention is deleted.', ['uri' => $item['uri'], $uid, 'id' => $item_id, 'uri-id' => $item['uri-id'], 'guid' => $item['guid']]);
2314 Post\User::delete(['uri-id' => $item['uri-id'], 'uid' => $item['uid']]);
2318 $arr = ['item' => $item, 'user' => $owner];
2320 Hook::callAll('tagged', $arr);
2322 if (Tag::isMentioned($item['parent-uri-id'], $owner['url'])) {
2323 Logger::info('Mention found in parent tag.', ['uri' => $item['uri'], 'uid' => $uid, 'id' => $item_id, 'uri-id' => $item['uri-id'], 'guid' => $item['guid']]);
2325 Logger::debug('No mentions found in parent, quitting here.', ['id' => $item_id, 'uri-id' => $item['uri-id'], 'guid' => $item['guid']]);
2330 Logger::info('Community post will be distributed', ['uri' => $item['uri'], 'uid' => $uid, 'id' => $item_id, 'uri-id' => $item['uri-id'], 'guid' => $item['guid']]);
2332 if ($owner['page-flags'] == User::PAGE_FLAGS_PRVGROUP) {
2334 $allow_gid = '<' . Circle::FOLLOWERS . '>';
2337 self::performActivity($item['id'], 'announce', $uid, $allow_cid, $allow_gid, $deny_cid, $deny_gid);
2339 self::performActivity($item['id'], 'announce', $uid);
2342 Logger::info('Community post had been distributed', ['uri' => $item['uri'], 'uid' => $uid, 'id' => $item_id, 'uri-id' => $item['uri-id'], 'guid' => $item['guid']]);
2347 * Automatically reshare the item if the "remote_self" option is selected
2349 * @param array $item
2352 private static function autoReshare(array $item)
2354 if ($item['gravity'] != self::GRAVITY_PARENT) {
2358 $cdata = Contact::getPublicAndUserContactID($item['author-id'], $item['uid']);
2359 if (empty($cdata['user']) || ($cdata['user'] != $item['contact-id'])) {
2363 if (!DBA::exists('contact', ['id' => $cdata['user'], 'remote_self' => LocalRelationship::MIRROR_NATIVE_RESHARE])) {
2367 if (!in_array($item['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN])) {
2371 if (User::getById($item['uid'], ['blocked'])['blocked'] ?? false) {
2375 Logger::info('Automatically reshare item', ['uid' => $item['uid'], 'id' => $item['id'], 'guid' => $item['guid'], 'uri-id' => $item['uri-id']]);
2377 self::performActivity($item['id'], 'announce', $item['uid']);
2380 public static function isRemoteSelf(array $contact, array &$datarray): bool
2382 if ($contact['remote_self'] != LocalRelationship::MIRROR_OWN_POST) {
2386 // Prevent the forwarding of posts that are forwarded
2387 if (!empty($datarray['extid']) && ($datarray['extid'] == Protocol::DFRN)) {
2388 Logger::info('Already forwarded');
2392 // Prevent to forward already forwarded posts
2393 if ($datarray['app'] == DI::baseUrl()->getHost()) {
2394 Logger::info('Already forwarded (second test)');
2398 // Only forward posts
2399 if ($datarray['verb'] != Activity::POST) {
2400 Logger::info('No post');
2404 if (($contact['network'] != Protocol::FEED) && ($datarray['private'] == self::PRIVATE)) {
2405 Logger::info('Not public');
2409 if (User::getById($contact['uid'], ['blocked'])['blocked'] ?? false) {
2410 Logger::info('User is blocked', ['contact' => $contact]);
2414 $datarray2 = $datarray;
2415 Logger::info('remote-self start', ['contact' => $contact['url'], 'remote_self' => $contact['remote_self'], 'item' => $datarray]);
2417 $self = DBA::selectFirst(
2419 ['id', 'name', 'url', 'thumb'],
2420 ['uid' => $contact['uid'], 'self' => true]
2422 if (!DBA::isResult($self)) {
2423 Logger::error('Self contact not found', ['uid' => $contact['uid']]);
2427 $datarray['contact-id'] = $self['id'];
2429 $datarray['author-name'] = $datarray['owner-name'] = $self['name'];
2430 $datarray['author-link'] = $datarray['owner-link'] = $self['url'];
2431 $datarray['author-avatar'] = $datarray['owner-avatar'] = $self['thumb'];
2433 unset($datarray['edited']);
2435 unset($datarray['network']);
2436 unset($datarray['owner-id']);
2437 unset($datarray['author-id']);
2439 if ($contact['network'] != Protocol::FEED) {
2440 $old_uri_id = $datarray['uri-id'] ?? 0;
2441 $datarray['guid'] = System::createUUID();
2442 unset($datarray['plink']);
2443 $datarray['uri'] = self::newURI($datarray['guid']);
2444 $datarray['uri-id'] = ItemURI::getIdByURI($datarray['uri']);
2445 $datarray['extid'] = Protocol::DFRN;
2446 $urlpart = parse_url($datarray2['author-link']);
2447 $datarray['app'] = $urlpart['host'];
2448 if (!empty($old_uri_id)) {
2449 Post\Media::copy($old_uri_id, $datarray['uri-id']);
2452 unset($datarray['parent-uri']);
2453 unset($datarray['thr-parent']);
2455 // Store the original post
2456 $result = self::insert($datarray2);
2457 Logger::info('remote-self post original item', ['contact' => $contact['url'], 'result' => $result, 'item' => $datarray2]);
2459 $datarray['private'] = self::PUBLIC;
2460 $datarray['app'] = 'Feed';
2464 return (bool)$result;
2471 * @param array $item
2474 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2475 * @throws \ImagickException
2477 public static function fixPrivatePhotos(string $s, int $uid, array $item = null, int $cid = 0): string
2479 if (DI::config()->get('system', 'disable_embedded')) {
2483 Logger::info('check for photos');
2484 $site = substr(DI::baseUrl(), strpos(DI::baseUrl(), '://'));
2489 $img_start = strpos($orig_body, '[img');
2490 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
2491 $img_len = ($img_start !== false ? strpos(substr($orig_body, $img_start + $img_st_close + 1), '[/img]') : false);
2493 while (($img_st_close !== false) && ($img_len !== false)) {
2494 $img_st_close++; // make it point to AFTER the closing bracket
2495 $image = substr($orig_body, $img_start + $img_st_close, $img_len);
2497 Logger::info('found photo', ['image' => $image]);
2499 if (stristr($image, $site . '/photo/')) {
2500 // Only embed locally hosted photos
2502 $i = basename($image);
2503 $i = str_replace(['.jpg', '.png', '.gif'], ['', '', ''], $i);
2504 $x = strpos($i, '-');
2507 $res = substr($i, $x + 1);
2508 $i = substr($i, 0, $x);
2509 $photo = Photo::getPhotoForUser($uid, $i, $res);
2510 if (DBA::isResult($photo)) {
2512 * Check to see if we should replace this photo link with an embedded image
2513 * 1. No need to do so if the photo is public
2514 * 2. If there's a contact-id provided, see if they're in the access list
2515 * for the photo. If so, embed it.
2516 * 3. Otherwise, if we have an item, see if the item permissions match the photo
2517 * permissions, regardless of order but first check to see if they're an exact
2518 * match to save some processing overhead.
2520 if (self::hasPermissions($photo)) {
2522 $recips = self::enumeratePermissions($photo);
2523 if (in_array($cid, $recips)) {
2527 if (self::samePermissions($uid, $item, $photo)) {
2533 $photo_img = Photo::getImageForPhoto($photo);
2534 // If a custom width and height were specified, apply before embedding
2535 if (preg_match("/\[img\=([0-9]*)x([0-9]*)\]/is", substr($orig_body, $img_start, $img_st_close), $match)) {
2536 Logger::info('scaling photo');
2538 $width = intval($match[1]);
2539 $height = intval($match[2]);
2541 $photo_img->scaleDown(max($width, $height));
2544 $data = $photo_img->asString();
2545 $type = $photo_img->getType();
2547 Logger::info('replacing photo');
2548 $image = 'data:' . $type . ';base64,' . base64_encode($data);
2549 Logger::debug('replaced', ['image' => $image]);
2555 $new_body = $new_body . substr($orig_body, 0, $img_start + $img_st_close) . $image . '[/img]';
2556 $orig_body = substr($orig_body, $img_start + $img_st_close + $img_len + strlen('[/img]'));
2557 if ($orig_body === false) {
2561 $img_start = strpos($orig_body, '[img');
2562 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
2563 $img_len = ($img_start !== false ? strpos(substr($orig_body, $img_start + $img_st_close + 1), '[/img]') : false);
2566 $new_body = $new_body . $orig_body;
2571 private static function hasPermissions(array $obj)
2573 return !empty($obj['allow_cid']) || !empty($obj['allow_gid']) ||
2574 !empty($obj['deny_cid']) || !empty($obj['deny_gid']);
2577 // @TODO $uid is unused parameter
2578 private static function samePermissions($uid, array $obj1, array $obj2): bool
2580 // first part is easy. Check that these are exactly the same.
2581 if (($obj1['allow_cid'] == $obj2['allow_cid'])
2582 && ($obj1['allow_gid'] == $obj2['allow_gid'])
2583 && ($obj1['deny_cid'] == $obj2['deny_cid'])
2584 && ($obj1['deny_gid'] == $obj2['deny_gid'])
2589 // This is harder. Parse all the permissions and compare the resulting set.
2590 $recipients1 = self::enumeratePermissions($obj1);
2591 $recipients2 = self::enumeratePermissions($obj2);
2595 /// @TODO Comparison of arrays, maybe use array_diff_assoc() here?
2596 return ($recipients1 == $recipients2);
2600 * Returns an array of contact-ids that are allowed to see this object
2602 * @param array $obj Item array with at least uid, allow_cid, allow_gid, deny_cid and deny_gid
2603 * @param bool $check_dead Prunes unavailable contacts from the result
2604 * @param bool $expand_followers Expand the list of followers
2606 * @throws \Exception
2608 public static function enumeratePermissions(array $obj, bool $check_dead = false, bool $expand_followers = true): array
2610 $aclFormatter = DI::aclFormatter();
2612 if (!$expand_followers && (!empty($obj['deny_cid']) || !empty($obj['deny_gid']))) {
2613 $expand_followers = true;
2616 $allow_people = $aclFormatter->expand($obj['allow_cid']);
2617 $allow_circles = Circle::expand($obj['uid'], $aclFormatter->expand($obj['allow_gid']), $check_dead, $expand_followers);
2618 $deny_people = $aclFormatter->expand($obj['deny_cid']);
2619 $deny_circles = Circle::expand($obj['uid'], $aclFormatter->expand($obj['deny_gid']), $check_dead);
2620 $recipients = array_unique(array_merge($allow_people, $allow_circles));
2621 $deny = array_unique(array_merge($deny_people, $deny_circles));
2622 $recipients = array_diff($recipients, $deny);
2626 public static function expire(int $uid, int $days, string $network = "", bool $force = false)
2628 if (!$uid || ($days < 1)) {
2633 "`uid` = ? AND NOT `deleted` AND `gravity` = ?",
2634 $uid, self::GRAVITY_PARENT
2638 * $expire_network_only = save your own wall posts
2639 * and just expire conversations started by others
2641 $expire_network_only = DI::pConfig()->get($uid, 'expire', 'network_only', false);
2643 if ($expire_network_only) {
2644 $condition[0] .= " AND NOT `wall`";
2647 if ($network != "") {
2648 $condition[0] .= " AND `network` = ?";
2649 $condition[] = $network;
2652 $condition[0] .= " AND `received` < ?";
2653 $condition[] = DateTimeFormat::utc('now - ' . $days . ' day');
2655 $items = Post::select(['resource-id', 'starred', 'id', 'post-type', 'uid', 'uri-id'], $condition);
2657 if (!DBA::isResult($items)) {
2661 $expire_items = (bool)DI::pConfig()->get($uid, 'expire', 'items', true);
2663 // Forcing expiring of items - but not notes and marked items
2665 $expire_items = true;
2668 $expire_notes = (bool)DI::pConfig()->get($uid, 'expire', 'notes', true);
2669 $expire_starred = (bool)DI::pConfig()->get($uid, 'expire', 'starred', true);
2670 $expire_photos = (bool)DI::pConfig()->get($uid, 'expire', 'photos', false);
2674 $priority = DI::config()->get('system', 'expire-notify-priority');
2676 while ($item = Post::fetch($items)) {
2677 // don't expire filed items
2678 if (DBA::exists('post-category', ['uri-id' => $item['uri-id'], 'uid' => $item['uid'], 'type' => Post\Category::FILE])) {
2682 // Only expire posts, not photos and photo comments
2684 if (!$expire_photos && !empty($item['resource-id'])) {
2686 } elseif (!$expire_starred && intval($item['starred'])) {
2688 } elseif (!$expire_notes && ($item['post-type'] == self::PT_PERSONAL_NOTE)) {
2690 } elseif (!$expire_items && ($item['post-type'] != self::PT_PERSONAL_NOTE)) {
2694 self::markForDeletionById($item['id'], $priority);
2699 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]);
2702 public static function firstPostDate(int $uid, bool $wall = false)
2704 $user = User::getById($uid, ['register_date']);
2710 "`uid` = ? AND `wall` = ? AND NOT `deleted` AND `visible` AND `received` >= ?",
2711 $uid, $wall, $user['register_date']
2713 $params = ['order' => ['received' => false]];
2714 $thread = Post::selectFirstThread(['received'], $condition, $params);
2715 if (DBA::isResult($thread)) {
2716 $postdate = substr(DateTimeFormat::local($thread['received']), 0, 10);
2723 * add/remove activity to an item
2725 * Toggle activities as like,dislike,attend of an item
2727 * @param int $item_id
2728 * @param string $verb
2729 * Activity verb. One of
2730 * like, unlike, dislike, undislike, attendyes, unattendyes,
2731 * attendno, unattendno, attendmaybe, unattendmaybe,
2732 * announce, unannounce
2734 * @param string $allow_cid
2735 * @param string $allow_gid
2736 * @param string $deny_cid
2737 * @param string $deny_gid
2739 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2740 * @throws \ImagickException
2741 * @hook 'post_local_end'
2743 * 'post_id' => ID of posted item
2745 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
2751 Logger::notice('Start create activity', ['verb' => $verb, 'item' => $item_id, 'user' => $uid]);
2753 $item = Post::selectFirst(self::ITEM_FIELDLIST, ['id' => $item_id]);
2754 if (!DBA::isResult($item)) {
2755 Logger::warning('Post had not been fetched', ['id' => $item_id]);
2759 $uri_id = $item['uri-id'];
2761 if (!in_array($item['uid'], [0, $uid])) {
2765 if (!Post::exists(['uri-id' => $item['parent-uri-id'], 'uid' => $uid])) {
2766 $stored = self::storeForUserByUriId($item['parent-uri-id'], $uid, ['post-reason' => Item::PR_ACTIVITY]);
2767 if (($item['parent-uri-id'] == $item['uri-id']) && !empty($stored)) {
2768 $item = Post::selectFirst(self::ITEM_FIELDLIST, ['id' => $stored]);
2769 if (!DBA::isResult($item)) {
2770 Logger::info('Could not fetch just created item - should not happen', ['stored' => $stored, 'uid' => $uid, 'uri-id' => $uri_id]);
2776 // Retrieves the local post owner
2777 $owner = User::getOwnerDataById($uid);
2778 if (empty($owner)) {
2779 Logger::info('Empty owner for user', ['uid' => $uid]);
2783 // Retrieve the current logged in user's public contact
2784 $author_id = Contact::getPublicIdByUserId($uid);
2785 if (empty($author_id)) {
2786 Logger::info('Empty public contact');
2794 $activity = Activity::LIKE;
2798 $activity = Activity::DISLIKE;
2802 $activity = Activity::ATTEND;
2806 $activity = Activity::ATTENDNO;
2809 case 'unattendmaybe':
2810 $activity = Activity::ATTENDMAYBE;
2814 $activity = Activity::FOLLOW;
2818 $activity = Activity::ANNOUNCE;
2821 Logger::warning('unknown verb', ['verb' => $verb, 'item' => $item_id]);
2825 $mode = Strings::startsWith($verb, 'un') ? 'delete' : 'create';
2827 // Enable activity toggling instead of on/off
2828 $event_verb_flag = $activity === Activity::ATTEND || $activity === Activity::ATTENDNO || $activity === Activity::ATTENDMAYBE;
2830 // Look for an existing verb row
2831 // Event participation activities are mutually exclusive, only one of them can exist at all times.
2832 if ($event_verb_flag) {
2833 $verbs = [Activity::ATTEND, Activity::ATTENDNO, Activity::ATTENDMAYBE];
2835 // Translate to the index based activity index
2837 foreach ($verbs as $verb) {
2838 $vids[] = Verb::getID($verb);
2841 $vids = Verb::getID($activity);
2845 'vid' => $vids, 'deleted' => false, 'gravity' => self::GRAVITY_ACTIVITY,
2846 'author-id' => $author_id, 'uid' => $uid, 'thr-parent-id' => $uri_id
2848 $like_item = Post::selectFirst(['id', 'guid', 'verb'], $condition);
2850 if (DBA::isResult($like_item)) {
2852 * Truth table for existing activities
2854 * | Inputs || Outputs |
2855 * |----------------------------||-------------------|
2856 * | Mode | Event | Same verb || Delete? | Return? |
2857 * |--------|-------|-----------||---------|---------|
2858 * | create | Yes | Yes || No | Yes |
2859 * | create | Yes | No || Yes | No |
2860 * | create | No | Yes || No | Yes |
2861 * | create | No | No || N/A†|
2862 * | delete | Yes | Yes || Yes | N/A‡ |
2863 * | delete | Yes | No || No | N/A‡ |
2864 * | delete | No | Yes || Yes | N/A‡ |
2865 * | delete | No | No || N/A†|
2866 * |--------|-------|-----------||---------|---------|
2867 * | A | B | C || A xor C | !B or C |
2869 * †Can't happen: It's impossible to find an existing non-event activity without
2870 * the same verb because we are only looking for this single verb.
2872 * ‡ The "mode = delete" is returning early whether an existing activity was found or not.
2874 if ($mode == 'create' xor $like_item['verb'] == $activity) {
2875 self::markForDeletionById($like_item['id']);
2878 if (!$event_verb_flag || $like_item['verb'] == $activity) {
2883 // No need to go further if we aren't creating anything
2884 if ($mode == 'delete') {
2888 $objtype = $item['resource-id'] ? Activity\ObjectType::IMAGE : Activity\ObjectType::NOTE;
2891 'guid' => System::createUUID(),
2892 'uri' => self::newURI(),
2894 'contact-id' => $owner['id'],
2895 'wall' => $item['wall'],
2897 'network' => Protocol::DFRN,
2898 'protocol' => Conversation::PARCEL_DIRECT,
2899 'direction' => Conversation::PUSH,
2900 'gravity' => self::GRAVITY_ACTIVITY,
2901 'parent' => $item['id'],
2902 'thr-parent' => $item['uri'],
2903 'owner-id' => $author_id,
2904 'author-id' => $author_id,
2905 'body' => $activity,
2906 'verb' => $activity,
2907 'object-type' => $objtype,
2908 'allow_cid' => $allow_cid ?? $item['allow_cid'],
2909 'allow_gid' => $allow_gid ?? $item['allow_gid'],
2910 'deny_cid' => $deny_cid ?? $item['deny_cid'],
2911 'deny_gid' => $deny_gid ?? $item['deny_gid'],
2916 if (in_array($activity, [Activity::LIKE, Activity::DISLIKE])) {
2917 $signed = Diaspora::createLikeSignature($uid, $new_item);
2918 if (!empty($signed)) {
2919 $new_item['diaspora_signed_text'] = json_encode($signed);
2923 self::insert($new_item, true);
2925 // If the parent item isn't visible then set it to visible
2926 // @todo Check if this is still needed
2927 if (!$item['visible']) {
2928 self::update(['visible' => true], ['id' => $item['id']]);
2934 * Fetch the SQL condition for the given user id
2936 * @param integer $owner_id User ID for which the permissions should be fetched
2937 * @return array condition
2939 public static function getPermissionsConditionArrayByUserId(int $owner_id): array
2941 $local_user = DI::userSession()->getLocalUserId();
2942 $remote_user = DI::userSession()->getRemoteContactID($owner_id);
2944 // default permissions - anonymous user
2945 $condition = ["`private` != ?", self::PRIVATE];
2947 if ($local_user && ($local_user == $owner_id)) {
2948 // Profile owner - everything is visible
2950 } elseif ($remote_user) {
2951 // Authenticated visitor - fetch the matching permissionsets
2952 $permissionSets = DI::permissionSet()->selectByContactId($remote_user, $owner_id);
2955 "(`private` != ? OR (`private` = ? AND `wall`
2956 AND `psid` IN (" . implode(', ', array_fill(0, count($set), '?')) . ")))",
2957 self::PRIVATE, self::PRIVATE
2959 $condition = array_merge($condition, $permissionSets->column('id'));
2967 * Get a permission SQL string for the given user
2969 * @param int $owner_id
2970 * @param string $table
2973 public static function getPermissionsSQLByUserId(int $owner_id, string $table = ''): string
2975 $local_user = DI::userSession()->getLocalUserId();
2976 $remote_user = DI::userSession()->getRemoteContactID($owner_id);
2978 if (!empty($table)) {
2979 $table = DBA::quoteIdentifier($table) . '.';
2983 * Construct permissions
2985 * default permissions - anonymous user
2987 $sql = sprintf(" AND " . $table . "`private` != %d", self::PRIVATE);
2989 // Profile owner - everything is visible
2990 if ($local_user && ($local_user == $owner_id)) {
2992 } elseif ($remote_user) {
2994 * Authenticated visitor. Unless pre-verified,
2995 * check that the contact belongs to this $owner_id
2996 * and load the circles the visitor belongs to.
2997 * If pre-verified, the caller is expected to have already
2998 * done this and passed the circles into this function.
3000 $permissionSets = DI::permissionSet()->selectByContactId($remote_user, $owner_id);
3003 $sql_set = sprintf(" OR (" . $table . "`private` = %d AND " . $table . "`wall` AND " . $table . "`psid` IN (", self::PRIVATE) . implode(',', $permissionSets->column('id')) . "))";
3008 $sql = sprintf(" AND (" . $table . "`private` != %d", self::PRIVATE) . $sql_set . ")";
3015 * get translated item type
3017 * @param array $item
3018 * @param \Friendica\Core\L10n $l10n
3021 public static function postType(array $item, \Friendica\Core\L10n $l10n): string
3023 if (!empty($item['event-id'])) {
3024 return $l10n->t('event');
3025 } elseif (!empty($item['resource-id'])) {
3026 return $l10n->t('photo');
3027 } elseif ($item['gravity'] == self::GRAVITY_ACTIVITY) {
3028 return $l10n->t('activity');
3029 } elseif ($item['gravity'] == self::GRAVITY_COMMENT) {
3030 return $l10n->t('comment');
3033 return $l10n->t('post');
3037 * Sets the "rendered-html" field of the provided item
3039 * Body is preserved to avoid side-effects as we modify it just-in-time for spoilers and private image links
3041 * @param array $item
3043 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3044 * @todo Remove reference, simply return "rendered-html" and "rendered-hash"
3046 private static function putInCache(&$item)
3048 // Save original body to prevent addons to modify it
3049 $body = $item['body'];
3051 $rendered_hash = $item['rendered-hash'] ?? '';
3052 $rendered_html = $item['rendered-html'] ?? '';
3055 $rendered_hash == ''
3056 || $rendered_html == ''
3057 || $rendered_hash != hash('md5', BBCode::VERSION . '::' . $body)
3058 || DI::config()->get('system', 'ignore_cache')
3060 $item['rendered-html'] = BBCode::convertForUriId($item['uri-id'], $item['body']);
3061 $item['rendered-hash'] = hash('md5', BBCode::VERSION . '::' . $body);
3063 $hook_data = ['item' => $item, 'rendered-html' => $item['rendered-html'], 'rendered-hash' => $item['rendered-hash']];
3064 Hook::callAll('put_item_in_cache', $hook_data);
3065 $item['rendered-html'] = $hook_data['rendered-html'];
3066 $item['rendered-hash'] = $hook_data['rendered-hash'];
3069 // Update if the generated values differ from the existing ones
3070 if ((($rendered_hash != $item['rendered-hash']) || ($rendered_html != $item['rendered-html'])) && !empty($item['id'])) {
3073 'rendered-html' => $item['rendered-html'],
3074 'rendered-hash' => $item['rendered-hash']
3076 ['id' => $item['id']]
3081 $item['body'] = $body;
3085 * Given an item array, convert the body element from bbcode to html and add smilie icons.
3086 * If attach is true, also add icons for item attachments.
3088 * @param array $item Record from item table
3089 * @param boolean $attach If true, add icons for item attachments as well
3090 * @param boolean $is_preview Whether this is a preview
3091 * @param boolean $only_cache Whether only cached HTML should be updated
3092 * @return string item body html
3093 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3094 * @throws \ImagickException
3095 * @hook prepare_body_init item array before any work
3096 * @hook prepare_body_content_filter ('item'=>item array, 'filter_reasons'=>string array) before first bbcode to html
3097 * @hook prepare_body ('item'=>item array, 'html'=>body string, 'is_preview'=>boolean, 'filter_reasons'=>string array) after first bbcode to html
3098 * @hook prepare_body_final ('item'=>item array, 'html'=>body string) after attach icons and blockquote special case handling (spoiler, author)
3100 public static function prepareBody(array &$item, bool $attach = false, bool $is_preview = false, bool $only_cache = false): string
3103 Hook::callAll('prepare_body_init', $item);
3106 // In order to provide theme developers more possibilities, event items
3107 // are treated differently.
3108 if ($item['object-type'] === Activity\ObjectType::EVENT && isset($item['event-id'])) {
3109 $ev = Event::getItemHTML($item);
3113 $tags = Tag::populateFromItem($item);
3115 $item['tags'] = $tags['tags'];
3116 $item['hashtags'] = $tags['hashtags'];
3117 $item['mentions'] = $tags['mentions'];
3120 $item['body'] = preg_replace("#\s*\[attachment .*?].*?\[/attachment]\s*#ism", "\n", $item['body']);
3121 $item['body'] = Post\Media::removeFromEndOfBody($item['body'] ?? '');
3122 $item['body'] = Post\Media::replaceImage($item['body']);
3125 $body = $item['body'];
3127 $item['body'] = preg_replace("#\s*\[attachment .*?].*?\[/attachment]\s*#ism", "\n", $item['body']);
3130 $fields = ['uri-id', 'uri', 'body', 'title', 'author-name', 'author-link', 'author-avatar', 'guid', 'created', 'plink', 'network', 'has-media', 'quote-uri-id', 'post-type'];
3134 $quote_shared_links = [];
3136 $shared = DI::contentItem()->getSharedPost($item, $fields);
3137 if (!empty($shared['post'])) {
3138 $shared_item = $shared['post'];
3139 $shared_item['body'] = Post\Media::removeFromEndOfBody($shared_item['body']);
3140 $shared_item['body'] = Post\Media::replaceImage($shared_item['body']);
3141 $quote_uri_id = $shared['post']['uri-id'];
3142 $shared_links[] = strtolower($shared['post']['uri']);
3143 $item['body'] = BBCode::removeSharedData($item['body']);
3144 } elseif (empty($shared_item['uri-id']) && empty($item['quote-uri-id']) && ($item['network'] != Protocol::DIASPORA)) {
3145 $media = Post\Media::getByURIId($item['uri-id'], [Post\Media::ACTIVITY]);
3146 if (!empty($media) && ($media[0]['media-uri-id'] != $item['uri-id'])) {
3147 $shared_item = Post::selectFirst($fields, ['uri-id' => $media[0]['media-uri-id'], 'uid' => [$item['uid'], 0]]);
3148 if (empty($shared_item['uri-id'])) {
3149 $shared_item = Post::selectFirst($fields, ['plink' => $media[0]['url'], 'uid' => [$item['uid'], 0]]);
3150 } elseif (!in_array(strtolower($media[0]['url']), $shared_links)) {
3151 $shared_links[] = strtolower($media[0]['url']);
3154 if (empty($shared_item['uri-id'])) {
3155 $shared_item = Post::selectFirst($fields, ['uri' => $media[0]['url'], 'uid' => [$item['uid'], 0]]);
3156 $shared_links[] = strtolower($media[0]['url']);
3159 if (!empty($shared_item['uri-id'])) {
3160 $data = BBCode::getAttachmentData($shared_item['body']);
3161 if (!empty($data['url'])) {
3162 $quote_shared_links[] = $data['url'];
3165 $quote_uri_id = $shared_item['uri-id'];
3170 if (!empty($quote_uri_id)) {
3171 if (isset($shared_item['plink'])) {
3172 $item['body'] .= "\n" . DI::contentItem()->createSharedBlockByArray($shared_item, false, true);
3174 DI::logger()->warning('Missing plink in shared item', ['item' => $item, 'shared' => $shared, 'quote_uri_id' => $quote_uri_id, 'shared_item' => $shared_item]);
3178 if (!empty($shared_item['uri-id'])) {
3179 $shared_uri_id = $shared_item['uri-id'];
3180 $shared_links[] = strtolower($shared_item['plink']);
3181 $sharedSplitAttachments = DI::postMediaRepository()->splitAttachments($shared_uri_id, [], $shared_item['has-media']);
3182 $shared_links = array_merge($shared_links, $sharedSplitAttachments['visual']->column('url'));
3183 $shared_links = array_merge($shared_links, $sharedSplitAttachments['link']->column('url'));
3184 $shared_links = array_merge($shared_links, $sharedSplitAttachments['additional']->column('url'));
3185 $item['body'] = self::replaceVisualAttachments($sharedSplitAttachments['visual'], $item['body']);
3188 $itemSplitAttachments = DI::postMediaRepository()->splitAttachments($item['uri-id'], $shared_links, $item['has-media'] ?? false);
3189 $item['body'] = self::replaceVisualAttachments($itemSplitAttachments['visual'], $item['body'] ?? '');
3191 self::putInCache($item);
3192 $item['body'] = $body;
3193 $s = $item["rendered-html"];
3199 // Compile eventual content filter reasons
3200 $filter_reasons = [];
3201 if (!$is_preview && DI::userSession()->getPublicContactId() != $item['author-id']) {
3202 if (!empty($item['user-blocked-author']) || !empty($item['user-blocked-owner'])) {
3203 $filter_reasons[] = DI::l10n()->t('%s is blocked', $item['author-name']);
3204 } elseif (!empty($item['user-ignored-author']) || !empty($item['user-ignored-owner'])) {
3205 $filter_reasons[] = DI::l10n()->t('%s is ignored', $item['author-name']);
3206 } elseif (!empty($item['user-collapsed-author']) || !empty($item['user-collapsed-owner'])) {
3207 $filter_reasons[] = DI::l10n()->t('Content from %s is collapsed', $item['author-name']);
3210 if (!empty($item['content-warning']) && (!DI::userSession()->getLocalUserId() || !DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'system', 'disable_cw', false))) {
3211 $filter_reasons[] = DI::l10n()->t('Content warning: %s', $item['content-warning']);
3214 $item['attachments'] = $itemSplitAttachments;
3218 'filter_reasons' => $filter_reasons
3220 Hook::callAll('prepare_body_content_filter', $hook_data);
3221 $filter_reasons = $hook_data['filter_reasons'];
3228 'preview' => $is_preview,
3229 'filter_reasons' => $filter_reasons
3231 Hook::callAll('prepare_body', $hook_data);
3232 $s = $hook_data['html'];
3237 // Replace the blockquotes with quotes that are used in mails.
3238 $mailquote = '<blockquote type="cite" class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex;">';
3239 $s = str_replace(['<blockquote>', '<blockquote class="spoiler">', '<blockquote class="author">'], [$mailquote, $mailquote, $mailquote], $s);
3243 if (!empty($sharedSplitAttachments)) {
3244 $s = self::addGallery($s, $sharedSplitAttachments['visual'], $item['uri-id']);
3245 $s = self::addVisualAttachments($sharedSplitAttachments['visual'], $shared_item, $s, true);
3246 $s = self::addLinkAttachment($shared_uri_id ?: $item['uri-id'], $sharedSplitAttachments, $body, $s, true, $quote_shared_links);
3247 $s = self::addNonVisualAttachments($sharedSplitAttachments['additional'], $item, $s, true);
3248 $body = BBCode::removeSharedData($body);
3251 $pos = strpos($s, BBCode::SHARED_ANCHOR);
3253 $shared_html = substr($s, $pos + strlen(BBCode::SHARED_ANCHOR));
3254 $s = substr($s, 0, $pos);
3257 $s = self::addGallery($s, $itemSplitAttachments['visual'], $item['uri-id']);
3258 $s = self::addVisualAttachments($itemSplitAttachments['visual'], $item, $s, false);
3259 $s = self::addLinkAttachment($item['uri-id'], $itemSplitAttachments, $body, $s, false, $shared_links);
3260 $s = self::addNonVisualAttachments($itemSplitAttachments['additional'], $item, $s, false);
3261 $s = self::addQuestions($item, $s);
3264 if (strpos($s, '<div class="map">') !== false && !empty($item['coord'])) {
3265 $x = Map::byCoordinates(trim($item['coord']));
3267 $s = preg_replace('/\<div class\=\"map\"\>/', '$0' . $x, $s);
3271 // Replace friendica image url size with theme preference.
3272 if (!empty($a->getThemeInfoValue('item_image_size'))) {
3273 $ps = $a->getThemeInfoValue('item_image_size');
3274 $s = preg_replace('|(<img[^>]+src="[^"]+/photo/[0-9a-f]+)-[0-9]|', "$1-" . $ps, $s);
3277 if (!empty($shared_html)) {
3281 $s = HTML::applyContentFilter($s, $filter_reasons);
3283 $hook_data = ['item' => $item, 'html' => $s];
3284 Hook::callAll('prepare_body_final', $hook_data);
3285 return $hook_data['html'];
3289 * @param array $images
3291 * @throws \Friendica\Network\HTTPException\ServiceUnavailableException
3293 private static function makeImageGrid(array $images): string
3295 // Image for first column (fc) and second column (sc)
3299 for ($i = 0; $i < count($images); $i++) {
3300 ($i % 2 == 0) ? ($images_fc[] = $images[$i]) : ($images_sc[] = $images[$i]);
3303 return Renderer::replaceMacros(Renderer::getMarkupTemplate('content/image_grid.tpl'), [
3312 * Modify links to pictures to links for the "Fancybox" gallery
3315 * @param PostMedias $PostMedias
3316 * @param int $uri_id
3319 private static function addGallery(string $s, PostMedias $PostMedias, int $uri_id): string
3321 foreach ($PostMedias as $PostMedia) {
3322 if (!$PostMedia->preview || ($PostMedia->type !== Post\Media::IMAGE)) {
3326 $s = str_replace('<a href="' . $PostMedia->url . '"', '<a data-fancybox="' . $uri_id . '" href="' . $PostMedia->url . '"', $s);
3333 * Check if the body contains a link
3335 * @param string $body
3336 * @param string $url
3340 public static function containsLink(string $body, string $url, int $type = 0): bool
3342 // Make sure that for example site parameters aren't used when testing if the link is contained in the body
3343 $urlparts = parse_url($url);
3344 if (empty($urlparts)) {
3348 unset($urlparts['query']);
3349 unset($urlparts['fragment']);
3352 $url = (string)Uri::fromParts($urlparts);
3353 } catch (\InvalidArgumentException $e) {
3354 DI::logger()->notice('Invalid URL', ['$url' => $url, '$urlparts' => $urlparts]);
3355 /* See https://github.com/friendica/friendica/issues/12113
3356 * Malformed URLs will result in a Fatal Error
3361 // Remove media links to only search in embedded content
3362 // @todo Check images for image link, audio for audio links, ...
3363 if (in_array($type, [Post\Media::AUDIO, Post\Media::VIDEO, Post\Media::IMAGE])) {
3364 $body = preg_replace("/\[url=[^\[\]]*\](.*)\[\/url\]/Usi", ' $1 ', $body);
3367 if (strpos($body, $url)) {
3371 foreach ([0, 1, 2] as $size) {
3373 preg_match('#/photo/.*-' . $size . '\.#ism', $url) &&
3374 strpos(preg_replace('#(/photo/.*)-[012]\.#ism', '$1-' . $size . '.', $body), $url)
3384 * Replace visual attachments in the body
3386 * @param PostMedias $PostMedias
3387 * @param string $body
3388 * @return string modified body
3390 private static function replaceVisualAttachments(PostMedias $PostMedias, string $body): string
3392 DI::profiler()->startRecording('rendering');
3394 foreach ($PostMedias as $PostMedia) {
3395 if ($PostMedia->preview) {
3396 if (DI::baseUrl()->isLocalUri($PostMedia->preview)) {
3399 $proxy = DI::baseUrl() . $PostMedia->getPreviewPath(Proxy::SIZE_LARGE);
3400 $search = ['[img=' . $PostMedia->preview . ']', ']' . $PostMedia->preview . '[/img]'];
3401 $replace = ['[img=' . $proxy . ']', ']' . $proxy . '[/img]'];
3403 $body = str_replace($search, $replace, $body);
3404 } elseif ($PostMedia->mimetype->type == 'image') {
3405 if (DI::baseUrl()->isLocalUri($PostMedia->url)) {
3408 $proxy = DI::baseUrl() . $PostMedia->getPreviewPath(Proxy::SIZE_LARGE);
3409 $search = ['[img=' . $PostMedia->url . ']', ']' . $PostMedia->url . '[/img]'];
3410 $replace = ['[img=' . $proxy . ']', ']' . $proxy . '[/img]'];
3412 $body = str_replace($search, $replace, $body);
3415 DI::profiler()->stopRecording();
3420 * Add visual attachments to the content
3422 * @param PostMedias $PostMedias
3423 * @param array $item
3424 * @param string $content
3425 * @param bool $shared
3426 * @return string modified content
3427 * @throws ServiceUnavailableException
3429 private static function addVisualAttachments(PostMedias $PostMedias, array $item, string $content, bool $shared): string
3431 DI::profiler()->startRecording('rendering');
3436 // @todo In the future we should make a single for the template engine with all media in it. This allows more flexibilty.
3437 foreach ($PostMedias as $PostMedia) {
3438 if (self::containsLink($item['body'], $PostMedia->preview ?? $PostMedia->url, $PostMedia->type)) {
3442 if ($PostMedia->mimetype->type == 'image') {
3443 $preview_url = DI::baseUrl() . $PostMedia->getPreviewPath($PostMedia->width > $PostMedia->height ? Proxy::SIZE_MEDIUM : Proxy::SIZE_LARGE);
3444 } elseif ($PostMedia->preview) {
3445 $preview_url = DI::baseUrl() . $PostMedia->getPreviewPath(Proxy::SIZE_LARGE);
3450 if ($preview_url && self::containsLink($item['body'], $preview_url)) {
3454 if ($PostMedia->mimetype->type == 'video') {
3455 /// @todo Move the template to /content as well
3456 $media = Renderer::replaceMacros(Renderer::getMarkupTemplate('video_top.tpl'), [
3458 'id' => $PostMedia->id,
3459 'src' => (string)$PostMedia->url,
3460 'name' => $PostMedia->name ?: $PostMedia->url,
3461 'preview' => $preview_url,
3462 'mime' => (string)$PostMedia->mimetype,
3465 if (($item['post-type'] ?? null) == Item::PT_VIDEO) {
3468 $trailing .= $media;
3470 } elseif ($PostMedia->mimetype->type == 'audio') {
3471 $media = Renderer::replaceMacros(Renderer::getMarkupTemplate('content/audio.tpl'), [
3473 'id' => $PostMedia->id,
3474 'src' => (string)$PostMedia->url,
3475 'name' => $PostMedia->name ?: $PostMedia->url,
3476 'mime' => (string)$PostMedia->mimetype,
3479 if (($item['post-type'] ?? null) == Item::PT_AUDIO) {
3482 $trailing .= $media;
3484 } elseif ($PostMedia->mimetype->type == 'image') {
3485 $src_url = DI::baseUrl() . $PostMedia->getPhotoPath();
3486 if (self::containsLink($item['body'], $src_url)) {
3492 'preview' => $preview_url,
3493 'attachment' => $PostMedia,
3499 if (count($images) > 1) {
3500 $media = self::makeImageGrid($images);
3501 } elseif (count($images) == 1) {
3502 $media = Renderer::replaceMacros(Renderer::getMarkupTemplate('content/image.tpl'), [
3503 '$image' => $images[0],
3507 // On Diaspora posts the attached pictures are leading
3508 if ($item['network'] == Protocol::DIASPORA) {
3511 $trailing .= $media;
3515 $content = str_replace(BBCode::TOP_ANCHOR, '<div class="body-attach">' . $leading . '</div>' . BBCode::TOP_ANCHOR, $content);
3516 $content = str_replace(BBCode::BOTTOM_ANCHOR, '<div class="body-attach">' . $trailing . '</div>' . BBCode::BOTTOM_ANCHOR, $content);
3518 if ($leading != '') {
3519 $content = '<div class="body-attach">' . $leading . '</div>' . $content;
3522 if ($trailing != '') {
3523 $content .= '<div class="body-attach">' . $trailing . '</div>';
3527 DI::profiler()->stopRecording();
3532 * Add link attachment to the content
3535 * @param PostMedias[] $attachments
3536 * @param string $body
3537 * @param string $content
3538 * @param bool $shared
3539 * @param array $ignore_links A list of URLs to ignore
3540 * @return string modified content
3541 * @throws InternalServerErrorException
3542 * @throws ServiceUnavailableException
3544 private static function addLinkAttachment(int $uriid, array $attachments, string $body, string $content, bool $shared, array $ignore_links): string
3546 DI::profiler()->startRecording('rendering');
3547 // Don't show a preview when there is a visual attachment (audio or video)
3548 $types = $attachments['visual']->column('type');
3549 $preview = !in_array(PostMedia::TYPE_IMAGE, $types) && !in_array(PostMedia::TYPE_VIDEO, $types);
3551 /** @var ?PostMedia $attachment */
3553 foreach ($attachments['link'] as $PostMedia) {
3555 foreach ($ignore_links as $ignore_link) {
3556 if (Strings::compareLink($PostMedia->url, $ignore_link)) {
3560 // @todo Judge between the links to use the one with most information
3561 if (!$found && (empty($attachment) || $PostMedia->authorName ||
3562 (!$attachment->name && $PostMedia->name) ||
3563 (!$attachment->description && $PostMedia->description) ||
3564 (!$attachment->preview && $PostMedia->preview))) {
3565 $attachment = $PostMedia;
3569 if (!empty($attachment)) {
3572 'author_name' => $attachment->authorName ?? '',
3573 'author_url' => (string)($attachment->authorUrl ?? ''),
3574 'description' => $attachment->description ?? '',
3577 'provider_name' => $attachment->publisherName ?? '',
3578 'provider_url' => (string)($attachment->publisherUrl ?? ''),
3580 'title' => $attachment->name ?? '',
3582 'url' => (string)$attachment->url,
3585 if ($preview && $attachment->preview) {
3586 if ($attachment->previewWidth >= 500) {
3587 $data['image'] = DI::baseUrl() . $attachment->getPreviewPath(Proxy::SIZE_MEDIUM);
3589 $data['preview'] = DI::baseUrl() . $attachment->getPreviewPath(Proxy::SIZE_MEDIUM);
3593 if (!empty($data['description']) && !empty($content)) {
3594 similar_text($data['description'], $content, $percent);
3599 if (!empty($data['description']) && (($data['title'] == $data['description']) || ($percent > 95) || (strpos($content, $data['description']) !== false))) {
3600 $data['description'] = '';
3603 if (($data['author_name'] ?? '') == ($data['provider_name'] ?? '')) {
3604 $data['author_name'] = '';
3607 if (($data['author_url'] ?? '') == ($data['provider_url'] ?? '')) {
3608 $data['author_url'] = '';
3610 } elseif (preg_match("/.*(\[attachment.*?\].*?\[\/attachment\]).*/ism", $body, $match)) {
3611 $data = BBCode::getAttachmentData($match[1]);
3613 DI::profiler()->stopRecording();
3615 if (isset($data['url']) && !in_array(strtolower($data['url']), $ignore_links)) {
3616 if (!empty($data['description']) || !empty($data['image']) || !empty($data['preview']) || (!empty($data['title']) && !Strings::compareLink($data['title'], $data['url']))) {
3617 $parts = parse_url($data['url']);
3618 if (!empty($parts['scheme']) && !empty($parts['host'])) {
3619 if (empty($data['provider_name'])) {
3620 $data['provider_name'] = $parts['host'];
3622 if (empty($data['provider_url']) || empty(parse_url($data['provider_url'], PHP_URL_SCHEME))) {
3623 $data['provider_url'] = $parts['scheme'] . '://' . $parts['host'];
3625 if (!empty($parts['port'])) {
3626 $data['provider_url'] .= ':' . $parts['port'];
3631 // @todo Use a template
3632 $preview_mode = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'system', 'preview_mode', BBCode::PREVIEW_LARGE);
3633 if ($preview_mode != BBCode::PREVIEW_NONE) {
3634 $rendered = BBCode::convertAttachment('', BBCode::INTERNAL, false, $data, $uriid, $preview_mode);
3638 } elseif (!self::containsLink($content, $data['url'], Post\Media::HTML)) {
3639 $rendered = Renderer::replaceMacros(Renderer::getMarkupTemplate('content/link.tpl'), [
3640 '$url' => $data['url'],
3641 '$title' => $data['title'],
3648 return str_replace(BBCode::BOTTOM_ANCHOR, BBCode::BOTTOM_ANCHOR . $rendered, $content);
3650 return $content . $rendered;
3657 * Add non-visual attachments to the content
3659 * @param PostMedias $PostMedias
3660 * @param array $item
3661 * @param string $content
3662 * @return string modified content
3663 * @throws InternalServerErrorException
3664 * @throws \ImagickException
3666 private static function addNonVisualAttachments(PostMedias $PostMedias, array $item, string $content): string
3668 DI::profiler()->startRecording('rendering');
3670 foreach ($PostMedias as $PostMedia) {
3671 if (strpos($item['body'], $PostMedia->url)) {
3677 'id' => $item['author-id'],
3678 'network' => $item['author-network'],
3679 'url' => $item['author-link'],
3680 'alias' => $item['author-alias']
3682 $the_url = Contact::magicLinkByContact($author, $PostMedia->url);
3684 $title = Strings::escapeHtml(trim($PostMedia->description ?? '' ?: $PostMedia->url));
3686 if ($PostMedia->size) {
3687 $title .= ' ' . $PostMedia->size . ' ' . DI::l10n()->t('bytes');
3690 /// @todo Use a template
3691 $icon = '<div class="attachtype icon s22 type-' . $PostMedia->mimetype->type . ' subtype-' . $PostMedia->mimetype->subtype . '"></div>';
3692 $trailing .= '<a href="' . strip_tags($the_url) . '" title="' . $title . '" class="attachlink" target="_blank" rel="noopener noreferrer" >' . $icon . '</a>';
3695 if ($trailing != '') {
3696 $content .= '<div class="body-attach">' . $trailing . '</div>';
3699 DI::profiler()->stopRecording();
3703 private static function addQuestions(array $item, string $content): string
3705 DI::profiler()->startRecording('rendering');
3706 if (!empty($item['question-id'])) {
3708 'id' => $item['question-id'],
3709 'multiple' => $item['question-multiple'],
3710 'voters' => $item['question-voters'],
3711 'endtime' => $item['question-end-time']
3714 $options = Post\QuestionOption::getByURIId($item['uri-id']);
3715 foreach ($options as $key => $option) {
3716 if ($question['voters'] > 0) {
3717 $percent = $option['replies'] / $question['voters'] * 100;
3718 $options[$key]['vote'] = DI::l10n()->tt('%2$s (%3$d%%, %1$d vote)', '%2$s (%3$d%%, %1$d votes)', $option['replies'], $option['name'], round($percent, 1));
3720 $options[$key]['vote'] = DI::l10n()->tt('%2$s (%1$d vote)', '%2$s (%1$d votes)', $option['replies'], $option['name']);
3724 if (!empty($question['voters']) && !empty($question['endtime'])) {
3725 $summary = DI::l10n()->tt('%d voter. Poll end: %s', '%d voters. Poll end: %s', $question['voters'], Temporal::getRelativeDate($question['endtime']));
3726 } elseif (!empty($question['voters'])) {
3727 $summary = DI::l10n()->tt('%d voter.', '%d voters.', $question['voters']);
3728 } elseif (!empty($question['endtime'])) {
3729 $summary = DI::l10n()->t('Poll end: %s', Temporal::getRelativeDate($question['endtime']));
3734 $content .= Renderer::replaceMacros(Renderer::getMarkupTemplate('content/question.tpl'), [
3735 '$question' => $question,
3736 '$options' => $options,
3737 '$summary' => $summary,
3740 DI::profiler()->stopRecording();
3745 * get private link for item
3747 * @param array $item
3748 * @return boolean|array False if item has not plink, otherwise array('href'=>plink url, 'title'=>translated title)
3749 * @throws \Exception
3751 public static function getPlink(array $item)
3753 if (!empty($item['plink']) && Network::isValidHttpUrl($item['plink'])) {
3754 $plink = $item['plink'];
3755 } elseif (!empty($item['uri']) && Network::isValidHttpUrl($item['uri']) && !Network::isLocalLink($item['uri'])) {
3756 $plink = $item['uri'];
3759 if (DI::userSession()->getLocalUserId()) {
3761 'href' => "display/" . $item['guid'],
3762 'orig' => "display/" . $item['guid'],
3763 'title' => DI::l10n()->t('View on separate page'),
3764 'orig_title' => DI::l10n()->t('View on separate page'),
3767 if (!empty($plink) && ($item['private'] == self::PRIVATE)) {
3770 'id' => $item['author-id'],
3771 'network' => $item['author-network'],
3772 'url' => $item['author-link'],
3773 'alias' => $item['author-alias'],
3775 $plink = Contact::magicLinkByContact($author, $plink);
3778 if (!empty($plink)) {
3779 $ret['href'] = DI::baseUrl()->remove($plink);
3780 $ret['title'] = DI::l10n()->t('Link to source');
3782 } elseif (!empty($plink) && ($item['private'] != self::PRIVATE)) {
3786 'title' => DI::l10n()->t('Link to source'),
3787 'orig_title' => DI::l10n()->t('Link to source'),
3797 * Does the given uri-id belongs to a post that is sent as starting post to a group?
3798 * This does apply to posts that are sent via ! and not in parallel to a group via @
3800 * @param int $uri_id
3802 * @return boolean "true" when it is a group post
3804 public static function isGroupPost(int $uri_id): bool
3806 if (Post::exists(['private' => Item::PUBLIC, 'uri-id' => $uri_id])) {
3810 foreach (Tag::getByURIId($uri_id, [Tag::EXCLUSIVE_MENTION, Tag::AUDIENCE]) as $tag) {
3811 // @todo Possibly check for a public audience in the future, see https://socialhub.activitypub.rocks/t/fep-1b12-group-federation/2724
3812 // and https://codeberg.org/fediverse/fep/src/branch/main/feps/fep-1b12.md
3813 if (DBA::exists('contact', ['uid' => 0, 'nurl' => Strings::normaliseLink($tag['url']), 'contact-type' => Contact::TYPE_COMMUNITY])) {
3821 * Search item id for given URI or plink
3823 * @param string $uri
3824 * @param integer $uid
3826 * @return integer item id
3828 public static function searchByLink(string $uri, int $uid = 0): int
3830 $ssl_uri = str_replace('http://', 'https://', $uri);
3831 $uris = [$uri, $ssl_uri, Strings::normaliseLink($uri)];
3833 $item = Post::selectFirst(['id'], ['uri' => $uris, 'uid' => $uid]);
3834 if (DBA::isResult($item)) {
3838 $item = Post::selectFirst(['id'], ['plink' => $uris, 'uid' => $uid]);
3839 if (DBA::isResult($item)) {
3847 * Return the URI for a link to the post
3849 * @param string $uri URI or link to post
3851 * @return string URI
3853 public static function getURIByLink(string $uri): string
3855 $ssl_uri = str_replace('http://', 'https://', $uri);
3856 $uris = [$uri, $ssl_uri, Strings::normaliseLink($uri)];
3858 $item = Post::selectFirst(['uri'], ['uri' => $uris]);
3859 if (DBA::isResult($item)) {
3860 return $item['uri'];
3863 $item = Post::selectFirst(['uri'], ['plink' => $uris]);
3864 if (DBA::isResult($item)) {
3865 return $item['uri'];
3872 * Fetches item for given URI or plink
3874 * @param string $uri
3875 * @param integer $uid
3877 * @return integer item id
3879 public static function fetchByLink(string $uri, int $uid = 0): int
3881 Logger::info('Trying to fetch link', ['uid' => $uid, 'uri' => $uri]);
3882 $item_id = self::searchByLink($uri, $uid);
3883 if (!empty($item_id)) {
3884 Logger::info('Link found', ['uid' => $uid, 'uri' => $uri, 'id' => $item_id]);
3894 Hook::callAll('item_by_link', $hookData);
3896 if (isset($hookData['item_id'])) {
3897 return is_numeric($hookData['item_id']) ? $hookData['item_id'] : 0;
3900 $fetched_uri = ActivityPub\Processor::fetchMissingActivity($uri, [], '', ActivityPub\Receiver::COMPLETION_MANUAL, $uid);
3903 $item_id = self::searchByLink($fetched_uri, $uid);
3905 $item_id = Diaspora::fetchByURL($uri);
3908 if (!empty($item_id)) {
3909 Logger::info('Link fetched', ['uid' => $uid, 'uri' => $uri, 'id' => $item_id]);
3913 Logger::info('Link not found', ['uid' => $uid, 'uri' => $uri]);
3918 * Fetch the uri-id of a quote
3920 * @param string $body
3923 public static function getQuoteUriId(string $body, int $uid = 0): int
3925 $shared = BBCode::fetchShareAttributes($body);
3926 if (empty($shared['guid']) && empty($shared['message_id'])) {
3930 if (empty($shared['link']) && empty($shared['message_id'])) {
3931 Logger::notice('Invalid share block.', ['share' => $shared]);
3935 if (!empty($shared['guid'])) {
3936 $shared_item = Post::selectFirst(['uri-id'], ['guid' => $shared['guid'], 'uid' => [0, $uid]]);
3937 if (!empty($shared_item['uri-id'])) {
3938 Logger::debug('Found post by guid', ['guid' => $shared['guid'], 'uid' => $uid]);
3939 return $shared_item['uri-id'];
3943 if (!empty($shared['message_id'])) {
3944 $shared_item = Post::selectFirst(['uri-id'], ['uri' => $shared['message_id'], 'uid' => [0, $uid]]);
3945 if (!empty($shared_item['uri-id'])) {
3946 Logger::debug('Found post by message_id', ['message_id' => $shared['message_id'], 'uid' => $uid]);
3947 return $shared_item['uri-id'];
3951 if (!empty($shared['link'])) {
3952 $shared_item = Post::selectFirst(['uri-id'], ['plink' => $shared['link'], 'uid' => [0, $uid]]);
3953 if (!empty($shared_item['uri-id'])) {
3954 Logger::debug('Found post by link', ['link' => $shared['link'], 'uid' => $uid]);
3955 return $shared_item['uri-id'];
3959 $url = $shared['message_id'] ?: $shared['link'];
3960 $id = self::fetchByLink($url);
3962 Logger::notice('Post could not be fetched.', ['url' => $url, 'uid' => $uid]);
3966 $shared_item = Post::selectFirst(['uri-id'], ['id' => $id]);
3967 if (!empty($shared_item['uri-id'])) {
3968 Logger::debug('Fetched shared post', ['id' => $id, 'url' => $url, 'uid' => $uid]);
3969 return $shared_item['uri-id'];
3972 Logger::warning('Post does not exist although it was supposed to had been fetched.', ['id' => $id, 'url' => $url, 'uid' => $uid]);