3 * @copyright Copyright (C) 2010-2023, the Friendica project
5 * @license GNU AGPL version 3 or any later version
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU Affero General Public License as
9 * published by the Free Software Foundation, either version 3 of the
10 * License, or (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU Affero General Public License for more details.
17 * You should have received a copy of the GNU Affero General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
22 namespace Friendica\Model;
24 use Friendica\Content\Text\BBCode;
25 use Friendica\Content\Text\HTML;
26 use Friendica\Core\Hook;
27 use Friendica\Core\Logger;
28 use Friendica\Core\Protocol;
29 use Friendica\Core\Renderer;
30 use Friendica\Core\System;
31 use Friendica\Core\Worker;
32 use Friendica\Database\DBA;
34 use Friendica\Network\HTTPException\InternalServerErrorException;
35 use Friendica\Protocol\Activity;
36 use Friendica\Protocol\ActivityPub;
37 use Friendica\Protocol\Delivery;
38 use Friendica\Protocol\Diaspora;
39 use Friendica\Util\DateTimeFormat;
40 use Friendica\Util\Map;
41 use Friendica\Util\Network;
42 use Friendica\Util\Proxy;
43 use Friendica\Util\Strings;
44 use Friendica\Util\Temporal;
45 use GuzzleHttp\Psr7\Uri;
46 use LanguageDetection\Language;
50 // Posting types, inspired by https://www.w3.org/TR/activitystreams-vocabulary/#object-types
57 const PT_DOCUMENT = 19;
60 const PT_PERSONAL_NOTE = 128;
62 // Posting reasons (Why had a post been stored for a user?)
69 const PR_FOLLOWER = 69;
70 const PR_ANNOUNCEMENT = 70;
71 const PR_COMMENT = 71;
75 const PR_FETCHED = 75;
76 const PR_COMPLETION = 76;
78 const PR_ACTIVITY = 78;
79 const PR_DISTRIBUTE = 79;
82 const PR_AUDIENCE = 82;
84 // system.accept_only_sharer setting values
85 const COMPLETION_NONE = 1;
86 const COMPLETION_COMMENT = 0;
87 const COMPLETION_LIKE = 2;
89 // Field list that is used to display the items
90 const DISPLAY_FIELDLIST = [
91 'uid', 'id', 'parent', 'guid', 'network', 'gravity',
92 'uri-id', 'uri', 'thr-parent-id', 'thr-parent', 'parent-uri-id', 'parent-uri', 'conversation',
93 'commented', 'created', 'edited', 'received', 'verb', 'object-type', 'postopts', 'plink',
94 'wall', 'private', 'starred', 'origin', 'parent-origin', 'title', 'body', 'language',
95 'content-warning', 'location', 'coord', 'app', 'rendered-hash', 'rendered-html', 'object',
96 'quote-uri', 'quote-uri-id', 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid', 'mention', 'global',
97 'author-id', 'author-link', 'author-name', 'author-avatar', 'author-network', 'author-updated', 'author-gsid', 'author-addr', 'author-uri-id',
98 'owner-id', 'owner-link', 'owner-name', 'owner-avatar', 'owner-network', 'owner-contact-type', 'owner-updated',
99 'causer-id', 'causer-link', 'causer-name', 'causer-avatar', 'causer-contact-type', 'causer-network',
100 'contact-id', 'contact-uid', 'contact-link', 'contact-name', 'contact-avatar',
101 'writable', 'self', 'cid', 'alias',
102 'event-created', 'event-edited', 'event-start', 'event-finish',
103 'event-summary', 'event-desc', 'event-location', 'event-type',
104 'event-nofinish', 'event-ignore', 'event-id',
105 'question-id', 'question-multiple', 'question-voters', 'question-end-time',
106 'has-categories', 'has-media',
107 'delivery_queue_count', 'delivery_queue_done', 'delivery_queue_failed'
110 // Field list that is used to deliver items via the protocols
111 const DELIVER_FIELDLIST = ['uid', 'id', 'parent', 'uri-id', 'uri', 'thr-parent', 'parent-uri', 'guid',
112 'parent-guid', 'conversation', 'received', 'created', 'edited', 'verb', 'object-type', 'object', 'target',
113 'private', 'title', 'body', 'raw-body', 'location', 'coord', 'app',
114 'inform', 'deleted', 'extid', 'post-type', 'post-reason', 'gravity',
115 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid',
116 'author-id', 'author-addr', 'author-link', 'author-name', 'author-avatar', 'owner-id', 'owner-link', 'contact-uid',
117 'signed_text', 'network', 'wall', 'contact-id', 'plink', 'origin',
118 'thr-parent-id', 'parent-uri-id', 'quote-uri', 'quote-uri-id', 'postopts', 'pubmail',
119 'event-created', 'event-edited', 'event-start', 'event-finish',
120 'event-summary', 'event-desc', 'event-location', 'event-type',
121 'event-nofinish', 'event-ignore', 'event-id'];
123 // All fields in the item table
124 const ITEM_FIELDLIST = ['id', 'uid', 'parent', 'uri', 'parent-uri', 'thr-parent',
125 'guid', 'uri-id', 'parent-uri-id', 'thr-parent-id', 'conversation', 'vid',
126 'quote-uri', 'quote-uri-id', 'contact-id', 'wall', 'gravity', 'extid', 'psid',
127 'created', 'edited', 'commented', 'received', 'changed', 'verb',
128 'postopts', 'plink', 'resource-id', 'event-id', 'inform',
129 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid', 'post-type', 'post-reason',
130 'private', 'pubmail', 'visible', 'starred',
131 'unseen', 'deleted', 'origin', 'mention', 'global', 'network',
132 'title', 'content-warning', 'body', 'location', 'coord', 'app',
133 'rendered-hash', 'rendered-html', 'object-type', 'object', 'target-type', 'target',
134 'author-id', 'author-link', 'author-name', 'author-avatar', 'author-network',
135 'owner-id', 'owner-link', 'owner-name', 'owner-avatar', 'causer-id'];
137 // List of all verbs that don't need additional content data.
138 // Never reorder or remove entries from this list. Just add new ones at the end, if needed.
140 Activity::LIKE, Activity::DISLIKE,
141 Activity::ATTEND, Activity::ATTENDNO, Activity::ATTENDMAYBE,
150 // Item weight for query ordering
151 const GRAVITY_PARENT = 0;
152 const GRAVITY_ACTIVITY = 3;
153 const GRAVITY_COMMENT = 6;
154 const GRAVITY_UNKNOWN = 9;
157 * Update existing item entries
159 * @param array $fields The fields that are to be changed
160 * @param array $condition The condition for finding the item entries
162 * In the future we may have to change permissions as well.
163 * Then we had to add the user id as third parameter.
165 * A return value of "0" doesn't mean an error - but that 0 rows had been changed.
167 * @return integer|boolean number of affected rows - or "false" if there was an error
168 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
170 public static function update(array $fields, array $condition)
172 if (empty($condition) || empty($fields)) {
176 if (isset($fields['extid'])) {
177 $fields['external-id'] = ItemURI::getIdByURI($fields['extid']);
180 if (!empty($fields['verb'])) {
181 $fields['vid'] = Verb::getID($fields['verb']);
184 if (!empty($fields['edited'])) {
185 $previous = Post::selectFirst(['edited'], $condition);
188 $rows = Post::update($fields, $condition);
189 if (is_bool($rows)) {
193 // We only need to call the line by line update for specific fields
194 if (empty($fields['body']) && empty($fields['file']) &&
195 empty($fields['attach']) && empty($fields['edited'])) {
199 Logger::info('Updating per single row method', ['fields' => $fields, 'condition' => $condition]);
201 $items = Post::select(['id', 'origin', 'uri-id', 'uid', 'author-network', 'quote-uri-id'], $condition);
205 while ($item = DBA::fetch($items)) {
206 if (!empty($fields['body'])) {
207 if (!empty($item['quote-uri-id'])) {
208 $fields['body'] = BBCode::removeSharedData($fields['body']);
210 if (!empty($fields['raw-body'])) {
211 $fields['raw-body'] = BBCode::removeSharedData($fields['raw-body']);
215 $content_fields = ['raw-body' => trim($fields['raw-body'] ?? $fields['body'])];
217 // Remove all media attachments from the body and store them in the post-media table
218 // @todo On shared postings (Diaspora style and commented reshare) don't fetch content from the shared part
219 $content_fields['raw-body'] = Post\Media::insertFromBody($item['uri-id'], $content_fields['raw-body']);
220 $content_fields['raw-body'] = self::setHashtags($content_fields['raw-body']);
222 Post\Media::insertFromRelevantUrl($item['uri-id'], $content_fields['raw-body'], $fields['body'], $item['author-network']);
224 Post\Media::insertFromAttachmentData($item['uri-id'], $fields['body']);
225 $content_fields['raw-body'] = BBCode::removeAttachment($content_fields['raw-body']);
227 Post\Content::update($item['uri-id'], $content_fields);
230 if (!empty($fields['file'])) {
231 Post\Category::storeTextByURIId($item['uri-id'], $item['uid'], $fields['file']);
234 if (!empty($fields['attach'])) {
235 Post\Media::insertFromAttachment($item['uri-id'], $fields['attach']);
238 // We only need to notify others when it is an original entry from us.
239 // Only call the notifier when the item had been edited and records had been changed.
240 if ($item['origin'] && !empty($fields['edited']) && ($previous['edited'] != $fields['edited'])) {
241 $notify_items[] = $item['id'];
247 foreach ($notify_items as $notify_item) {
248 $post = Post::selectFirst([], ['id' => $notify_item]);
250 if ($post['gravity'] != self::GRAVITY_PARENT) {
251 $signed = Diaspora::createCommentSignature($post);
252 if (!empty($signed)) {
253 DBA::replace('diaspora-interaction', ['uri-id' => $post['uri-id'], 'interaction' => json_encode($signed)]);
257 Worker::add(Worker::PRIORITY_HIGH, 'Notifier', Delivery::POST, (int)$post['uri-id'], (int)$post['uid']);
264 * Delete an item and notify others about it - if it was ours
266 * @param array $condition The condition for finding the item entries
267 * @param integer $priority Priority for the notification
269 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
271 public static function markForDeletion(array $condition, int $priority = Worker::PRIORITY_HIGH)
273 $items = Post::select(['id'], $condition);
274 while ($item = Post::fetch($items)) {
275 self::markForDeletionById($item['id'], $priority);
281 * Delete an item for an user and notify others about it - if it was ours
283 * @param array $condition The condition for finding the item entries
284 * @param integer $uid User who wants to delete this item
286 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
288 public static function deleteForUser(array $condition, int $uid)
294 $items = Post::select(['id', 'uid', 'uri-id'], $condition);
295 while ($item = Post::fetch($items)) {
296 if (in_array($item['uid'], [$uid, 0])) {
297 Post\User::update($item['uri-id'], $uid, ['hidden' => true], true);
298 Post\ThreadUser::update($item['uri-id'], $uid, ['hidden' => true], true);
301 if ($item['uid'] == $uid) {
302 self::markForDeletionById($item['id'], Worker::PRIORITY_HIGH);
303 } elseif ($item['uid'] != 0) {
304 Logger::warning('Wrong ownership. Not deleting item', ['id' => $item['id']]);
311 * Mark an item for deletion, delete related data and notify others about it - if it was ours
313 * @param integer $item_id
314 * @param integer $priority Priority for the notification
315 * @return boolean success
316 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
318 public static function markForDeletionById(int $item_id, int $priority = Worker::PRIORITY_HIGH): bool
320 Logger::info('Mark item for deletion by id', ['id' => $item_id, 'callstack' => System::callstack()]);
321 // locate item to be deleted
322 $fields = ['id', 'uri', 'uri-id', 'uid', 'parent', 'parent-uri-id', 'origin',
323 'deleted', 'resource-id', 'event-id',
324 'verb', 'object-type', 'object', 'target', 'contact-id', 'psid', 'gravity'];
325 $item = Post::selectFirst($fields, ['id' => $item_id]);
326 if (!DBA::isResult($item)) {
327 Logger::info('Item not found.', ['id' => $item_id]);
331 if ($item['deleted']) {
332 Logger::info('Item has already been marked for deletion.', ['id' => $item_id]);
336 $parent = Post::selectFirst(['origin'], ['id' => $item['parent']]);
337 if (!DBA::isResult($parent)) {
338 $parent = ['origin' => false];
341 // clean up categories and tags so they don't end up as orphans
342 Post\Category::deleteByURIId($item['uri-id'], $item['uid']);
345 * If item is a link to a photo resource, nuke all the associated photos
346 * (visitors will not have photo resources)
347 * This only applies to photos uploaded from the photos page. Photos inserted into a post do not
348 * generate a resource-id and therefore aren't intimately linked to the item.
350 /// @TODO: this should first check if photo is used elsewhere
351 if ($item['resource-id']) {
352 Photo::delete(['resource-id' => $item['resource-id'], 'uid' => $item['uid']]);
355 // If item is a link to an event, delete the event.
356 if (intval($item['event-id'])) {
357 Event::delete($item['event-id']);
360 // If item has attachments, drop them
361 $attachments = Post\Media::getByURIId($item['uri-id'], [Post\Media::DOCUMENT]);
362 foreach($attachments as $attachment) {
363 if (preg_match('|attach/(\d+)|', $attachment['url'], $matches)) {
364 Attach::delete(['id' => $matches[1], 'uid' => $item['uid']]);
368 // Set the item to "deleted"
369 $item_fields = ['deleted' => true, 'edited' => DateTimeFormat::utcNow(), 'changed' => DateTimeFormat::utcNow()];
370 Post::update($item_fields, ['id' => $item['id']]);
372 Post\Category::storeTextByURIId($item['uri-id'], $item['uid'], '');
374 if (!Post::exists(["`uri-id` = ? AND `uid` != 0 AND NOT `deleted`", $item['uri-id']])) {
375 self::markForDeletion(['uri-id' => $item['uri-id'], 'uid' => 0, 'deleted' => false], $priority);
378 Post\DeliveryData::delete($item['uri-id']);
380 // If it's the parent of a comment thread, kill all the kids
381 if ($item['gravity'] == self::GRAVITY_PARENT) {
382 self::markForDeletion(['parent' => $item['parent'], 'deleted' => false], $priority);
385 // Is it our comment and/or our thread?
386 if (($item['origin'] || $parent['origin']) && ($item['uid'] != 0)) {
387 // When we delete the original post we will delete all existing copies on the server as well
388 self::markForDeletion(['uri-id' => $item['uri-id'], 'deleted' => false], $priority);
390 // send the notification upstream/downstream
392 Worker::add(['priority' => $priority, 'dont_fork' => true], 'Notifier', Delivery::DELETION, (int)$item['uri-id'], (int)$item['uid']);
394 } elseif ($item['uid'] != 0) {
395 Post\User::update($item['uri-id'], $item['uid'], ['hidden' => true]);
396 Post\ThreadUser::update($item['uri-id'], $item['uid'], ['hidden' => true]);
399 DI::notify()->deleteForItem($item['uri-id']);
400 DI::notification()->deleteForItem($item['uri-id']);
402 Logger::info('Item has been marked for deletion.', ['id' => $item_id]);
408 * Get guid from given item record
410 * @param array $item Item record
411 * @param bool Whether to notify (?)
412 * @return string Guid
414 public static function guid(array $item, bool $notify): string
416 if (!empty($item['guid'])) {
417 return trim($item['guid']);
421 // We have to avoid duplicates. So we create the GUID in form of a hash of the plink or uri.
422 // We add the hash of our own host because our host is the original creator of the post.
423 $prefix_host = DI::baseUrl()->getHost();
427 // We are only storing the post so we create a GUID from the original hostname.
428 if (!empty($item['author-link'])) {
429 $parsed = parse_url($item['author-link']);
430 if (!empty($parsed['host'])) {
431 $prefix_host = $parsed['host'];
435 if (empty($prefix_host) && !empty($item['plink'])) {
436 $parsed = parse_url($item['plink']);
437 if (!empty($parsed['host'])) {
438 $prefix_host = $parsed['host'];
442 if (empty($prefix_host) && !empty($item['uri'])) {
443 $parsed = parse_url($item['uri']);
444 if (!empty($parsed['host'])) {
445 $prefix_host = $parsed['host'];
449 // Is it in the format data@host.tld? - Used for mail contacts
450 if (empty($prefix_host) && !empty($item['author-link']) && strstr($item['author-link'], '@')) {
451 $mailparts = explode('@', $item['author-link']);
452 $prefix_host = array_pop($mailparts);
456 if (!empty($item['plink'])) {
457 $guid = self::guidFromUri($item['plink'], $prefix_host);
458 } elseif (!empty($item['uri'])) {
459 $guid = self::guidFromUri($item['uri'], $prefix_host);
461 $guid = System::createUUID(hash('crc32', $prefix_host));
468 * Returns contact id from given item record
470 * @param array $item Item record
471 * @return int Contact id
473 private static function contactId(array $item): int
475 if ($item['uid'] == 0) {
476 return $item['author-id'];
479 if ($item['origin']) {
480 $owner = User::getOwnerDataById($item['uid']);
484 if (!empty($item['causer-id']) && Contact::isSharing($item['causer-id'], $item['uid'], true)) {
485 $cdata = Contact::getPublicAndUserContactID($item['causer-id'], $item['uid']);
486 if (!empty($cdata['user'])) {
487 return $cdata['user'];
491 if ($item['gravity'] == self::GRAVITY_PARENT) {
492 if (Contact::isSharingByURL($item['owner-link'], $item['uid'], true)) {
493 $contact_id = Contact::getIdForURL($item['owner-link'], $item['uid']);
495 $contact_id = Contact::getIdForURL($item['owner-link']);
497 if (!empty($contact_id)) {
502 if (Contact::isSharingByURL($item['author-link'], $item['uid'], true)) {
503 $contact_id = Contact::getIdForURL($item['author-link'], $item['uid']);
505 $contact_id = Contact::getIdForURL($item['author-link']);
508 if (!empty($contact_id)) {
512 Logger::warning('contact-id could not be fetched, using self contact instead.', ['uid' => $item['uid'], 'item' => $item]);
513 $self = Contact::selectFirst(['id'], ['self' => true, 'uid' => $item['uid']]);
518 * Write an item array into a spool file to be inserted later.
519 * This command is called whenever there are issues storing an item.
521 * @param array $item The item fields that are to be inserted
524 private static function spool(array $item)
526 // Now we store the data in the spool directory
527 // We use "microtime" to keep the arrival order and "mt_rand" to avoid duplicates
528 $file = 'item-' . round(microtime(true) * 10000) . '-' . mt_rand() . '.msg';
530 $spoolpath = System::getSpoolPath();
531 if ($spoolpath != '') {
532 $spool = $spoolpath . '/' . $file;
534 file_put_contents($spool, json_encode($item));
535 Logger::warning("Item wasn't stored - Item was spooled into file", ['file' => $file]);
540 * Check if the item array is a duplicate
542 * @param array $item Item record
543 * @return boolean is it a duplicate?
545 private static function isDuplicate(array $item): bool
547 // Checking if there is already an item with the same guid
548 $condition = ['guid' => $item['guid'], 'network' => $item['network'], 'uid' => $item['uid']];
549 if (Post::exists($condition)) {
550 Logger::notice('Found already existing item', $condition);
554 $condition = ['uri-id' => $item['uri-id'], 'uid' => $item['uid'],
555 'network' => [$item['network'], Protocol::DFRN]];
556 if (Post::exists($condition)) {
557 Logger::notice('duplicated item with the same uri found.', $condition);
561 // On Friendica and Diaspora the GUID is unique
562 if (in_array($item['network'], [Protocol::DFRN, Protocol::DIASPORA])) {
563 $condition = ['guid' => $item['guid'], 'uid' => $item['uid']];
564 if (Post::exists($condition)) {
565 Logger::notice('duplicated item with the same guid found.', $condition);
568 } elseif ($item['network'] == Protocol::OSTATUS) {
569 // Check for an existing post with the same content. There seems to be a problem with OStatus.
570 $condition = ["`body` = ? AND `network` = ? AND `created` = ? AND `contact-id` = ? AND `uid` = ?",
571 $item['body'], $item['network'], $item['created'], $item['contact-id'], $item['uid']];
572 if (Post::exists($condition)) {
573 Logger::notice('duplicated item with the same body found.', $item);
579 * Check for already added items.
580 * There is a timing issue here that sometimes creates double postings.
581 * An unique index would help - but the limitations of MySQL (maximum size of index values) prevent this.
583 if (($item['uid'] == 0) && Post::exists(['uri-id' => $item['uri-id'], 'uid' => 0])) {
584 Logger::notice('Global item already stored.', ['uri-id' => $item['uri-id'], 'network' => $item['network']]);
592 * Check if the item array is valid
594 * @param array $item Item record
595 * @return boolean item is valid
597 public static function isValid(array $item): bool
599 // When there is no content then we don't post it
600 if (($item['body'] . $item['title'] == '') && empty($item['quote-uri-id']) && empty($item['attachments']) && (empty($item['uri-id']) || !Post\Media::existsByURIId($item['uri-id']))) {
601 Logger::notice('No body, no title.');
605 if (!empty($item['uid'])) {
606 $owner = User::getOwnerDataById($item['uid'], false);
608 Logger::warning('Missing item user owner data', ['uid' => $item['uid']]);
612 if ($owner['account_expired'] || $owner['account_removed']) {
613 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']]);
618 if (!empty($item['author-id']) && Contact::isBlocked($item['author-id'])) {
619 Logger::notice('Author is blocked node-wide', ['author-link' => $item['author-link'], 'item-uri' => $item['uri']]);
623 if (!empty($item['author-link']) && Network::isUrlBlocked($item['author-link'])) {
624 Logger::notice('Author server is blocked', ['author-link' => $item['author-link'], 'item-uri' => $item['uri']]);
628 if (!empty($item['owner-id']) && Contact::isBlocked($item['owner-id'])) {
629 Logger::notice('Owner is blocked node-wide', ['owner-link' => $item['owner-link'], 'item-uri' => $item['uri']]);
633 if (!empty($item['owner-link']) && Network::isUrlBlocked($item['owner-link'])) {
634 Logger::notice('Owner server is blocked', ['owner-link' => $item['owner-link'], 'item-uri' => $item['uri']]);
638 if ($item['verb'] == Activity::FOLLOW) {
639 if (!$item['origin'] && ($item['author-id'] == Contact::getPublicIdByUserId($item['uid']))) {
640 // Our own follow request can be relayed to us. We don't store it to avoid notification chaos.
641 Logger::info("Follow: Don't store not origin follow request", ['parent-uri' => $item['parent-uri']]);
645 $condition = ['verb' => Activity::FOLLOW, 'uid' => $item['uid'],
646 'parent-uri' => $item['parent-uri'], 'author-id' => $item['author-id']];
647 if (Post::exists($condition)) {
648 // It happens that we receive multiple follow requests by the same author - we only store one.
649 Logger::info('Follow: Found existing follow request from author', ['author-id' => $item['author-id'], 'parent-uri' => $item['parent-uri']]);
658 * Check if the item array is too old
660 * @param array $item Item record
661 * @return boolean item is too old
663 public static function isTooOld(array $item): bool
665 // check for create date and expire time
666 $expire_interval = DI::config()->get('system', 'dbclean-expire-days', 0);
668 $user = DBA::selectFirst('user', ['expire'], ['uid' => $item['uid']]);
669 if (DBA::isResult($user) && ($user['expire'] > 0) && (($user['expire'] < $expire_interval) || ($expire_interval == 0))) {
670 $expire_interval = $user['expire'];
673 if (($expire_interval > 0) && !empty($item['created'])) {
674 $expire_date = time() - ($expire_interval * 86400);
675 $created_date = strtotime($item['created']);
676 if ($created_date < $expire_date) {
677 Logger::notice('Item created before expiration interval.', [
678 'created' => date('c', $created_date),
679 'expired' => date('c', $expire_date),
690 * Return the id of the given item array if it has been stored before
692 * @param array $item Item record
693 * @return integer Item id or zero on error
695 private static function getDuplicateID(array $item): int
697 if (empty($item['network']) || in_array($item['network'], Protocol::FEDERATED)) {
698 $condition = ['`uri-id` = ? AND `uid` = ? AND `network` IN (?, ?, ?, ?)',
701 Protocol::ACTIVITYPUB,
706 $existing = Post::selectFirst(['id', 'network'], $condition);
707 if (DBA::isResult($existing)) {
708 // We only log the entries with a different user id than 0. Otherwise we would have too many false positives
709 if ($item['uid'] != 0) {
710 Logger::notice('Item already existed for user', [
711 'uri-id' => $item['uri-id'],
712 'uid' => $item['uid'],
713 'network' => $item['network'],
714 'existing_id' => $existing['id'],
715 'existing_network' => $existing['network']
719 return $existing['id'];
726 * Fetch the uri-id of the parent for the given uri-id
728 * @param integer $uriid
731 public static function getParent(int $uriid): int
733 $thread_parent = Post::selectFirstPost(['thr-parent-id', 'gravity'], ['uri-id' => $uriid]);
734 if (empty($thread_parent)) {
738 if ($thread_parent['gravity'] == Item::GRAVITY_PARENT) {
742 return self::getParent($thread_parent['thr-parent-id']);
746 * Fetch top-level parent data for the given item array
749 * @return array item array with parent data
752 private static function getTopLevelParent(array $item): array
754 $fields = ['uid', 'uri', 'parent-uri', 'id', 'deleted',
755 'uri-id', 'parent-uri-id',
756 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid',
757 'wall', 'private', 'origin', 'author-id'];
758 $condition = ['uri-id' => [$item['thr-parent-id'], $item['parent-uri-id']], 'uid' => $item['uid']];
759 $params = ['order' => ['id' => false]];
760 $parent = Post::selectFirst($fields, $condition, $params);
762 if (!DBA::isResult($parent) && Post::exists(['uri-id' => [$item['thr-parent-id'], $item['parent-uri-id']], 'uid' => 0])) {
763 $stored = Item::storeForUserByUriId($item['thr-parent-id'], $item['uid'], ['post-reason' => Item::PR_COMPLETION]);
764 if (!$stored && ($item['thr-parent-id'] != $item['parent-uri-id'])) {
765 $stored = Item::storeForUserByUriId($item['parent-uri-id'], $item['uid'], ['post-reason' => Item::PR_COMPLETION]);
768 Logger::info('Stored thread parent item for user', ['uri-id' => $item['thr-parent-id'], 'uid' => $item['uid'], 'stored' => $stored]);
769 $parent = Post::selectFirst($fields, $condition, $params);
773 if (!DBA::isResult($parent)) {
774 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)]);
778 if ($parent['uri-id'] == $parent['parent-uri-id']) {
782 $condition = ['uri-id' => $parent['parent-uri-id'],
783 'parent-uri-id' => $parent['parent-uri-id'],
784 'uid' => $parent['uid']];
785 $params = ['order' => ['id' => false]];
786 $toplevel_parent = Post::selectFirst($fields, $condition, $params);
788 if (!DBA::isResult($toplevel_parent) && $item['origin']) {
789 $stored = Item::storeForUserByUriId($item['parent-uri-id'], $item['uid'], ['post-reason' => Item::PR_COMPLETION]);
790 Logger::info('Stored parent item for user', ['uri-id' => $item['parent-uri-id'], 'uid' => $item['uid'], 'stored' => $stored]);
791 $toplevel_parent = Post::selectFirst($fields, $condition, $params);
794 if (!DBA::isResult($toplevel_parent)) {
795 Logger::notice('item top level parent was not found - ignoring item', ['parent-uri-id' => $parent['parent-uri-id'], 'uid' => $parent['uid']]);
799 return $toplevel_parent;
803 * Get the gravity for the given item array
806 * @return integer gravity
808 private static function getGravity(array $item): int
810 $activity = DI::activity();
812 if (isset($item['gravity'])) {
813 return intval($item['gravity']);
814 } elseif ($item['parent-uri-id'] === $item['uri-id']) {
815 return self::GRAVITY_PARENT;
816 } elseif ($activity->match($item['verb'], Activity::POST)) {
817 return self::GRAVITY_COMMENT;
818 } elseif ($activity->match($item['verb'], Activity::FOLLOW)) {
819 return self::GRAVITY_ACTIVITY;
820 } elseif ($activity->match($item['verb'], Activity::ANNOUNCE)) {
821 return self::GRAVITY_ACTIVITY;
824 Logger::info('Unknown gravity for verb', ['verb' => $item['verb']]);
825 return self::GRAVITY_UNKNOWN; // Should not happen
828 private static function prepareOriginPost(array $item): array
830 $item = DI::contentItem()->initializePost($item);
831 $item = DI::contentItem()->finalizePost($item);
837 * Inserts item record
839 * @param array $item Item array to be inserted
840 * @param int $notify Notification (type?)
841 * @param bool $post_local (???)
842 * @return int Zero means error, otherwise primary key (id) is being returned
844 public static function insert(array $item, int $notify = 0, bool $post_local = true): int
848 $priority = Worker::PRIORITY_HIGH;
850 // If it is a posting where users should get notifications, then define it as wall posting
852 $item = self::prepareOriginPost($item);
854 if (is_int($notify) && in_array($notify, Worker::PRIORITIES)) {
858 $item['network'] = trim(($item['network'] ?? '') ?: Protocol::PHANTOM);
861 $uid = intval($item['uid']);
863 $item['guid'] = self::guid($item, $notify);
864 $item['uri'] = substr(trim($item['uri'] ?? '') ?: self::newURI($item['guid']), 0, 255);
867 $item['uri-id'] = ItemURI::insert(['uri' => $item['uri'], 'guid' => $item['guid']]);
869 // Backward compatibility: parent-uri used to be the direct parent uri.
870 // If it is provided without a thr-parent, it probably is the old behavior.
871 if (empty($item['thr-parent']) || empty($item['parent-uri'])) {
872 $item['thr-parent'] = trim($item['thr-parent'] ?? $item['parent-uri'] ?? $item['uri']);
873 $item['parent-uri'] = $item['thr-parent'];
876 $item['thr-parent-id'] = ItemURI::getIdByURI($item['thr-parent']);
877 $item['parent-uri-id'] = ItemURI::getIdByURI($item['parent-uri']);
879 // Store conversation data
880 $source = $item['source'] ?? '';
881 unset($item['conversation-uri']);
882 unset($item['conversation-href']);
883 unset($item['source']);
886 * Do we already have this item?
887 * We have to check several networks since Friendica posts could be repeated
888 * via OStatus (maybe Diaspora as well)
890 $duplicate = self::getDuplicateID($item);
895 // Additional duplicate checks
896 /// @todo Check why the first duplication check returns the item number and the second a 0
897 if (self::isDuplicate($item)) {
901 if (!isset($item['post-type'])) {
902 $item['post-type'] = empty($item['title']) ? self::PT_NOTE : self::PT_ARTICLE;
905 $defined_permissions = isset($item['allow_cid']) && isset($item['allow_gid']) && isset($item['deny_cid']) && isset($item['deny_gid']) && isset($item['private']);
907 $item['wall'] = intval($item['wall'] ?? 0);
908 $item['extid'] = trim($item['extid'] ?? '');
909 $item['author-name'] = trim($item['author-name'] ?? '');
910 $item['author-link'] = trim($item['author-link'] ?? '');
911 $item['author-avatar'] = trim($item['author-avatar'] ?? '');
912 $item['owner-name'] = trim($item['owner-name'] ?? '');
913 $item['owner-link'] = trim($item['owner-link'] ?? '');
914 $item['owner-avatar'] = trim($item['owner-avatar'] ?? '');
915 $item['received'] = (isset($item['received']) ? DateTimeFormat::utc($item['received']) : DateTimeFormat::utcNow());
916 $item['created'] = (isset($item['created']) ? DateTimeFormat::utc($item['created']) : $item['received']);
917 $item['edited'] = (isset($item['edited']) ? DateTimeFormat::utc($item['edited']) : $item['created']);
918 $item['changed'] = (isset($item['changed']) ? DateTimeFormat::utc($item['changed']) : $item['created']);
919 $item['commented'] = (isset($item['commented']) ? DateTimeFormat::utc($item['commented']) : $item['created']);
920 $item['title'] = substr(trim($item['title'] ?? ''), 0, 255);
921 $item['location'] = trim($item['location'] ?? '');
922 $item['coord'] = trim($item['coord'] ?? '');
923 $item['visible'] = (isset($item['visible']) ? intval($item['visible']) : 1);
924 $item['deleted'] = 0;
925 $item['verb'] = trim($item['verb'] ?? '');
926 $item['object-type'] = trim($item['object-type'] ?? '');
927 $item['object'] = trim($item['object'] ?? '');
928 $item['target-type'] = trim($item['target-type'] ?? '');
929 $item['target'] = trim($item['target'] ?? '');
930 $item['plink'] = substr(trim($item['plink'] ?? ''), 0, 255);
931 $item['allow_cid'] = trim($item['allow_cid'] ?? '');
932 $item['allow_gid'] = trim($item['allow_gid'] ?? '');
933 $item['deny_cid'] = trim($item['deny_cid'] ?? '');
934 $item['deny_gid'] = trim($item['deny_gid'] ?? '');
935 $item['private'] = intval($item['private'] ?? self::PUBLIC);
936 $item['body'] = trim($item['body'] ?? '');
937 $item['raw-body'] = trim($item['raw-body'] ?? $item['body']);
938 $item['app'] = trim($item['app'] ?? '');
939 $item['origin'] = intval($item['origin'] ?? 0);
940 $item['postopts'] = trim($item['postopts'] ?? '');
941 $item['resource-id'] = trim($item['resource-id'] ?? '');
942 $item['event-id'] = intval($item['event-id'] ?? 0);
943 $item['inform'] = trim($item['inform'] ?? '');
944 $item['file'] = trim($item['file'] ?? '');
946 // Communities aren't working with the Diaspora protocol
947 if (($uid != 0) && ($item['network'] == Protocol::DIASPORA)) {
948 $user = User::getById($uid, ['account-type']);
949 if ($user['account-type'] == Contact::TYPE_COMMUNITY) {
950 Logger::info('Community posts are not supported via Diaspora');
955 // Items cannot be stored before they happen ...
956 if ($item['created'] > DateTimeFormat::utcNow()) {
957 $item['created'] = DateTimeFormat::utcNow();
960 // We haven't invented time travel by now.
961 if ($item['edited'] > DateTimeFormat::utcNow()) {
962 $item['edited'] = DateTimeFormat::utcNow();
965 $item['plink'] = ($item['plink'] ?? '') ?: DI::baseUrl() . '/display/' . urlencode($item['guid']);
967 $item['gravity'] = self::getGravity($item);
969 $default = ['url' => $item['author-link'], 'name' => $item['author-name'],
970 'photo' => $item['author-avatar'], 'network' => $item['network']];
971 $item['author-id'] = ($item['author-id'] ?? 0) ?: Contact::getIdForURL($item['author-link'], 0, null, $default);
973 $default = ['url' => $item['owner-link'], 'name' => $item['owner-name'],
974 'photo' => $item['owner-avatar'], 'network' => $item['network']];
975 $item['owner-id'] = ($item['owner-id'] ?? 0) ?: Contact::getIdForURL($item['owner-link'], 0, null, $default);
977 $item['post-reason'] = self::getPostReason($item);
979 // Ensure that there is an avatar cache
980 Contact::checkAvatarCache($item['author-id']);
981 Contact::checkAvatarCache($item['owner-id']);
983 $item['contact-id'] = self::contactId($item);
985 if (!empty($item['direction']) && in_array($item['direction'], [Conversation::PUSH, Conversation::RELAY]) &&
986 empty($item['origin']) && self::isTooOld($item)) {
987 Logger::info('Item is too old', ['item' => $item]);
991 if (!self::isValid($item)) {
995 if ($item['gravity'] !== self::GRAVITY_PARENT) {
996 $toplevel_parent = self::getTopLevelParent($item);
997 if (empty($toplevel_parent)) {
1001 $parent_id = $toplevel_parent['id'];
1002 $item['parent-uri'] = $toplevel_parent['uri'];
1003 $item['parent-uri-id'] = $toplevel_parent['uri-id'];
1004 $item['deleted'] = $toplevel_parent['deleted'];
1005 $item['wall'] = $toplevel_parent['wall'];
1007 // Reshares have to keep their permissions to allow forums to work
1008 if (!$defined_permissions && (!$item['origin'] || ($item['verb'] != Activity::ANNOUNCE))) {
1009 $item['allow_cid'] = $toplevel_parent['allow_cid'];
1010 $item['allow_gid'] = $toplevel_parent['allow_gid'];
1011 $item['deny_cid'] = $toplevel_parent['deny_cid'];
1012 $item['deny_gid'] = $toplevel_parent['deny_gid'];
1015 $parent_origin = $toplevel_parent['origin'];
1017 // Don't federate received participation messages
1018 if ($item['verb'] != Activity::FOLLOW) {
1019 $item['wall'] = $toplevel_parent['wall'];
1021 $item['wall'] = false;
1022 // Participations are technical messages, so they are set to "seen" automatically
1023 $item['unseen'] = false;
1027 * If the parent is private, force privacy for the entire conversation
1028 * This differs from the above settings as it subtly allows comments from
1029 * email correspondents to be private even if the overall thread is not.
1031 if (!$defined_permissions && $toplevel_parent['private']) {
1032 $item['private'] = $toplevel_parent['private'];
1035 // If its a post that originated here then tag the thread as "mention"
1036 if ($item['origin'] && $item['uid']) {
1037 DBA::update('post-thread-user', ['mention' => true], ['uri-id' => $item['parent-uri-id'], 'uid' => $item['uid']]);
1038 Logger::info('tagged thread as mention', ['parent' => $parent_id, 'parent-uri-id' => $item['parent-uri-id'], 'uid' => $item['uid']]);
1041 // Update the contact relations
1042 Contact\Relation::store($toplevel_parent['author-id'], $item['author-id'], $item['created']);
1045 $parent_origin = $item['origin'];
1047 if ($item['wall'] && empty($item['conversation'])) {
1048 $item['conversation'] = $item['parent-uri'] . '#context';
1052 if ($item['origin']) {
1053 if (Photo::setPermissionFromBody($item['body'], $item['uid'], $item['contact-id'], $item['allow_cid'], $item['allow_gid'], $item['deny_cid'], $item['deny_gid'])) {
1054 $item['object-type'] = Activity\ObjectType::IMAGE;
1057 $item = DI::contentItem()->moveAttachmentsFromBodyToAttach($item);
1060 $item['parent-uri-id'] = ItemURI::getIdByURI($item['parent-uri']);
1061 $item['thr-parent-id'] = ItemURI::getIdByURI($item['thr-parent']);
1063 if (!empty($item['conversation']) && empty($item['conversation-id'])) {
1064 $item['conversation-id'] = ItemURI::getIdByURI($item['conversation']);
1067 // Is this item available in the global items (with uid=0)?
1068 if ($item['uid'] == 0) {
1069 $item['global'] = true;
1071 // Set the global flag on all items if this was a global item entry
1072 Post::update(['global' => true], ['uri-id' => $item['uri-id']]);
1074 $item['global'] = Post::exists(['uid' => 0, 'uri-id' => $item['uri-id']]);
1078 if (!$defined_permissions && !empty($item['allow_cid'] . $item['allow_gid'] . $item['deny_cid'] . $item['deny_gid'])) {
1079 $item['private'] = self::PRIVATE;
1082 if ($notify && $post_local) {
1083 $item['edit'] = false;
1084 $item['parent'] = $parent_id;
1086 // Trigger automatic reactions for addons
1087 if (!isset($item['api_source'])) {
1088 $item['api_source'] = true;
1091 // We have to tell the hooks who we are - this really should be improved
1092 if (!DI::userSession()->getLocalUserId()) {
1093 $_SESSION['authenticated'] = true;
1094 $_SESSION['uid'] = $uid;
1095 $dummy_session = true;
1097 $dummy_session = false;
1100 Hook::callAll('post_local', $item);
1102 if ($dummy_session) {
1103 unset($_SESSION['authenticated']);
1104 unset($_SESSION['uid']);
1106 } elseif (!$notify) {
1107 Hook::callAll('post_remote', $item);
1110 if (!empty($item['cancel'])) {
1111 Logger::notice('post cancelled by addon.');
1115 if (empty($item['vid']) && !empty($item['verb'])) {
1116 $item['vid'] = Verb::getID($item['verb']);
1119 // Creates or assigns the permission set
1120 $item['psid'] = DI::permissionSet()->selectOrCreate(
1121 DI::permissionSetFactory()->createFromString(
1129 if (!empty($item['extid'])) {
1130 $item['external-id'] = ItemURI::getIdByURI($item['extid']);
1133 if ($item['verb'] == Activity::ANNOUNCE) {
1134 self::setOwnerforResharedItem($item);
1137 if (isset($item['attachments'])) {
1138 foreach ($item['attachments'] as $attachment) {
1139 $attachment['uri-id'] = $item['uri-id'];
1140 Post\Media::insert($attachment);
1142 unset($item['attachments']);
1145 if (empty($item['quote-uri-id'])) {
1146 $quote_id = self::getQuoteUriId($item['body']);
1147 if (!empty($quote_id)) {
1148 // This is one of these "should not happen" situations.
1149 // The protocol implementations should already have done this job.
1150 Logger::notice('Quote-uri-id detected in post', ['id' => $quote_id, 'guid' => $item['guid'], 'uri-id' => $item['uri-id'], 'callstack' => System::callstack(20)]);
1151 $item['quote-uri-id'] = $quote_id;
1155 if (!empty($item['quote-uri-id'])) {
1156 $item['raw-body'] = BBCode::removeSharedData($item['raw-body']);
1157 $item['body'] = BBCode::removeSharedData($item['body']);
1160 // Remove all media attachments from the body and store them in the post-media table
1161 $item['raw-body'] = Post\Media::insertFromBody($item['uri-id'], $item['raw-body']);
1162 $item['raw-body'] = self::setHashtags($item['raw-body']);
1164 $author = Contact::getById($item['author-id'], ['network']);
1165 Post\Media::insertFromRelevantUrl($item['uri-id'], $item['raw-body'], $item['body'], $author['network'] ?? '');
1167 Post\Media::insertFromAttachmentData($item['uri-id'], $item['body']);
1168 $item['body'] = BBCode::removeAttachment($item['body']);
1169 $item['raw-body'] = BBCode::removeAttachment($item['raw-body']);
1171 // Check for hashtags in the body and repair or add hashtag links
1172 $item['body'] = self::setHashtags($item['body']);
1174 $item['language'] = self::getLanguage($item);
1176 $notify_type = Delivery::POST;
1178 // Filling item related side tables
1179 if (!empty($item['attach'])) {
1180 Post\Media::insertFromAttachment($item['uri-id'], $item['attach']);
1183 if (empty($item['event-id'])) {
1184 unset($item['event-id']);
1186 $ev = Event::fromBBCode($item['body']);
1187 if ((!empty($ev['desc']) || !empty($ev['summary'])) && !empty($ev['start'])) {
1188 Logger::info('Event found.');
1189 $ev['cid'] = $item['contact-id'];
1190 $ev['uid'] = $item['uid'];
1191 $ev['uri'] = $item['uri'];
1192 $ev['edited'] = $item['edited'];
1193 $ev['private'] = $item['private'];
1194 $ev['guid'] = $item['guid'];
1195 $ev['plink'] = $item['plink'];
1196 $ev['network'] = $item['network'];
1197 $ev['protocol'] = $item['protocol'] ?? Conversation::PARCEL_UNKNOWN;
1198 $ev['direction'] = $item['direction'] ?? Conversation::UNKNOWN;
1199 $ev['source'] = $item['source'] ?? '';
1201 $event = DBA::selectFirst('event', ['id'], ['uri' => $item['uri'], 'uid' => $item['uid']]);
1202 if (DBA::isResult($event)) {
1203 $ev['id'] = $event['id'];
1206 $event_id = Event::store($ev);
1207 $item = Event::getItemArrayForImportedId($event_id, $item);
1209 Logger::info('Event was stored', ['id' => $event_id]);
1213 if (empty($item['causer-id'])) {
1214 unset($item['causer-id']);
1217 if (in_array($item['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN])) {
1218 $content_warning = BBCode::getAbstract($item['body'], Protocol::ACTIVITYPUB);
1219 if (!empty($content_warning) && empty($item['content-warning'])) {
1220 $item['content-warning'] = BBCode::toPlaintext($content_warning);
1224 Post::insert($item['uri-id'], $item);
1226 if ($item['gravity'] == self::GRAVITY_PARENT) {
1227 Post\Thread::insert($item['uri-id'], $item);
1230 // The content of activities normally doesn't matter - except for likes from Misskey
1231 if (!in_array($item['verb'], self::ACTIVITIES) || in_array($item['verb'], [Activity::LIKE, Activity::DISLIKE]) && !empty($item['body']) && (mb_strlen($item['body']) == 1)) {
1232 Post\Content::insert($item['uri-id'], $item);
1235 $item['parent'] = $parent_id;
1237 // Create Diaspora signature
1238 if ($item['origin'] && empty($item['diaspora_signed_text']) && ($item['gravity'] != self::GRAVITY_PARENT)) {
1239 $signed = Diaspora::createCommentSignature($item);
1240 if (!empty($signed)) {
1241 $item['diaspora_signed_text'] = json_encode($signed);
1245 if (!empty($item['diaspora_signed_text'])) {
1246 DBA::replace('diaspora-interaction', ['uri-id' => $item['uri-id'], 'interaction' => $item['diaspora_signed_text']]);
1249 // Attached file links
1250 if (!empty($item['file'])) {
1251 Post\Category::storeTextByURIId($item['uri-id'], $item['uid'], $item['file']);
1254 // Delivery relevant data
1255 $delivery_data = Post\DeliveryData::extractFields($item);
1257 if (!empty($item['origin']) || !empty($item['wall']) || !empty($delivery_data['postopts']) || !empty($delivery_data['inform'])) {
1258 Post\DeliveryData::insert($item['uri-id'], $delivery_data);
1261 // Store tags from the body if this hadn't been handled previously in the protocol classes
1262 if (!Tag::existsForPost($item['uri-id'])) {
1263 Tag::storeFromBody($item['uri-id'], $item['body']);
1266 $condition = ['uri-id' => $item['uri-id'], 'uid' => $item['uid']];
1267 if (Post::exists($condition)) {
1268 Logger::notice('Item is already inserted - aborting', $condition);
1272 $post_user_id = Post\User::insert($item['uri-id'], $item['uid'], $item);
1273 if (!$post_user_id) {
1274 Logger::notice('Post-User is already inserted - aborting', ['uid' => $item['uid'], 'uri-id' => $item['uri-id']]);
1278 if ($item['gravity'] == self::GRAVITY_PARENT) {
1279 $item['post-user-id'] = $post_user_id;
1280 Post\ThreadUser::insert($item['uri-id'], $item['uid'], $item);
1283 Logger::notice('created item', ['post-id' => $post_user_id, 'uid' => $item['uid'], 'network' => $item['network'], 'uri-id' => $item['uri-id'], 'guid' => $item['guid']]);
1285 $posted_item = Post::selectFirst(self::ITEM_FIELDLIST, ['post-user-id' => $post_user_id]);
1286 if (!DBA::isResult($posted_item)) {
1287 // On failure store the data into a spool file so that the "SpoolPost" worker can try again later.
1288 Logger::warning('Could not store item. it will be spooled', ['id' => $post_user_id]);
1289 self::spool($orig_item);
1293 // update the commented timestamp on the parent
1294 if (DI::config()->get('system', 'like_no_comment')) {
1295 // Update when it is a comment
1296 $update_commented = in_array($posted_item['gravity'], [self::GRAVITY_PARENT, self::GRAVITY_COMMENT]);
1298 // Update when it isn't a follow or tag verb
1299 $update_commented = !in_array($posted_item['verb'], [Activity::FOLLOW, Activity::TAG]);
1302 if ($update_commented) {
1303 $fields = ['commented' => DateTimeFormat::utcNow(), 'changed' => DateTimeFormat::utcNow()];
1305 $fields = ['changed' => DateTimeFormat::utcNow()];
1308 Post::update($fields, ['uri-id' => $posted_item['parent-uri-id'], 'uid' => $posted_item['uid']]);
1310 // In that function we check if this is a forum post. Additionally we delete the item under certain circumstances
1311 if (self::tagDeliver($posted_item['uid'], $post_user_id)) {
1312 // Get the user information for the logging
1313 $user = User::getById($uid);
1315 Logger::notice('Item had been deleted', ['id' => $post_user_id, 'user' => $uid, 'account-type' => $user['account-type']]);
1320 DI::contentItem()->postProcessPost($posted_item);
1322 Hook::callAll('post_remote_end', $posted_item);
1325 if ($posted_item['gravity'] === self::GRAVITY_PARENT) {
1326 self::addShadow($post_user_id);
1328 self::addShadowPost($post_user_id);
1331 self::updateContact($posted_item);
1333 Post\UserNotification::setNotification($posted_item['uri-id'], $posted_item['uid']);
1335 // Distribute items to users who subscribed to their tags
1336 self::distributeByTags($posted_item);
1338 // Automatically reshare the item if the "remote_self" option is selected
1339 self::autoReshare($posted_item);
1341 $transmit = $notify || ($posted_item['visible'] && ($parent_origin || $posted_item['origin']));
1344 if ($posted_item['uid'] && Contact\User::isBlocked($posted_item['author-id'], $posted_item['uid'])) {
1345 Logger::info('Message from blocked author will not be relayed', ['item' => $posted_item['id'], 'uri' => $posted_item['uri'], 'cid' => $posted_item['author-id']]);
1348 if ($transmit && $posted_item['uid'] && Contact\User::isBlocked($posted_item['owner-id'], $posted_item['uid'])) {
1349 Logger::info('Message from blocked owner will not be relayed', ['item' => $posted_item['id'], 'uri' => $posted_item['uri'], 'cid' => $posted_item['owner-id']]);
1352 if ($transmit && !empty($posted_item['causer-id']) && $posted_item['uid'] && Contact\User::isBlocked($posted_item['causer-id'], $posted_item['uid'])) {
1353 Logger::info('Message from blocked causer will not be relayed', ['item' => $posted_item['id'], 'uri' => $posted_item['uri'], 'cid' => $posted_item['causer-id']]);
1357 // Don't relay participation messages
1358 if (($posted_item['verb'] == Activity::FOLLOW) &&
1359 (!$posted_item['origin'] || ($posted_item['author-id'] != Contact::getPublicIdByUserId($uid)))) {
1360 Logger::info('Participation messages will not be relayed', ['item' => $posted_item['id'], 'uri' => $posted_item['uri'], 'verb' => $posted_item['verb']]);
1365 if (!empty($source) && ($transmit || DI::config()->get('debug', 'store_source'))) {
1366 Post\Activity::insert($item['uri-id'], $source);
1370 Worker::add(['priority' => $priority, 'dont_fork' => true], 'Notifier', $notify_type, (int)$posted_item['uri-id'], (int)$posted_item['uid']);
1373 // Fill the cache with the rendered content.
1374 if (in_array($posted_item['gravity'], [self::GRAVITY_PARENT, self::GRAVITY_COMMENT]) && ($posted_item['uid'] == 0)) {
1375 self::updateDisplayCache($posted_item['uri-id']);
1378 return $post_user_id;
1382 * Fetch the post reason for a given item array
1384 * @param array $item
1388 public static function getPostReason(array $item): int
1390 $actor = ($item['gravity'] == self::GRAVITY_PARENT) ? $item['owner-id'] : $item['author-id'];
1391 if (empty($item['origin']) && ($item['uid'] != 0) && Contact::isSharing($actor, $item['uid'])) {
1392 return self::PR_FOLLOWER;
1395 if (!empty($item['origin']) && empty($item['post-reason'])) {
1396 return self::PR_LOCAL;
1399 return $item['post-reason'] ?? self::PR_NONE;
1403 * Update the display cache
1405 * @param integer $uri_id
1407 * @throws InternalServerErrorException
1408 * @throws \ImagickException
1410 public static function updateDisplayCache(int $uri_id)
1412 $item = Post::selectFirst(self::DISPLAY_FIELDLIST, ['uri-id' => $uri_id]);
1417 self::prepareBody($item, false, false, true);
1421 * Change the owner of a parent item if it had been shared by a forum
1423 * (public) forum posts in the new format consist of the regular post by the author
1424 * followed by an announce message sent from the forum account.
1425 * Changing the owner helps in grouping forum posts.
1427 * @param array $item
1430 private static function setOwnerforResharedItem(array $item)
1432 $parent = Post::selectFirst(['id', 'causer-id', 'owner-id', 'author-id', 'author-link', 'origin', 'post-reason'],
1433 ['uri-id' => $item['thr-parent-id'], 'uid' => $item['uid']]);
1434 if (!DBA::isResult($parent)) {
1435 Logger::error('Parent not found', ['uri-id' => $item['thr-parent-id'], 'uid' => $item['uid']]);
1439 $author = Contact::selectFirst(['url', 'contact-type', 'network'], ['id' => $item['author-id']]);
1440 if (!DBA::isResult($author)) {
1441 Logger::error('Author not found', ['id' => $item['author-id']]);
1445 $self_contact = Contact::selectFirst(['id'], ['uid' => $item['uid'], 'self' => true]);
1446 $self = !empty($self_contact) ? $self_contact['id'] : 0;
1448 $cid = Contact::getIdForURL($author['url'], $item['uid']);
1449 if (empty($cid) || (!Contact::isSharing($cid, $item['uid']) && ($cid != $self))) {
1450 Logger::info('The resharer is not a following contact: quit', ['resharer' => $author['url'], 'uid' => $item['uid'], 'cid' => $cid]);
1454 if ($author['contact-type'] != Contact::TYPE_COMMUNITY) {
1455 if ($parent['post-reason'] == self::PR_ANNOUNCEMENT) {
1456 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']]);
1460 if (Contact::isSharing($parent['owner-id'], $item['uid'])) {
1461 Logger::info('The resharer is no forum: quit', ['resharer' => $item['author-id'], 'owner' => $parent['owner-id'], 'author' => $parent['author-id'], 'uid' => $item['uid']]);
1466 self::update(['post-reason' => self::PR_ANNOUNCEMENT, 'causer-id' => $item['author-id']], ['id' => $parent['id']]);
1467 Logger::info('Set announcement post-reason', ['uri-id' => $item['uri-id'], 'thr-parent-id' => $item['thr-parent-id'], 'uid' => $item['uid']]);
1471 * Distribute the given item to users who subscribed to their tags
1473 * @param array $item Processed item
1475 private static function distributeByTags(array $item)
1477 if (($item['uid'] != 0) || ($item['gravity'] != self::GRAVITY_PARENT) || !in_array($item['network'], Protocol::FEDERATED)) {
1481 $uids = Tag::getUIDListByURIId($item['uri-id']);
1482 foreach ($uids as $uid) {
1483 $stored = self::storeForUserByUriId($item['uri-id'], $uid, ['post-reason' => self::PR_TAG]);
1484 Logger::info('Stored item for users', ['uri-id' => $item['uri-id'], 'uid' => $uid, 'stored' => $stored]);
1489 * Distributes public items to the receivers
1491 * @param integer $itemid Item ID that should be added
1492 * @param string $signed_text Original text (for Diaspora signatures), JSON encoded.
1493 * @throws \Exception
1495 public static function distribute(int $itemid, string $signed_text = '')
1497 $condition = ["`id` IN (SELECT `parent` FROM `post-user-view` WHERE `id` = ?)", $itemid];
1498 $parent = Post::selectFirst(['owner-id'], $condition);
1499 if (!DBA::isResult($parent)) {
1500 Logger::warning('Item not found', ['condition' => $condition]);
1504 // Only distribute public items from native networks
1505 $condition = ['id' => $itemid, 'uid' => 0,
1506 'network' => array_merge(Protocol::FEDERATED ,['']),
1507 'visible' => true, 'deleted' => false, 'private' => [self::PUBLIC, self::UNLISTED]];
1508 $item = Post::selectFirst(array_merge(self::ITEM_FIELDLIST, ['protocol']), $condition);
1509 if (!DBA::isResult($item)) {
1510 Logger::warning('Item not found', ['condition' => $condition]);
1514 $origin = $item['origin'];
1518 /// @todo add a field "pcid" in the contact table that refers to the public contact id.
1519 $owner = DBA::selectFirst('contact', ['url', 'nurl', 'alias'], ['id' => $parent['owner-id']]);
1520 if (!DBA::isResult($owner)) {
1524 $condition = ['nurl' => $owner['nurl'], 'rel' => [Contact::SHARING, Contact::FRIEND]];
1525 $contacts = DBA::select('contact', ['uid'], $condition);
1526 while ($contact = DBA::fetch($contacts)) {
1527 if ($contact['uid'] == 0) {
1531 $users[$contact['uid']] = $contact['uid'];
1533 DBA::close($contacts);
1535 $condition = ['alias' => $owner['url'], 'rel' => [Contact::SHARING, Contact::FRIEND]];
1536 $contacts = DBA::select('contact', ['uid'], $condition);
1537 while ($contact = DBA::fetch($contacts)) {
1538 if ($contact['uid'] == 0) {
1542 $users[$contact['uid']] = $contact['uid'];
1544 DBA::close($contacts);
1546 if (!empty($owner['alias'])) {
1547 $condition = ['nurl' => Strings::normaliseLink($owner['alias']), 'rel' => [Contact::SHARING, Contact::FRIEND]];
1548 $contacts = DBA::select('contact', ['uid'], $condition);
1549 while ($contact = DBA::fetch($contacts)) {
1550 if ($contact['uid'] == 0) {
1554 $users[$contact['uid']] = $contact['uid'];
1556 DBA::close($contacts);
1561 if ($item['uri-id'] != $item['parent-uri-id']) {
1562 $parents = Post::select(['uid', 'origin'], ["`uri-id` = ? AND `uid` != 0", $item['parent-uri-id']]);
1563 while ($parent = Post::fetch($parents)) {
1564 $users[$parent['uid']] = $parent['uid'];
1565 if ($parent['origin'] && !$origin) {
1566 $origin_uid = $parent['uid'];
1569 DBA::close($parents);
1572 foreach ($users as $uid) {
1573 if ($origin_uid == $uid) {
1574 $item['diaspora_signed_text'] = $signed_text;
1576 $item['post-reason'] = self::PR_DISTRIBUTE;
1577 self::storeForUser($item, $uid);
1582 * Store a public item defined by their URI-ID for the given users
1584 * @param integer $uri_id URI-ID of the given item
1585 * @param integer $uid The user that will receive the item entry
1586 * @param array $fields Additional fields to be stored
1587 * @param integer $source_uid User id of the source post
1588 * @return integer stored item id
1590 public static function storeForUserByUriId(int $uri_id, int $uid, array $fields = [], int $source_uid = 0): int
1592 if ($uid == $source_uid) {
1593 Logger::warning('target UID must not be be equal to the source UID', ['uri-id' => $uri_id, 'uid' => $uid]);
1597 $item = Post::selectFirst(array_merge(self::ITEM_FIELDLIST, ['protocol']), ['uri-id' => $uri_id, 'uid' => $source_uid]);
1598 if (!DBA::isResult($item)) {
1599 Logger::warning('Item could not be fetched', ['uri-id' => $uri_id, 'uid' => $source_uid]);
1603 if (($uid != 0) && ($item['gravity'] == self::GRAVITY_PARENT)) {
1604 $owner = User::getOwnerDataById($uid);
1605 if (($owner['contact-type'] == User::ACCOUNT_TYPE_COMMUNITY) && !Tag::isMentioned($uri_id, $owner['url'])) {
1606 Logger::info('Target user is a forum but is not mentioned here, thread will not be stored', ['uid' => $uid, 'uri-id' => $uri_id]);
1611 if (($source_uid == 0) && (($item['private'] == self::PRIVATE) || !in_array($item['network'], Protocol::FEDERATED))) {
1612 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']]);
1616 $item['post-reason'] = self::PR_STORED;
1618 $item = array_merge($item, $fields);
1620 if (($uid != 0) && Contact::isSharing(($item['gravity'] == Item::GRAVITY_PARENT) ? $item['owner-id'] : $item['author-id'], $uid)) {
1621 $item['post-reason'] = self::PR_FOLLOWER;
1624 $is_reshare = ($item['gravity'] == self::GRAVITY_ACTIVITY) && ($item['verb'] == Activity::ANNOUNCE);
1626 if (($uid != 0) && (($item['gravity'] == self::GRAVITY_PARENT) || $is_reshare) &&
1627 DI::pConfig()->get($uid, 'system', 'accept_only_sharer') == self::COMPLETION_NONE &&
1628 !in_array($item['post-reason'], [self::PR_FOLLOWER, self::PR_TAG, self::PR_TO, self::PR_CC, self::PR_ACTIVITY, self::PR_AUDIENCE])) {
1629 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']]);
1633 $causer = $item['causer-id'] ?: $item['author-id'];
1635 if (($uri_id != $item['parent-uri-id']) && ($item['gravity'] == self::GRAVITY_COMMENT) && !Post::exists(['uri-id' => $item['parent-uri-id'], 'uid' => $uid])) {
1636 if (!self::fetchParent($item['parent-uri-id'], $uid, $causer)) {
1637 Logger::info('Parent post had not been added', ['uri-id' => $item['parent-uri-id'], 'uid' => $uid, 'causer' => $causer]);
1640 Logger::info('Fetched parent post', ['uri-id' => $item['parent-uri-id'], 'uid' => $uid, 'causer' => $causer]);
1641 } elseif (($uri_id != $item['thr-parent-id']) && $is_reshare && !Post::exists(['uri-id' => $item['thr-parent-id'], 'uid' => $uid])) {
1642 if (!self::fetchParent($item['thr-parent-id'], $uid, $causer)) {
1643 Logger::info('Thread parent had not been added', ['uri-id' => $item['thr-parent-id'], 'uid' => $uid, 'causer' => $causer]);
1646 Logger::info('Fetched thread parent', ['uri-id' => $item['thr-parent-id'], 'uid' => $uid, 'causer' => $causer]);
1649 $stored = self::storeForUser($item, $uid);
1650 Logger::info('Item stored for user', ['uri-id' => $item['uri-id'], 'uid' => $uid, 'causer' => $causer, 'source-uid' => $source_uid, 'stored' => $stored]);
1655 * Fetch the parent with the given uri-id
1657 * @param integer $uri_id
1658 * @param integer $uid
1659 * @param integer $causer
1663 private static function fetchParent(int $uri_id, int $uid, int $causer): int
1665 // Fetch the origin user for the post
1666 $origin_uid = self::GetOriginUidForUriId($uri_id, $uid);
1667 if (is_null($origin_uid)) {
1668 Logger::info('Origin item was not found', ['uid' => $uid, 'uri-id' => $uri_id]);
1672 return self::storeForUserByUriId($uri_id, $uid, ['causer-id' => $causer, 'post-reason' => self::PR_FETCHED], $origin_uid);
1676 * Returns the origin uid of a post if the given user is allowed to see it.
1682 private static function GetOriginUidForUriId(int $uriid, int $uid)
1684 if (Post::exists(['uri-id' => $uriid, 'uid' => $uid])) {
1688 $post = Post::selectFirst(['uid', 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid', 'private'], ['uri-id' => $uriid, 'origin' => true]);
1689 if (!empty($post)) {
1690 if (in_array($post['private'], [Item::PUBLIC, Item::UNLISTED])) {
1691 return $post['uid'];
1694 $pcid = Contact::getPublicIdByUserId($uid);
1699 foreach (Item::enumeratePermissions($post, true) as $receiver) {
1700 if ($receiver == $pcid) {
1701 return $post['uid'];
1708 if (Post::exists(['uri-id' => $uriid, 'uid' => 0])) {
1712 // When the post belongs to a a forum then all forum users are allowed to access it
1713 foreach (Tag::getByURIId($uriid, [Tag::MENTION, Tag::EXCLUSIVE_MENTION]) as $tag) {
1714 if (DBA::exists('contact', ['uid' => $uid, 'nurl' => Strings::normaliseLink($tag['url']), 'contact-type' => Contact::TYPE_COMMUNITY])) {
1715 $target_uid = User::getIdForURL($tag['url']);
1716 if (!empty($target_uid)) {
1726 * Store a public item array for the given users
1728 * @param array $item The item entry that will be stored
1729 * @param integer $uid The user that will receive the item entry
1730 * @return integer stored item id
1731 * @throws \Exception
1733 private static function storeForUser(array $item, int $uid): int
1735 $post = Post::selectFirst(['id'], ['uri-id' => $item['uri-id'], 'uid' => $uid]);
1736 if (!empty($post['id'])) {
1737 if (!empty($item['event-id'])) {
1738 $event_post = Post::selectFirst(['event-id'], ['uri-id' => $item['uri-id'], 'uid' => $uid]);
1739 if (!empty($event_post['event-id'])) {
1740 $event = DBA::selectFirst('event', ['edited', 'start', 'finish', 'summary', 'desc', 'location', 'nofinish'], ['id' => $item['event-id']]);
1741 if (!empty($event)) {
1742 // We aren't using "Event::store" here, since we don't want to trigger any further action
1743 $ret = DBA::update('event', $event, ['id' => $event_post['event-id']]);
1744 Logger::info('Event updated', ['uid' => $uid, 'source-event' => $item['event-id'], 'target-event' => $event_post['event-id'], 'ret' => $ret]);
1748 Logger::info('Item already exists', ['uri-id' => $item['uri-id'], 'uid' => $uid, 'id' => $post['id']]);
1752 // Data from the "post-user" table
1754 unset($item['mention']);
1755 unset($item['starred']);
1756 unset($item['unseen']);
1757 unset($item['psid']);
1758 unset($item['pinned']);
1759 unset($item['ignored']);
1760 unset($item['pubmail']);
1761 unset($item['event-id']);
1762 unset($item['hidden']);
1763 unset($item['notification-type']);
1765 // Data from the "post-delivery-data" table
1766 unset($item['postopts']);
1767 unset($item['inform']);
1769 $item['uid'] = $uid;
1770 $item['origin'] = 0;
1774 if ($item['gravity'] == self::GRAVITY_PARENT) {
1775 $contact = DBA::selectFirst('contact', [], ['id' => $item['contact-id'], 'self' => false]);
1776 if (DBA::isResult($contact)) {
1777 $notify = self::isRemoteSelf($contact, $item);
1778 $item['wall'] = (bool)$notify;
1782 $item['contact-id'] = self::contactId($item);
1783 $distributed = self::insert($item, $notify);
1785 if (!$distributed) {
1786 Logger::info("Distributed item wasn't stored", ['uri-id' => $item['uri-id'], 'user' => $uid]);
1788 Logger::info('Distributed item was stored', ['uri-id' => $item['uri-id'], 'user' => $uid, 'stored' => $distributed]);
1790 return $distributed;
1794 * Add a shadow entry for a given item id that is a thread starter
1796 * We store every public item entry additionally with the user id "0".
1797 * This is used for the community page and for the search.
1798 * It is planned that in the future we will store public item entries only once.
1800 * @param integer $itemid Item ID that should be added
1801 * @throws \Exception
1803 private static function addShadow(int $itemid)
1805 $fields = ['uid', 'private', 'visible', 'deleted', 'network', 'uri-id'];
1806 $condition = ['id' => $itemid, 'gravity' => self::GRAVITY_PARENT];
1807 $item = Post::selectFirst($fields, $condition);
1809 if (!DBA::isResult($item)) {
1813 // is it already a copy?
1814 if (($itemid == 0) || ($item['uid'] == 0)) {
1818 // Is it a visible public post?
1819 if (!$item["visible"] || $item["deleted"] || ($item["private"] == self::PRIVATE)) {
1823 // is it an entry from a connector? Only add an entry for natively connected networks
1824 if (!in_array($item["network"], array_merge(Protocol::FEDERATED ,['']))) {
1828 if (Post::exists(['uri-id' => $item['uri-id'], 'uid' => 0])) {
1832 $item = Post::selectFirst(array_merge(self::ITEM_FIELDLIST, ['protocol']), ['id' => $itemid]);
1834 if (DBA::isResult($item)) {
1835 // Preparing public shadow (removing user specific data)
1838 unset($item['parent']);
1839 unset($item['wall']);
1840 unset($item['mention']);
1841 unset($item['origin']);
1842 unset($item['starred']);
1843 unset($item['postopts']);
1844 unset($item['inform']);
1845 unset($item['post-reason']);
1846 if ($item['uri-id'] == $item['parent-uri-id']) {
1847 $item['contact-id'] = $item['owner-id'];
1849 $item['contact-id'] = $item['author-id'];
1852 $public_shadow = self::insert($item);
1854 Logger::info('Stored public shadow', ['thread' => $itemid, 'id' => $public_shadow]);
1859 * Add a shadow entry for a given item id that is a comment
1861 * This function does the same like the function above - but for comments
1863 * @param integer $itemid Item ID that should be added
1864 * @throws \Exception
1866 private static function addShadowPost(int $itemid)
1868 $item = Post::selectFirst(array_merge(self::ITEM_FIELDLIST, ['protocol']), ['id' => $itemid]);
1869 if (!DBA::isResult($item)) {
1873 // Is it a toplevel post?
1874 if ($item['gravity'] == self::GRAVITY_PARENT) {
1875 self::addShadow($itemid);
1879 // Is this a shadow entry?
1880 if ($item['uid'] == 0) {
1884 // Is there a shadow parent?
1885 if (!Post::exists(['uri-id' => $item['parent-uri-id'], 'uid' => 0])) {
1889 // Is there already a shadow entry?
1890 if (Post::exists(['uri-id' => $item['uri-id'], 'uid' => 0])) {
1894 // Save "origin" and "parent" state
1895 $origin = $item['origin'];
1896 $parent = $item['parent'];
1898 // Preparing public shadow (removing user specific data)
1901 unset($item['parent']);
1902 unset($item['wall']);
1903 unset($item['mention']);
1904 unset($item['origin']);
1905 unset($item['starred']);
1906 unset($item['postopts']);
1907 unset($item['inform']);
1908 unset($item['post-reason']);
1909 $item['contact-id'] = Contact::getIdForURL($item['author-link']);
1911 $public_shadow = self::insert($item);
1913 Logger::info('Stored public shadow', ['uri-id' => $item['uri-id'], 'id' => $public_shadow]);
1915 // If this was a comment to a Diaspora post we don't get our comment back.
1916 // This means that we have to distribute the comment by ourselves.
1917 if ($origin && Post::exists(['id' => $parent, 'network' => Protocol::DIASPORA])) {
1918 self::distribute($public_shadow);
1923 * Adds a language specification in a "language" element of given $arr.
1924 * Expects "body" element to exist in $arr.
1926 * @param array $item
1927 * @return string detected language
1928 * @throws \Text_LanguageDetect_Exception
1930 private static function getLanguage(array $item): string
1932 if (!empty($item['language'])) {
1933 return $item['language'];
1936 if (!in_array($item['gravity'], [self::GRAVITY_PARENT, self::GRAVITY_COMMENT]) || empty($item['body'])) {
1940 $languages = self::getLanguageArray(trim($item['title'] . "\n" . $item['body']), 3);
1941 if (empty($languages)) {
1945 return json_encode($languages);
1949 * Get a language array from a given text
1951 * @param string $body
1952 * @param integer $count
1955 public static function getLanguageArray(string $body, int $count): array
1957 // Convert attachments to links
1958 $naked_body = BBCode::removeAttachment($body);
1959 if (empty($naked_body)) {
1963 // Remove links and pictures
1964 $naked_body = BBCode::removeLinks($naked_body);
1966 // Convert the title and the body to plain text
1967 $naked_body = BBCode::toPlaintext($naked_body);
1969 // Remove possibly remaining links
1970 $naked_body = preg_replace(Strings::autoLinkRegEx(), '', $naked_body);
1972 if (empty($naked_body)) {
1976 $naked_body = self::getDominantLanguage($naked_body);
1978 $availableLanguages = DI::l10n()->getAvailableLanguages();
1979 // See https://github.com/friendica/friendica/issues/10511
1980 // Persian is manually added to language detection until a persian translation is provided for the interface, at
1981 // which point it will be automatically available through `getAvailableLanguages()` and this should be removed.
1982 $availableLanguages['fa'] = 'fa';
1984 $ld = new Language(array_keys($availableLanguages));
1985 return $ld->detect($naked_body)->limit(0, $count)->close() ?: [];
1989 * Check if latin or non latin are dominant in the body and only return the dominant one
1991 * @param string $body
1994 private static function getDominantLanguage(string $body): string
1998 for ($i = 0; $i < mb_strlen($body); $i++) {
1999 $character = mb_substr($body, $i, 1);
2000 $ord = mb_ord($character);
2002 // We add the most common characters to both strings.
2003 if (($ord <= 64) || ($ord >= 91 && $ord <= 96) || ($ord >= 123 && $ord <= 191) || in_array($ord, [215, 247]) || ($ord >= 697 && $ord <= 735) || ($ord > 65535)) {
2004 $latin .= $character;
2005 $non_latin .= $character;
2006 } elseif ($ord < 768) {
2007 $latin .= $character;
2009 $non_latin .= $character;
2012 return (mb_strlen($latin) > mb_strlen($non_latin)) ? $latin : $non_latin;
2015 public static function getLanguageMessage(array $item): string
2017 $iso639 = new \Matriphe\ISO639\ISO639;
2019 $used_languages = '';
2020 foreach (json_decode($item['language'], true) as $language => $reliability) {
2021 $used_languages .= $iso639->languageByCode1($language) . ' (' . $language . "): " . number_format($reliability, 5) . '\n';
2023 $used_languages = DI::l10n()->t('Detected languages in this post:\n%s', $used_languages);
2024 return $used_languages;
2028 * Creates an unique guid out of a given uri.
2029 * This function is used for messages outside the fediverse (Connector posts, feeds, Mails, ...)
2030 * Posts that are created on this system are using System::createUUID.
2031 * Received ActivityPub posts are using Processor::getGUIDByURL.
2033 * @param string $uri uri of an item entry
2034 * @param string|null $host hostname for the GUID prefix
2035 * @return string Unique guid
2036 * @throws \Exception
2038 public static function guidFromUri(string $uri, string $host = null): string
2040 // Our regular guid routine is using this kind of prefix as well
2041 // We have to avoid that different routines could accidentally create the same value
2042 $parsed = parse_url($uri);
2044 // Remove the scheme to make sure that "https" and "http" doesn't make a difference
2045 unset($parsed['scheme']);
2047 $hostPart = $host ?? $parsed['host'] ?? '';
2049 Logger::warning('Empty host GUID part', ['uri' => $uri, 'host' => $host, 'parsed' => $parsed, 'callstack' => System::callstack(10)]);
2052 // Glue it together to be able to make a hash from it
2053 $host_id = implode('/', $parsed);
2055 // Use a mixture of several hashes to provide some GUID like experience
2056 return hash('crc32', $hostPart) . '-' . hash('joaat', $host_id) . '-' . hash('fnv164', $host_id);
2060 * generate an unique URI
2062 * @param string $guid An existing GUID (Otherwise it will be generated)
2065 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2067 public static function newURI(string $guid = ''): string
2070 $guid = System::createUUID();
2073 return DI::baseUrl() . '/objects/' . $guid;
2077 * Set "success_update" and "last-item" to the date of the last time we heard from this contact
2079 * This can be used to filter for inactive contacts.
2080 * Only do this for public postings to avoid privacy problems, since poco data is public.
2081 * Don't set this value if it isn't from the owner (could be an author that we don't know)
2083 * @param array $arr Contains the just posted item record
2084 * @throws \Exception
2086 private static function updateContact(array $arr)
2088 // Unarchive the author
2089 $contact = DBA::selectFirst('contact', [], ['id' => $arr["author-id"]]);
2090 if (DBA::isResult($contact)) {
2091 Contact::unmarkForArchival($contact);
2094 // Unarchive the contact if it's not our own contact
2095 $contact = DBA::selectFirst('contact', [], ['id' => $arr["contact-id"], 'self' => false]);
2096 if (DBA::isResult($contact)) {
2097 Contact::unmarkForArchival($contact);
2100 /// @todo On private posts we could obfuscate the date
2101 $update = ($arr['private'] != self::PRIVATE) || in_array($arr['network'], Protocol::FEDERATED);
2103 // Is it a forum? Then we don't care about the rules from above
2104 if (!$update && in_array($arr["network"], [Protocol::ACTIVITYPUB, Protocol::DFRN]) && ($arr["parent-uri-id"] === $arr["uri-id"])) {
2105 if (DBA::exists('contact', ['id' => $arr['contact-id'], 'forum' => true])) {
2111 // The "self" contact id is used (for example in the connectors) when the contact is unknown
2112 // So we have to ensure to only update the last item when it had been our own post,
2113 // or it had been done by a "regular" contact.
2114 if (!empty($arr['wall'])) {
2115 $condition = ['id' => $arr['contact-id']];
2117 $condition = ['id' => $arr['contact-id'], 'self' => false];
2119 Contact::update(['failed' => false, 'local-data' => true, 'success_update' => $arr['received'], 'last-item' => $arr['received']], $condition);
2121 // Now do the same for the system wide contacts with uid=0
2122 if ($arr['private'] != self::PRIVATE) {
2123 Contact::update(['failed' => false, 'local-data' => true, 'success_update' => $arr['received'], 'last-item' => $arr['received']],
2124 ['id' => $arr['owner-id']]);
2126 if ($arr['owner-id'] != $arr['author-id']) {
2127 Contact::update(['failed' => false, 'local-data' => true, 'success_update' => $arr['received'], 'last-item' => $arr['received']],
2128 ['id' => $arr['author-id']]);
2133 public static function setHashtags(string $body): string
2135 $body = BBCode::performWithEscapedTags($body, ['noparse', 'pre', 'code', 'img'], function ($body) {
2136 $tags = BBCode::getTags($body);
2139 if (!count($tags)) {
2143 // This sorting is important when there are hashtags that are part of other hashtags
2144 // Otherwise there could be problems with hashtags like #test and #test2
2145 // Because of this we are sorting from the longest to the shortest tag.
2146 usort($tags, function ($a, $b) {
2147 return strlen($b) <=> strlen($a);
2150 $URLSearchString = "^\[\]";
2152 // All hashtags should point to the home server if "local_tags" is activated
2153 if (DI::config()->get('system', 'local_tags')) {
2154 $body = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
2155 "#[url=" . DI::baseUrl() . "/search?tag=$2]$2[/url]", $body);
2158 // mask hashtags inside of url, bookmarks and attachments to avoid urls in urls
2159 $body = preg_replace_callback("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
2161 return ("[url=" . str_replace("#", "#", $match[1]) . "]" . str_replace("#", "#", $match[2]) . "[/url]");
2164 $body = preg_replace_callback("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism",
2166 return ("[bookmark=" . str_replace("#", "#", $match[1]) . "]" . str_replace("#", "#", $match[2]) . "[/bookmark]");
2169 $body = preg_replace_callback("/\[attachment (.*?)\](.*?)\[\/attachment\]/ism",
2171 return ("[attachment " . str_replace("#", "#", $match[1]) . "]" . $match[2] . "[/attachment]");
2174 // Repair recursive urls
2175 $body = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
2178 foreach ($tags as $tag) {
2179 if ((strpos($tag, '#') !== 0) || strpos($tag, '[url=') || strlen($tag) < 2 || $tag[1] == '#') {
2183 $basetag = str_replace('_', ' ', substr($tag, 1));
2184 $newtag = '#[url=' . DI::baseUrl() . '/search?tag=' . $basetag . ']' . $basetag . '[/url]';
2186 $body = str_replace($tag, $newtag, $body);
2189 // Convert back the masked hashtags
2190 $body = str_replace("#", "#", $body);
2199 * look for mention tags and setup a second delivery chain for forum/community posts if appropriate
2202 * @param int $item_id
2203 * @return boolean true if item was deleted, else false
2204 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2205 * @throws \ImagickException
2207 private static function tagDeliver(int $uid, int $item_id): bool
2211 $owner = User::getOwnerDataById($uid);
2212 if (!DBA::isResult($owner)) {
2213 Logger::warning('User not found, quitting here.', ['uid' => $uid]);
2217 if ($owner['contact-type'] != User::ACCOUNT_TYPE_COMMUNITY) {
2218 Logger::debug('Owner is no community, quitting here.', ['uid' => $uid, 'id' => $item_id]);
2222 $item = Post::selectFirst(self::ITEM_FIELDLIST, ['id' => $item_id, 'gravity' => [self::GRAVITY_PARENT, self::GRAVITY_COMMENT], 'origin' => false]);
2223 if (!DBA::isResult($item)) {
2224 Logger::debug('Post is an activity or origin or not found at all, quitting here.', ['id' => $item_id]);
2228 if ($item['gravity'] == self::GRAVITY_PARENT) {
2229 if (Tag::isMentioned($item['uri-id'], $owner['url'])) {
2230 Logger::info('Mention found in tag.', ['uri' => $item['uri'], 'uid' => $uid, 'id' => $item_id, 'uri-id' => $item['uri-id'], 'guid' => $item['guid']]);
2232 Logger::info('Top-level post without mention is deleted.', ['uri' => $item['uri'], $uid, 'id' => $item_id, 'uri-id' => $item['uri-id'], 'guid' => $item['guid']]);
2233 Post\User::delete(['uri-id' => $item['uri-id'], 'uid' => $item['uid']]);
2237 $arr = ['item' => $item, 'user' => $owner];
2239 Hook::callAll('tagged', $arr);
2241 if (Tag::isMentioned($item['parent-uri-id'], $owner['url'])) {
2242 Logger::info('Mention found in parent tag.', ['uri' => $item['uri'], 'uid' => $uid, 'id' => $item_id, 'uri-id' => $item['uri-id'], 'guid' => $item['guid']]);
2244 Logger::debug('No mentions found in parent, quitting here.', ['id' => $item_id, 'uri-id' => $item['uri-id'], 'guid' => $item['guid']]);
2249 Logger::info('Community post will be distributed', ['uri' => $item['uri'], 'uid' => $uid, 'id' => $item_id, 'uri-id' => $item['uri-id'], 'guid' => $item['guid']]);
2251 if ($owner['page-flags'] == User::PAGE_FLAGS_PRVGROUP) {
2253 $allow_gid = '<' . Group::FOLLOWERS . '>';
2256 self::performActivity($item['id'], 'announce', $uid, $allow_cid, $allow_gid, $deny_cid, $deny_gid);
2258 self::performActivity($item['id'], 'announce', $uid);
2261 Logger::info('Community post had been distributed', ['uri' => $item['uri'], 'uid' => $uid, 'id' => $item_id, 'uri-id' => $item['uri-id'], 'guid' => $item['guid']]);
2266 * Automatically reshare the item if the "remote_self" option is selected
2268 * @param array $item
2271 private static function autoReshare(array $item)
2273 if ($item['gravity'] != self::GRAVITY_PARENT) {
2277 $cdata = Contact::getPublicAndUserContactID($item['author-id'], $item['uid']);
2278 if (empty($cdata['user']) || ($cdata['user'] != $item['contact-id'])) {
2282 $cdata = Contact::getPublicAndUserContactID($item['author-id'], $item['uid']);
2283 if (empty($cdata['user']) || ($cdata['user'] != $item['contact-id'])) {
2287 if (!DBA::exists('contact', ['id' => $cdata['user'], 'remote_self' => Contact::MIRROR_NATIVE_RESHARE])) {
2291 if (!in_array($item['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN])) {
2295 Logger::info('Automatically reshare item', ['uid' => $item['uid'], 'id' => $item['id'], 'guid' => $item['guid'], 'uri-id' => $item['uri-id']]);
2297 self::performActivity($item['id'], 'announce', $item['uid']);
2300 public static function isRemoteSelf(array $contact, array &$datarray): bool
2302 if ($contact['remote_self'] != Contact::MIRROR_OWN_POST) {
2306 // Prevent the forwarding of posts that are forwarded
2307 if (!empty($datarray['extid']) && ($datarray['extid'] == Protocol::DFRN)) {
2308 Logger::info('Already forwarded');
2312 // Prevent to forward already forwarded posts
2313 if ($datarray['app'] == DI::baseUrl()->getHost()) {
2314 Logger::info('Already forwarded (second test)');
2318 // Only forward posts
2319 if ($datarray['verb'] != Activity::POST) {
2320 Logger::info('No post');
2324 if (($contact['network'] != Protocol::FEED) && ($datarray['private'] == self::PRIVATE)) {
2325 Logger::info('Not public');
2329 $datarray2 = $datarray;
2330 Logger::info('remote-self start', ['contact' => $contact['url'], 'remote_self'=> $contact['remote_self'], 'item' => $datarray]);
2332 $self = DBA::selectFirst('contact', ['id', 'name', 'url', 'thumb'],
2333 ['uid' => $contact['uid'], 'self' => true]);
2334 if (!DBA::isResult($self)) {
2335 Logger::error('Self contact not found', ['uid' => $contact['uid']]);
2339 $datarray['contact-id'] = $self['id'];
2341 $datarray['author-name'] = $datarray['owner-name'] = $self['name'];
2342 $datarray['author-link'] = $datarray['owner-link'] = $self['url'];
2343 $datarray['author-avatar'] = $datarray['owner-avatar'] = $self['thumb'];
2345 unset($datarray['edited']);
2347 unset($datarray['network']);
2348 unset($datarray['owner-id']);
2349 unset($datarray['author-id']);
2351 if ($contact['network'] != Protocol::FEED) {
2352 $old_uri_id = $datarray['uri-id'] ?? 0;
2353 $datarray['guid'] = System::createUUID();
2354 unset($datarray['plink']);
2355 $datarray['uri'] = self::newURI($datarray['guid']);
2356 $datarray['uri-id'] = ItemURI::getIdByURI($datarray['uri']);
2357 $datarray['extid'] = Protocol::DFRN;
2358 $urlpart = parse_url($datarray2['author-link']);
2359 $datarray['app'] = $urlpart['host'];
2360 if (!empty($old_uri_id)) {
2361 Post\Media::copy($old_uri_id, $datarray['uri-id']);
2364 unset($datarray['parent-uri']);
2365 unset($datarray['thr-parent']);
2367 // Store the original post
2368 $result = self::insert($datarray2);
2369 Logger::info('remote-self post original item', ['contact' => $contact['url'], 'result'=> $result, 'item' => $datarray2]);
2371 $datarray['private'] = self::PUBLIC;
2372 $datarray['app'] = 'Feed';
2376 return (bool)$result;
2383 * @param array $item
2386 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2387 * @throws \ImagickException
2389 public static function fixPrivatePhotos(string $s, int $uid, array $item = null, int $cid = 0): string
2391 if (DI::config()->get('system', 'disable_embedded')) {
2395 Logger::info('check for photos');
2396 $site = substr(DI::baseUrl(), strpos(DI::baseUrl(), '://'));
2401 $img_start = strpos($orig_body, '[img');
2402 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
2403 $img_len = ($img_start !== false ? strpos(substr($orig_body, $img_start + $img_st_close + 1), '[/img]') : false);
2405 while (($img_st_close !== false) && ($img_len !== false)) {
2406 $img_st_close++; // make it point to AFTER the closing bracket
2407 $image = substr($orig_body, $img_start + $img_st_close, $img_len);
2409 Logger::info('found photo', ['image' => $image]);
2411 if (stristr($image, $site . '/photo/')) {
2412 // Only embed locally hosted photos
2414 $i = basename($image);
2415 $i = str_replace(['.jpg', '.png', '.gif'], ['', '', ''], $i);
2416 $x = strpos($i, '-');
2419 $res = substr($i, $x + 1);
2420 $i = substr($i, 0, $x);
2421 $photo = Photo::getPhotoForUser($uid, $i, $res);
2422 if (DBA::isResult($photo)) {
2424 * Check to see if we should replace this photo link with an embedded image
2425 * 1. No need to do so if the photo is public
2426 * 2. If there's a contact-id provided, see if they're in the access list
2427 * for the photo. If so, embed it.
2428 * 3. Otherwise, if we have an item, see if the item permissions match the photo
2429 * permissions, regardless of order but first check to see if they're an exact
2430 * match to save some processing overhead.
2432 if (self::hasPermissions($photo)) {
2434 $recips = self::enumeratePermissions($photo);
2435 if (in_array($cid, $recips)) {
2439 if (self::samePermissions($uid, $item, $photo)) {
2445 $photo_img = Photo::getImageForPhoto($photo);
2446 // If a custom width and height were specified, apply before embedding
2447 if (preg_match("/\[img\=([0-9]*)x([0-9]*)\]/is", substr($orig_body, $img_start, $img_st_close), $match)) {
2448 Logger::info('scaling photo');
2450 $width = intval($match[1]);
2451 $height = intval($match[2]);
2453 $photo_img->scaleDown(max($width, $height));
2456 $data = $photo_img->asString();
2457 $type = $photo_img->getType();
2459 Logger::info('replacing photo');
2460 $image = 'data:' . $type . ';base64,' . base64_encode($data);
2461 Logger::debug('replaced', ['image' => $image]);
2467 $new_body = $new_body . substr($orig_body, 0, $img_start + $img_st_close) . $image . '[/img]';
2468 $orig_body = substr($orig_body, $img_start + $img_st_close + $img_len + strlen('[/img]'));
2469 if ($orig_body === false) {
2473 $img_start = strpos($orig_body, '[img');
2474 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
2475 $img_len = ($img_start !== false ? strpos(substr($orig_body, $img_start + $img_st_close + 1), '[/img]') : false);
2478 $new_body = $new_body . $orig_body;
2483 private static function hasPermissions(array $obj)
2485 return !empty($obj['allow_cid']) || !empty($obj['allow_gid']) ||
2486 !empty($obj['deny_cid']) || !empty($obj['deny_gid']);
2489 // @TODO $uid is unused parameter
2490 private static function samePermissions($uid, array $obj1, array $obj2): bool
2492 // first part is easy. Check that these are exactly the same.
2493 if (($obj1['allow_cid'] == $obj2['allow_cid'])
2494 && ($obj1['allow_gid'] == $obj2['allow_gid'])
2495 && ($obj1['deny_cid'] == $obj2['deny_cid'])
2496 && ($obj1['deny_gid'] == $obj2['deny_gid'])) {
2500 // This is harder. Parse all the permissions and compare the resulting set.
2501 $recipients1 = self::enumeratePermissions($obj1);
2502 $recipients2 = self::enumeratePermissions($obj2);
2506 /// @TODO Comparison of arrays, maybe use array_diff_assoc() here?
2507 return ($recipients1 == $recipients2);
2511 * Returns an array of contact-ids that are allowed to see this object
2513 * @param array $obj Item array with at least uid, allow_cid, allow_gid, deny_cid and deny_gid
2514 * @param bool $check_dead Prunes unavailable contacts from the result
2515 * @param bool $expand_followers Expand the list of followers
2517 * @throws \Exception
2519 public static function enumeratePermissions(array $obj, bool $check_dead = false, bool $expand_followers = true): array
2521 $aclFormatter = DI::aclFormatter();
2523 if (!$expand_followers && (!empty($obj['deny_cid']) || !empty($obj['deny_gid']))) {
2524 $expand_followers = true;
2527 $allow_people = $aclFormatter->expand($obj['allow_cid']);
2528 $allow_groups = Group::expand($obj['uid'], $aclFormatter->expand($obj['allow_gid']), $check_dead, $expand_followers);
2529 $deny_people = $aclFormatter->expand($obj['deny_cid']);
2530 $deny_groups = Group::expand($obj['uid'], $aclFormatter->expand($obj['deny_gid']), $check_dead);
2531 $recipients = array_unique(array_merge($allow_people, $allow_groups));
2532 $deny = array_unique(array_merge($deny_people, $deny_groups));
2533 $recipients = array_diff($recipients, $deny);
2537 public static function expire(int $uid, int $days, string $network = "", bool $force = false)
2539 if (!$uid || ($days < 1)) {
2543 $condition = ["`uid` = ? AND NOT `deleted` AND `gravity` = ?",
2544 $uid, self::GRAVITY_PARENT];
2547 * $expire_network_only = save your own wall posts
2548 * and just expire conversations started by others
2550 $expire_network_only = DI::pConfig()->get($uid, 'expire', 'network_only', false);
2552 if ($expire_network_only) {
2553 $condition[0] .= " AND NOT `wall`";
2556 if ($network != "") {
2557 $condition[0] .= " AND `network` = ?";
2558 $condition[] = $network;
2561 $condition[0] .= " AND `received` < ?";
2562 $condition[] = DateTimeFormat::utc('now - ' . $days . ' day');
2564 $items = Post::select(['resource-id', 'starred', 'id', 'post-type', 'uid', 'uri-id'], $condition);
2566 if (!DBA::isResult($items)) {
2570 $expire_items = (bool)DI::pConfig()->get($uid, 'expire', 'items', true);
2572 // Forcing expiring of items - but not notes and marked items
2574 $expire_items = true;
2577 $expire_notes = (bool)DI::pConfig()->get($uid, 'expire', 'notes', true);
2578 $expire_starred = (bool)DI::pConfig()->get($uid, 'expire', 'starred', true);
2579 $expire_photos = (bool)DI::pConfig()->get($uid, 'expire', 'photos', false);
2583 $priority = DI::config()->get('system', 'expire-notify-priority');
2585 while ($item = Post::fetch($items)) {
2586 // don't expire filed items
2587 if (DBA::exists('post-category', ['uri-id' => $item['uri-id'], 'uid' => $item['uid'], 'type' => Post\Category::FILE])) {
2591 // Only expire posts, not photos and photo comments
2593 if (!$expire_photos && !empty($item['resource-id'])) {
2595 } elseif (!$expire_starred && intval($item['starred'])) {
2597 } elseif (!$expire_notes && ($item['post-type'] == self::PT_PERSONAL_NOTE)) {
2599 } elseif (!$expire_items && ($item['post-type'] != self::PT_PERSONAL_NOTE)) {
2603 self::markForDeletionById($item['id'], $priority);
2608 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]);
2611 public static function firstPostDate(int $uid, bool $wall = false)
2613 $user = User::getById($uid, ['register_date']);
2618 $condition = ["`uid` = ? AND `wall` = ? AND NOT `deleted` AND `visible` AND `received` >= ?",
2619 $uid, $wall, $user['register_date']];
2620 $params = ['order' => ['received' => false]];
2621 $thread = Post::selectFirstThread(['received'], $condition, $params);
2622 if (DBA::isResult($thread)) {
2623 $postdate = substr(DateTimeFormat::local($thread['received']), 0, 10);
2630 * add/remove activity to an item
2632 * Toggle activities as like,dislike,attend of an item
2634 * @param int $item_id
2635 * @param string $verb
2636 * Activity verb. One of
2637 * like, unlike, dislike, undislike, attendyes, unattendyes,
2638 * attendno, unattendno, attendmaybe, unattendmaybe,
2639 * announce, unannounce
2641 * @param string $allow_cid
2642 * @param string $allow_gid
2643 * @param string $deny_cid
2644 * @param string $deny_gid
2646 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2647 * @throws \ImagickException
2648 * @hook 'post_local_end'
2650 * 'post_id' => ID of posted item
2652 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
2658 Logger::notice('Start create activity', ['verb' => $verb, 'item' => $item_id, 'user' => $uid]);
2660 $item = Post::selectFirst(self::ITEM_FIELDLIST, ['id' => $item_id]);
2661 if (!DBA::isResult($item)) {
2662 Logger::warning('Post had not been fetched', ['id' => $item_id]);
2666 $uri_id = $item['uri-id'];
2668 if (!in_array($item['uid'], [0, $uid])) {
2672 if (!Post::exists(['uri-id' => $item['parent-uri-id'], 'uid' => $uid])) {
2673 $stored = self::storeForUserByUriId($item['parent-uri-id'], $uid, ['post-reason' => Item::PR_ACTIVITY]);
2674 if (($item['parent-uri-id'] == $item['uri-id']) && !empty($stored)) {
2675 $item = Post::selectFirst(self::ITEM_FIELDLIST, ['id' => $stored]);
2676 if (!DBA::isResult($item)) {
2677 Logger::info('Could not fetch just created item - should not happen', ['stored' => $stored, 'uid' => $uid, 'uri-id' => $uri_id]);
2683 // Retrieves the local post owner
2684 $owner = User::getOwnerDataById($uid);
2685 if (empty($owner)) {
2686 Logger::info('Empty owner for user', ['uid' => $uid]);
2690 // Retrieve the current logged in user's public contact
2691 $author_id = Contact::getPublicIdByUserId($uid);
2692 if (empty($author_id)) {
2693 Logger::info('Empty public contact');
2701 $activity = Activity::LIKE;
2705 $activity = Activity::DISLIKE;
2709 $activity = Activity::ATTEND;
2713 $activity = Activity::ATTENDNO;
2716 case 'unattendmaybe':
2717 $activity = Activity::ATTENDMAYBE;
2721 $activity = Activity::FOLLOW;
2725 $activity = Activity::ANNOUNCE;
2728 Logger::warning('unknown verb', ['verb' => $verb, 'item' => $item_id]);
2732 $mode = Strings::startsWith($verb, 'un') ? 'delete' : 'create';
2734 // Enable activity toggling instead of on/off
2735 $event_verb_flag = $activity === Activity::ATTEND || $activity === Activity::ATTENDNO || $activity === Activity::ATTENDMAYBE;
2737 // Look for an existing verb row
2738 // Event participation activities are mutually exclusive, only one of them can exist at all times.
2739 if ($event_verb_flag) {
2740 $verbs = [Activity::ATTEND, Activity::ATTENDNO, Activity::ATTENDMAYBE];
2742 // Translate to the index based activity index
2744 foreach ($verbs as $verb) {
2745 $vids[] = Verb::getID($verb);
2748 $vids = Verb::getID($activity);
2751 $condition = ['vid' => $vids, 'deleted' => false, 'gravity' => self::GRAVITY_ACTIVITY,
2752 'author-id' => $author_id, 'uid' => $uid, 'thr-parent-id' => $uri_id];
2753 $like_item = Post::selectFirst(['id', 'guid', 'verb'], $condition);
2755 if (DBA::isResult($like_item)) {
2757 * Truth table for existing activities
2759 * | Inputs || Outputs |
2760 * |----------------------------||-------------------|
2761 * | Mode | Event | Same verb || Delete? | Return? |
2762 * |--------|-------|-----------||---------|---------|
2763 * | create | Yes | Yes || No | Yes |
2764 * | create | Yes | No || Yes | No |
2765 * | create | No | Yes || No | Yes |
2766 * | create | No | No || N/A†|
2767 * | delete | Yes | Yes || Yes | N/A‡ |
2768 * | delete | Yes | No || No | N/A‡ |
2769 * | delete | No | Yes || Yes | N/A‡ |
2770 * | delete | No | No || N/A†|
2771 * |--------|-------|-----------||---------|---------|
2772 * | A | B | C || A xor C | !B or C |
2774 * †Can't happen: It's impossible to find an existing non-event activity without
2775 * the same verb because we are only looking for this single verb.
2777 * ‡ The "mode = delete" is returning early whether an existing activity was found or not.
2779 if ($mode == 'create' xor $like_item['verb'] == $activity) {
2780 self::markForDeletionById($like_item['id']);
2783 if (!$event_verb_flag || $like_item['verb'] == $activity) {
2788 // No need to go further if we aren't creating anything
2789 if ($mode == 'delete') {
2793 $objtype = $item['resource-id'] ? Activity\ObjectType::IMAGE : Activity\ObjectType::NOTE;
2796 'guid' => System::createUUID(),
2797 'uri' => self::newURI(),
2799 'contact-id' => $owner['id'],
2800 'wall' => $item['wall'],
2802 'network' => Protocol::DFRN,
2803 'protocol' => Conversation::PARCEL_DIRECT,
2804 'direction' => Conversation::PUSH,
2805 'gravity' => self::GRAVITY_ACTIVITY,
2806 'parent' => $item['id'],
2807 'thr-parent' => $item['uri'],
2808 'owner-id' => $author_id,
2809 'author-id' => $author_id,
2810 'body' => $activity,
2811 'verb' => $activity,
2812 'object-type' => $objtype,
2813 'allow_cid' => $allow_cid ?? $item['allow_cid'],
2814 'allow_gid' => $allow_gid ?? $item['allow_gid'],
2815 'deny_cid' => $deny_cid ?? $item['deny_cid'],
2816 'deny_gid' => $deny_gid ?? $item['deny_gid'],
2821 if (in_array($activity, [Activity::LIKE, Activity::DISLIKE])) {
2822 $signed = Diaspora::createLikeSignature($uid, $new_item);
2823 if (!empty($signed)) {
2824 $new_item['diaspora_signed_text'] = json_encode($signed);
2828 self::insert($new_item, true);
2830 // If the parent item isn't visible then set it to visible
2831 // @todo Check if this is still needed
2832 if (!$item['visible']) {
2833 self::update(['visible' => true], ['id' => $item['id']]);
2839 * Fetch the SQL condition for the given user id
2841 * @param integer $owner_id User ID for which the permissions should be fetched
2842 * @return array condition
2844 public static function getPermissionsConditionArrayByUserId(int $owner_id): array
2846 $local_user = DI::userSession()->getLocalUserId();
2847 $remote_user = DI::userSession()->getRemoteContactID($owner_id);
2849 // default permissions - anonymous user
2850 $condition = ["`private` != ?", self::PRIVATE];
2852 if ($local_user && ($local_user == $owner_id)) {
2853 // Profile owner - everything is visible
2855 } elseif ($remote_user) {
2856 // Authenticated visitor - fetch the matching permissionsets
2857 $permissionSets = DI::permissionSet()->selectByContactId($remote_user, $owner_id);
2859 $condition = ["(`private` != ? OR (`private` = ? AND `wall`
2860 AND `psid` IN (" . implode(', ', array_fill(0, count($set), '?')) . ")))",
2861 self::PRIVATE, self::PRIVATE];
2862 $condition = array_merge($condition, $permissionSets->column('id'));
2870 * Get a permission SQL string for the given user
2872 * @param int $owner_id
2873 * @param string $table
2876 public static function getPermissionsSQLByUserId(int $owner_id, string $table = ''): string
2878 $local_user = DI::userSession()->getLocalUserId();
2879 $remote_user = DI::userSession()->getRemoteContactID($owner_id);
2881 if (!empty($table)) {
2882 $table = DBA::quoteIdentifier($table) . '.';
2886 * Construct permissions
2888 * default permissions - anonymous user
2890 $sql = sprintf(" AND " . $table . "`private` != %d", self::PRIVATE);
2892 // Profile owner - everything is visible
2893 if ($local_user && ($local_user == $owner_id)) {
2895 } elseif ($remote_user) {
2897 * Authenticated visitor. Unless pre-verified,
2898 * check that the contact belongs to this $owner_id
2899 * and load the groups the visitor belongs to.
2900 * If pre-verified, the caller is expected to have already
2901 * done this and passed the groups into this function.
2903 $permissionSets = DI::permissionSet()->selectByContactId($remote_user, $owner_id);
2906 $sql_set = sprintf(" OR (" . $table . "`private` = %d AND " . $table . "`wall` AND " . $table . "`psid` IN (", self::PRIVATE) . implode(',', $permissionSets->column('id')) . "))";
2911 $sql = sprintf(" AND (" . $table . "`private` != %d", self::PRIVATE) . $sql_set . ")";
2918 * get translated item type
2920 * @param array $item
2921 * @param \Friendica\Core\L10n $l10n
2924 public static function postType(array $item, \Friendica\Core\L10n $l10n): string
2926 if (!empty($item['event-id'])) {
2927 return $l10n->t('event');
2928 } elseif (!empty($item['resource-id'])) {
2929 return $l10n->t('photo');
2930 } elseif ($item['gravity'] == self::GRAVITY_ACTIVITY) {
2931 return $l10n->t('activity');
2932 } elseif ($item['gravity'] == self::GRAVITY_COMMENT) {
2933 return $l10n->t('comment');
2936 return $l10n->t('post');
2940 * Sets the "rendered-html" field of the provided item
2942 * Body is preserved to avoid side-effects as we modify it just-in-time for spoilers and private image links
2944 * @param array $item
2946 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2947 * @todo Remove reference, simply return "rendered-html" and "rendered-hash"
2949 private static function putInCache(&$item)
2951 // Save original body to prevent addons to modify it
2952 $body = $item['body'];
2954 $rendered_hash = $item['rendered-hash'] ?? '';
2955 $rendered_html = $item['rendered-html'] ?? '';
2957 if ($rendered_hash == ''
2958 || $rendered_html == ''
2959 || $rendered_hash != hash('md5', BBCode::VERSION . '::' . $body)
2960 || DI::config()->get('system', 'ignore_cache')
2962 $item['rendered-html'] = BBCode::convertForUriId($item['uri-id'], $item['body']);
2963 $item['rendered-hash'] = hash('md5', BBCode::VERSION . '::' . $body);
2965 $hook_data = ['item' => $item, 'rendered-html' => $item['rendered-html'], 'rendered-hash' => $item['rendered-hash']];
2966 Hook::callAll('put_item_in_cache', $hook_data);
2967 $item['rendered-html'] = $hook_data['rendered-html'];
2968 $item['rendered-hash'] = $hook_data['rendered-hash'];
2971 // Update if the generated values differ from the existing ones
2972 if ((($rendered_hash != $item['rendered-hash']) || ($rendered_html != $item['rendered-html'])) && !empty($item['id'])) {
2975 'rendered-html' => $item['rendered-html'],
2976 'rendered-hash' => $item['rendered-hash']
2978 ['id' => $item['id']]
2983 $item['body'] = $body;
2987 * Given an item array, convert the body element from bbcode to html and add smilie icons.
2988 * If attach is true, also add icons for item attachments.
2990 * @param array $item Record from item table
2991 * @param boolean $attach If true, add icons for item attachments as well
2992 * @param boolean $is_preview Whether this is a preview
2993 * @param boolean $only_cache Whether only cached HTML should be updated
2994 * @return string item body html
2995 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2996 * @throws \ImagickException
2997 * @hook prepare_body_init item array before any work
2998 * @hook prepare_body_content_filter ('item'=>item array, 'filter_reasons'=>string array) before first bbcode to html
2999 * @hook prepare_body ('item'=>item array, 'html'=>body string, 'is_preview'=>boolean, 'filter_reasons'=>string array) after first bbcode to html
3000 * @hook prepare_body_final ('item'=>item array, 'html'=>body string) after attach icons and blockquote special case handling (spoiler, author)
3002 public static function prepareBody(array &$item, bool $attach = false, bool $is_preview = false, bool $only_cache = false): string
3005 Hook::callAll('prepare_body_init', $item);
3008 // In order to provide theme developers more possibilities, event items
3009 // are treated differently.
3010 if ($item['object-type'] === Activity\ObjectType::EVENT && isset($item['event-id'])) {
3011 $ev = Event::getItemHTML($item);
3015 $tags = Tag::populateFromItem($item);
3017 $item['tags'] = $tags['tags'];
3018 $item['hashtags'] = $tags['hashtags'];
3019 $item['mentions'] = $tags['mentions'];
3022 $item['body'] = preg_replace("#\s*\[attachment .*?].*?\[/attachment]\s*#ism", "\n", $item['body']);
3023 $item['body'] = Post\Media::removeFromEndOfBody($item['body'] ?? '');
3024 $item['body'] = Post\Media::replaceImage($item['body']);
3027 $body = $item['body'];
3029 $item['body'] = preg_replace("#\s*\[attachment .*?].*?\[/attachment]\s*#ism", "\n", $item['body']);
3032 $fields = ['uri-id', 'uri', 'body', 'title', 'author-name', 'author-link', 'author-avatar', 'guid', 'created', 'plink', 'network', 'has-media', 'quote-uri-id', 'post-type'];
3036 $quote_shared_links = [];
3038 $shared = DI::contentItem()->getSharedPost($item, $fields);
3039 if (!empty($shared['post'])) {
3040 $shared_item = $shared['post'];
3041 $shared_item['body'] = Post\Media::removeFromEndOfBody($shared_item['body']);
3042 $shared_item['body'] = Post\Media::replaceImage($shared_item['body']);
3043 $quote_uri_id = $shared['post']['uri-id'];
3044 $shared_links[] = strtolower($shared['post']['uri']);
3045 $item['body'] = BBCode::removeSharedData($item['body']);
3046 } elseif (empty($shared_item['uri-id']) && empty($item['quote-uri-id']) && ($item['network'] != Protocol::DIASPORA)) {
3047 $media = Post\Media::getByURIId($item['uri-id'], [Post\Media::ACTIVITY]);
3048 if (!empty($media)) {
3049 $shared_item = Post::selectFirst($fields, ['uri-id' => $media[0]['media-uri-id'], 'uid' => [$item['uid'], 0]]);
3050 if (empty($shared_item['uri-id'])) {
3051 $shared_item = Post::selectFirst($fields, ['plink' => $media[0]['url'], 'uid' => [$item['uid'], 0]]);
3052 } elseif (!in_array(strtolower($media[0]['url']), $shared_links)) {
3053 $shared_links[] = strtolower($media[0]['url']);
3056 if (empty($shared_item['uri-id'])) {
3057 $shared_item = Post::selectFirst($fields, ['uri' => $media[0]['url'], 'uid' => [$item['uid'], 0]]);
3058 $shared_links[] = strtolower($media[0]['url']);
3061 if (!empty($shared_item['uri-id'])) {
3062 $data = BBCode::getAttachmentData($shared_item['body']);
3063 if (!empty($data['url'])) {
3064 $quote_shared_links[] = $data['url'];
3067 $quote_uri_id = $shared_item['uri-id'];
3072 if (!empty($quote_uri_id)) {
3073 if (isset($shared_item['plink'])) {
3074 $item['body'] .= "\n" . DI::contentItem()->createSharedBlockByArray($shared_item);
3076 DI::logger()->warning('Missing plink in shared item', ['item' => $item, 'shared' => $shared, 'quote_uri_id' => $quote_uri_id, 'shared_item' => $shared_item]);
3080 if (!empty($shared_item['uri-id'])) {
3081 $shared_uri_id = $shared_item['uri-id'];
3082 $shared_links[] = strtolower($shared_item['plink']);
3083 $shared_attachments = Post\Media::splitAttachments($shared_uri_id, [], $shared_item['has-media']);
3084 $shared_links = array_merge($shared_links, array_column($shared_attachments['visual'], 'url'));
3085 $shared_links = array_merge($shared_links, array_column($shared_attachments['link'], 'url'));
3086 $shared_links = array_merge($shared_links, array_column($shared_attachments['additional'], 'url'));
3087 $item['body'] = self::replaceVisualAttachments($shared_attachments, $item['body']);
3090 $attachments = Post\Media::splitAttachments($item['uri-id'], $shared_links, $item['has-media'] ?? false);
3091 $item['body'] = self::replaceVisualAttachments($attachments, $item['body'] ?? '');
3093 self::putInCache($item);
3094 $item['body'] = $body;
3095 $s = $item["rendered-html"];
3101 // Compile eventual content filter reasons
3102 $filter_reasons = [];
3103 if (!$is_preview && DI::userSession()->getPublicContactId() != $item['author-id']) {
3104 if (!empty($item['user-blocked-author']) || !empty($item['user-blocked-owner'])) {
3105 $filter_reasons[] = DI::l10n()->t('%s is blocked', $item['author-name']);
3106 } elseif (!empty($item['user-ignored-author']) || !empty($item['user-ignored-owner'])) {
3107 $filter_reasons[] = DI::l10n()->t('%s is ignored', $item['author-name']);
3108 } elseif (!empty($item['user-collapsed-author']) || !empty($item['user-collapsed-owner'])) {
3109 $filter_reasons[] = DI::l10n()->t('Content from %s is collapsed', $item['author-name']);
3112 if (!empty($item['content-warning']) && (!DI::userSession()->getLocalUserId() || !DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'system', 'disable_cw', false))) {
3113 $filter_reasons[] = DI::l10n()->t('Content warning: %s', $item['content-warning']);
3116 $item['attachments'] = $attachments;
3120 'filter_reasons' => $filter_reasons
3122 Hook::callAll('prepare_body_content_filter', $hook_data);
3123 $filter_reasons = $hook_data['filter_reasons'];
3130 'preview' => $is_preview,
3131 'filter_reasons' => $filter_reasons
3133 Hook::callAll('prepare_body', $hook_data);
3134 $s = $hook_data['html'];
3139 // Replace the blockquotes with quotes that are used in mails.
3140 $mailquote = '<blockquote type="cite" class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex;">';
3141 $s = str_replace(['<blockquote>', '<blockquote class="spoiler">', '<blockquote class="author">'], [$mailquote, $mailquote, $mailquote], $s);
3145 if (!empty($shared_attachments)) {
3146 $s = self::addGallery($s, $shared_attachments, $item['uri-id']);
3147 $s = self::addVisualAttachments($shared_attachments, $shared_item, $s, true);
3148 $s = self::addLinkAttachment($shared_uri_id ?: $item['uri-id'], $shared_attachments, $body, $s, true, $quote_shared_links);
3149 $s = self::addNonVisualAttachments($shared_attachments, $item, $s, true);
3150 $body = BBCode::removeSharedData($body);
3153 $s = self::addGallery($s, $attachments, $item['uri-id']);
3154 $s = self::addVisualAttachments($attachments, $item, $s, false);
3155 $s = self::addLinkAttachment($item['uri-id'], $attachments, $body, $s, false, $shared_links);
3156 $s = self::addNonVisualAttachments($attachments, $item, $s, false);
3157 $s = self::addQuestions($item, $s);
3160 if (strpos($s, '<div class="map">') !== false && !empty($item['coord'])) {
3161 $x = Map::byCoordinates(trim($item['coord']));
3163 $s = preg_replace('/\<div class\=\"map\"\>/', '$0' . $x, $s);
3167 // Replace friendica image url size with theme preference.
3168 if (!empty($a->getThemeInfoValue('item_image_size'))) {
3169 $ps = $a->getThemeInfoValue('item_image_size');
3170 $s = preg_replace('|(<img[^>]+src="[^"]+/photo/[0-9a-f]+)-[0-9]|', "$1-" . $ps, $s);
3173 $s = HTML::applyContentFilter($s, $filter_reasons);
3175 $hook_data = ['item' => $item, 'html' => $s];
3176 Hook::callAll('prepare_body_final', $hook_data);
3177 return $hook_data['html'];
3181 * @param array $images
3183 * @throws \Friendica\Network\HTTPException\ServiceUnavailableException
3185 private static function makeImageGrid(array $images): string
3187 // Image for first column (fc) and second column (sc)
3191 for ($i = 0; $i < count($images); $i++) {
3192 ($i % 2 == 0) ? ($images_fc[] = $images[$i]) : ($images_sc[] = $images[$i]);
3195 return Renderer::replaceMacros(Renderer::getMarkupTemplate('content/image_grid.tpl'), [
3204 * Modify links to pictures to links for the "Fancybox" gallery
3207 * @param array $attachments
3208 * @param integer $uri_id
3211 private static function addGallery(string $s, array $attachments, int $uri_id): string
3213 foreach ($attachments['visual'] as $attachment) {
3214 if (empty($attachment['preview']) || ($attachment['type'] != Post\Media::IMAGE)) {
3217 $s = str_replace('<a href="' . $attachment['url'] . '"', '<a data-fancybox="' . $uri_id . '" href="' . $attachment['url'] . '"', $s);
3223 * Check if the body contains a link
3225 * @param string $body
3226 * @param string $url
3230 public static function containsLink(string $body, string $url, int $type = 0): bool
3232 // Make sure that for example site parameters aren't used when testing if the link is contained in the body
3233 $urlparts = parse_url($url);
3234 if (empty($urlparts)) {
3238 unset($urlparts['query']);
3239 unset($urlparts['fragment']);
3242 $url = (string)Uri::fromParts($urlparts);
3243 } catch (\InvalidArgumentException $e) {
3244 DI::logger()->notice('Invalid URL', ['$url' => $url, '$urlparts' => $urlparts]);
3245 /* See https://github.com/friendica/friendica/issues/12113
3246 * Malformed URLs will result in a Fatal Error
3251 // Remove media links to only search in embedded content
3252 // @todo Check images for image link, audio for audio links, ...
3253 if (in_array($type, [Post\Media::AUDIO, Post\Media::VIDEO, Post\Media::IMAGE])) {
3254 $body = preg_replace("/\[url=[^\[\]]*\](.*)\[\/url\]/Usi", ' $1 ', $body);
3257 if (strpos($body, $url)) {
3261 foreach ([0, 1, 2] as $size) {
3262 if (preg_match('#/photo/.*-' . $size . '\.#ism', $url) &&
3263 strpos(preg_replace('#(/photo/.*)-[012]\.#ism', '$1-' . $size . '.', $body), $url)) {
3272 * Replace visual attachments in the body
3274 * @param array $attachments
3275 * @param string $body
3276 * @return string modified body
3278 private static function replaceVisualAttachments(array $attachments, string $body): string
3280 DI::profiler()->startRecording('rendering');
3282 foreach ($attachments['visual'] as $attachment) {
3283 if (!empty($attachment['preview'])) {
3284 if (Network::isLocalLink($attachment['preview'])) {
3287 $proxy = Post\Media::getPreviewUrlForId($attachment['id'], Proxy::SIZE_LARGE);
3288 $search = ['[img=' . $attachment['preview'] . ']', ']' . $attachment['preview'] . '[/img]'];
3289 $replace = ['[img=' . $proxy . ']', ']' . $proxy . '[/img]'];
3291 $body = str_replace($search, $replace, $body);
3292 } elseif ($attachment['filetype'] == 'image') {
3293 if (Network::isLocalLink($attachment['url'])) {
3296 $proxy = Post\Media::getUrlForId($attachment['id']);
3297 $search = ['[img=' . $attachment['url'] . ']', ']' . $attachment['url'] . '[/img]'];
3298 $replace = ['[img=' . $proxy . ']', ']' . $proxy . '[/img]'];
3300 $body = str_replace($search, $replace, $body);
3303 DI::profiler()->stopRecording();
3308 * Add visual attachments to the content
3310 * @param array $attachments
3311 * @param array $item
3312 * @param string $content
3313 * @return string modified content
3315 private static function addVisualAttachments(array $attachments, array $item, string $content, bool $shared): string
3317 DI::profiler()->startRecording('rendering');
3322 // @todo In the future we should make a single for the template engine with all media in it. This allows more flexibilty.
3323 foreach ($attachments['visual'] as $attachment) {
3324 if (self::containsLink($item['body'], $attachment['preview'] ?? $attachment['url'], $attachment['type'])) {
3328 if ($attachment['filetype'] == 'image') {
3329 $preview_url = Post\Media::getPreviewUrlForId($attachment['id'], ($attachment['width'] > $attachment['height']) ? Proxy::SIZE_MEDIUM : Proxy::SIZE_LARGE);
3330 } elseif (!empty($attachment['preview'])) {
3331 $preview_url = Post\Media::getPreviewUrlForId($attachment['id'], Proxy::SIZE_LARGE);
3336 if ($preview_url && self::containsLink($item['body'], $preview_url)) {
3340 if (($attachment['filetype'] == 'video')) {
3341 /// @todo Move the template to /content as well
3342 $media = Renderer::replaceMacros(Renderer::getMarkupTemplate('video_top.tpl'), [
3344 'id' => $attachment['id'],
3345 'src' => $attachment['url'],
3346 'name' => $attachment['name'] ?: $attachment['url'],
3347 'preview' => $preview_url,
3348 'mime' => $attachment['mimetype'],
3351 if (($item['post-type'] ?? null) == Item::PT_VIDEO) {
3354 $trailing .= $media;
3356 } elseif ($attachment['filetype'] == 'audio') {
3357 $media = Renderer::replaceMacros(Renderer::getMarkupTemplate('content/audio.tpl'), [
3359 'id' => $attachment['id'],
3360 'src' => $attachment['url'],
3361 'name' => $attachment['name'] ?: $attachment['url'],
3362 'mime' => $attachment['mimetype'],
3365 if (($item['post-type'] ?? null) == Item::PT_AUDIO) {
3368 $trailing .= $media;
3370 } elseif ($attachment['filetype'] == 'image') {
3371 $src_url = Post\Media::getUrlForId($attachment['id']);
3372 if (self::containsLink($item['body'], $src_url)) {
3375 $images[] = ['src' => $src_url, 'preview' => $preview_url, 'attachment' => $attachment, 'uri_id' => $item['uri-id']];
3380 if (count($images) > 1) {
3381 $media = self::makeImageGrid($images);
3382 } elseif (count($images) == 1) {
3383 $media = Renderer::replaceMacros(Renderer::getMarkupTemplate('content/image.tpl'), [
3384 '$image' => $images[0],
3388 // On Diaspora posts the attached pictures are leading
3389 if ($item['network'] == Protocol::DIASPORA) {
3392 $trailing .= $media;
3396 $content = str_replace(BBCode::TOP_ANCHOR, '<div class="body-attach">' . $leading . '</div>' . BBCode::TOP_ANCHOR, $content);
3397 $content = str_replace(BBCode::BOTTOM_ANCHOR, '<div class="body-attach">' . $trailing . '</div>' . BBCode::BOTTOM_ANCHOR, $content);
3399 if ($leading != '') {
3400 $content = '<div class="body-attach">' . $leading . '</div>' . $content;
3403 if ($trailing != '') {
3404 $content .= '<div class="body-attach">' . $trailing . '</div>';
3408 DI::profiler()->stopRecording();
3413 * Add link attachment to the content
3415 * @param array $attachments
3416 * @param string $body
3417 * @param string $content
3418 * @param bool $shared
3419 * @param array $ignore_links A list of URLs to ignore
3420 * @return string modified content
3422 private static function addLinkAttachment(int $uriid, array $attachments, string $body, string $content, bool $shared, array $ignore_links): string
3424 DI::profiler()->startRecording('rendering');
3425 // Don't show a preview when there is a visual attachment (audio or video)
3426 $types = array_column($attachments['visual'], 'type');
3427 $preview = !in_array(Post\Media::IMAGE, $types) && !in_array(Post\Media::VIDEO, $types);
3429 if (!empty($attachments['link'])) {
3430 foreach ($attachments['link'] as $link) {
3432 foreach ($ignore_links as $ignore_link) {
3433 if (Strings::compareLink($link['url'], $ignore_link)) {
3437 // @todo Judge between the links to use the one with most information
3438 if (!$found && (empty($attachment) || !empty($link['author-name']) ||
3439 (empty($attachment['name']) && !empty($link['name'])) ||
3440 (empty($attachment['description']) && !empty($link['description'])) ||
3441 (empty($attachment['preview']) && !empty($link['preview'])))) {
3442 $attachment = $link;
3447 if (!empty($attachment)) {
3450 'author_name' => $attachment['author-name'] ?? '',
3451 'author_url' => $attachment['author-url'] ?? '',
3452 'description' => $attachment['description'] ?? '',
3455 'provider_name' => $attachment['publisher-name'] ?? '',
3456 'provider_url' => $attachment['publisher-url'] ?? '',
3458 'title' => $attachment['name'] ?? '',
3460 'url' => $attachment['url']];
3462 if ($preview && !empty($attachment['preview'])) {
3463 if ($attachment['preview-width'] >= 500) {
3464 $data['image'] = Post\Media::getPreviewUrlForId($attachment['id'], Proxy::SIZE_MEDIUM);
3466 $data['preview'] = Post\Media::getPreviewUrlForId($attachment['id'], Proxy::SIZE_MEDIUM);
3470 if (!empty($data['description']) && !empty($content)) {
3471 similar_text($data['description'], $content, $percent);
3476 if (!empty($data['description']) && (($data['title'] == $data['description']) || ($percent > 95) || (strpos($content, $data['description']) !== false))) {
3477 $data['description'] = '';
3480 if (($data['author_name'] ?? '') == ($data['provider_name'] ?? '')) {
3481 $data['author_name'] = '';
3484 if (($data['author_url'] ?? '') == ($data['provider_url'] ?? '')) {
3485 $data['author_url'] = '';
3487 } elseif (preg_match("/.*(\[attachment.*?\].*?\[\/attachment\]).*/ism", $body, $match)) {
3488 $data = BBCode::getAttachmentData($match[1]);
3490 DI::profiler()->stopRecording();
3492 if (isset($data['url']) && !in_array(strtolower($data['url']), $ignore_links)) {
3493 if (!empty($data['description']) || !empty($data['image']) || !empty($data['preview']) || (!empty($data['title']) && !Strings::compareLink($data['title'], $data['url']))) {
3494 $parts = parse_url($data['url']);
3495 if (!empty($parts['scheme']) && !empty($parts['host'])) {
3496 if (empty($data['provider_name'])) {
3497 $data['provider_name'] = $parts['host'];
3499 if (empty($data['provider_url']) || empty(parse_url($data['provider_url'], PHP_URL_SCHEME))) {
3500 $data['provider_url'] = $parts['scheme'] . '://' . $parts['host'];
3502 if (!empty($parts['port'])) {
3503 $data['provider_url'] .= ':' . $parts['port'];
3508 // @todo Use a template
3509 $preview_mode = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'system', 'preview_mode', BBCode::PREVIEW_LARGE);
3510 if ($preview_mode != BBCode::PREVIEW_NONE) {
3511 $rendered = BBCode::convertAttachment('', BBCode::INTERNAL, false, $data, $uriid, $preview_mode);
3515 } elseif (!self::containsLink($content, $data['url'], Post\Media::HTML)) {
3516 $rendered = Renderer::replaceMacros(Renderer::getMarkupTemplate('content/link.tpl'), [
3517 '$url' => $data['url'],
3518 '$title' => $data['title'],
3525 return str_replace(BBCode::BOTTOM_ANCHOR, BBCode::BOTTOM_ANCHOR . $rendered, $content);
3527 return $content . $rendered;
3534 * Add non visual attachments to the content
3536 * @param array $attachments
3537 * @param array $item
3538 * @param string $content
3539 * @return string modified content
3541 private static function addNonVisualAttachments(array $attachments, array $item, string $content): string
3543 DI::profiler()->startRecording('rendering');
3545 foreach ($attachments['additional'] as $attachment) {
3546 if (strpos($item['body'], $attachment['url'])) {
3550 $author = ['uid' => 0, 'id' => $item['author-id'],
3551 'network' => $item['author-network'], 'url' => $item['author-link']];
3552 $the_url = Contact::magicLinkByContact($author, $attachment['url']);
3554 $title = Strings::escapeHtml(trim(($attachment['description'] ?? '') ?: $attachment['url']));
3556 if (!empty($attachment['size'])) {
3557 $title .= ' ' . $attachment['size'] . ' ' . DI::l10n()->t('bytes');
3560 /// @todo Use a template
3561 $icon = '<div class="attachtype icon s22 type-' . $attachment['filetype'] . ' subtype-' . $attachment['subtype'] . '"></div>';
3562 $trailing .= '<a href="' . strip_tags($the_url) . '" title="' . $title . '" class="attachlink" target="_blank" rel="noopener noreferrer" >' . $icon . '</a>';
3565 if ($trailing != '') {
3566 $content .= '<div class="body-attach">' . $trailing . '</div>';
3569 DI::profiler()->stopRecording();
3573 private static function addQuestions(array $item, string $content): string
3575 DI::profiler()->startRecording('rendering');
3576 if (!empty($item['question-id'])) {
3578 'id' => $item['question-id'],
3579 'multiple' => $item['question-multiple'],
3580 'voters' => $item['question-voters'],
3581 'endtime' => $item['question-end-time']
3584 $options = Post\QuestionOption::getByURIId($item['uri-id']);
3585 foreach ($options as $key => $option) {
3586 if ($question['voters'] > 0) {
3587 $percent = $option['replies'] / $question['voters'] * 100;
3588 $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));
3590 $options[$key]['vote'] = DI::l10n()->tt('%2$s (%1$d vote)', '%2$s (%1$d votes)', $option['replies'], $option['name']);
3594 if (!empty($question['voters']) && !empty($question['endtime'])) {
3595 $summary = DI::l10n()->tt('%d voter. Poll end: %s', '%d voters. Poll end: %s', $question['voters'], Temporal::getRelativeDate($question['endtime']));
3596 } elseif (!empty($question['voters'])) {
3597 $summary = DI::l10n()->tt('%d voter.', '%d voters.', $question['voters']);
3598 } elseif (!empty($question['endtime'])) {
3599 $summary = DI::l10n()->t('Poll end: %s', Temporal::getRelativeDate($question['endtime']));
3604 $content .= Renderer::replaceMacros(Renderer::getMarkupTemplate('content/question.tpl'), [
3605 '$question' => $question,
3606 '$options' => $options,
3607 '$summary' => $summary,
3610 DI::profiler()->stopRecording();
3615 * get private link for item
3617 * @param array $item
3618 * @return boolean|array False if item has not plink, otherwise array('href'=>plink url, 'title'=>translated title)
3619 * @throws \Exception
3621 public static function getPlink(array $item)
3623 if (!empty($item['plink']) && Network::isValidHttpUrl($item['plink'])) {
3624 $plink = $item['plink'];
3625 } elseif (!empty($item['uri']) && Network::isValidHttpUrl($item['uri']) && !Network::isLocalLink($item['uri'])) {
3626 $plink = $item['uri'];
3629 if (DI::userSession()->getLocalUserId()) {
3631 'href' => "display/" . $item['guid'],
3632 'orig' => "display/" . $item['guid'],
3633 'title' => DI::l10n()->t('View on separate page'),
3634 'orig_title' => DI::l10n()->t('View on separate page'),
3637 if (!empty($plink) && ($item['private'] == self::PRIVATE)) {
3638 $author = ['uid' => 0, 'id' => $item['author-id'],
3639 'network' => $item['author-network'], 'url' => $item['author-link']];
3640 $plink = Contact::magicLinkByContact($author, $plink);
3643 if (!empty($plink)) {
3644 $ret['href'] = DI::baseUrl()->remove($plink);
3645 $ret['title'] = DI::l10n()->t('Link to source');
3647 } elseif (!empty($plink) && ($item['private'] != self::PRIVATE)) {
3651 'title' => DI::l10n()->t('Link to source'),
3652 'orig_title' => DI::l10n()->t('Link to source'),
3662 * Does the given uri-id belongs to a post that is sent as starting post to a forum?
3664 * @param int $uri_id
3666 * @return boolean "true" when it is a forum post
3668 public static function isForumPost(int $uri_id): bool
3670 foreach (Tag::getByURIId($uri_id, [Tag::EXCLUSIVE_MENTION]) as $tag) {
3671 if (DBA::exists('contact', ['uid' => 0, 'nurl' => Strings::normaliseLink($tag['url']), 'contact-type' => Contact::TYPE_COMMUNITY])) {
3679 * Search item id for given URI or plink
3681 * @param string $uri
3682 * @param integer $uid
3684 * @return integer item id
3686 public static function searchByLink(string $uri, int $uid = 0): int
3688 $ssl_uri = str_replace('http://', 'https://', $uri);
3689 $uris = [$uri, $ssl_uri, Strings::normaliseLink($uri)];
3691 $item = Post::selectFirst(['id'], ['uri' => $uris, 'uid' => $uid]);
3692 if (DBA::isResult($item)) {
3696 $item = Post::selectFirst(['id'], ['plink' => $uris, 'uid' => $uid]);
3697 if (DBA::isResult($item)) {
3705 * Return the URI for a link to the post
3707 * @param string $uri URI or link to post
3709 * @return string URI
3711 public static function getURIByLink(string $uri): string
3713 $ssl_uri = str_replace('http://', 'https://', $uri);
3714 $uris = [$uri, $ssl_uri, Strings::normaliseLink($uri)];
3716 $item = Post::selectFirst(['uri'], ['uri' => $uris]);
3717 if (DBA::isResult($item)) {
3718 return $item['uri'];
3721 $item = Post::selectFirst(['uri'], ['plink' => $uris]);
3722 if (DBA::isResult($item)) {
3723 return $item['uri'];
3730 * Fetches item for given URI or plink
3732 * @param string $uri
3733 * @param integer $uid
3735 * @return integer item id
3737 public static function fetchByLink(string $uri, int $uid = 0): int
3739 Logger::info('Trying to fetch link', ['uid' => $uid, 'uri' => $uri]);
3740 $item_id = self::searchByLink($uri, $uid);
3741 if (!empty($item_id)) {
3742 Logger::info('Link found', ['uid' => $uid, 'uri' => $uri, 'id' => $item_id]);
3752 Hook::callAll('item_by_link', $hookData);
3754 if (isset($hookData['item_id'])) {
3755 return is_numeric($hookData['item_id']) ? $hookData['item_id'] : 0;
3758 $fetched_uri = ActivityPub\Processor::fetchMissingActivity($uri, [], '', ActivityPub\Receiver::COMPLETION_MANUAL, $uid);
3761 $item_id = self::searchByLink($fetched_uri, $uid);
3763 $item_id = Diaspora::fetchByURL($uri);
3766 if (!empty($item_id)) {
3767 Logger::info('Link fetched', ['uid' => $uid, 'uri' => $uri, 'id' => $item_id]);
3771 Logger::info('Link not found', ['uid' => $uid, 'uri' => $uri]);
3776 * Fetch the uri-id of a quote
3778 * @param string $body
3781 public static function getQuoteUriId(string $body, int $uid = 0): int
3783 $shared = BBCode::fetchShareAttributes($body);
3784 if (empty($shared['guid']) && empty($shared['message_id'])) {
3788 if (empty($shared['link']) && empty($shared['message_id'])) {
3789 Logger::notice('Invalid share block.', ['share' => $shared]);
3793 if (!empty($shared['guid'])) {
3794 $shared_item = Post::selectFirst(['uri-id'], ['guid' => $shared['guid'], 'uid' => [0, $uid]]);
3795 if (!empty($shared_item['uri-id'])) {
3796 Logger::debug('Found post by guid', ['guid' => $shared['guid'], 'uid' => $uid]);
3797 return $shared_item['uri-id'];
3801 if (!empty($shared['message_id'])) {
3802 $shared_item = Post::selectFirst(['uri-id'], ['uri' => $shared['message_id'], 'uid' => [0, $uid]]);
3803 if (!empty($shared_item['uri-id'])) {
3804 Logger::debug('Found post by message_id', ['message_id' => $shared['message_id'], 'uid' => $uid]);
3805 return $shared_item['uri-id'];
3809 if (!empty($shared['link'])) {
3810 $shared_item = Post::selectFirst(['uri-id'], ['plink' => $shared['link'], 'uid' => [0, $uid]]);
3811 if (!empty($shared_item['uri-id'])) {
3812 Logger::debug('Found post by link', ['link' => $shared['link'], 'uid' => $uid]);
3813 return $shared_item['uri-id'];
3817 $url = $shared['message_id'] ?: $shared['link'];
3818 $id = self::fetchByLink($url);
3820 Logger::notice('Post could not be fetched.', ['url' => $url, 'uid' => $uid]);
3824 $shared_item = Post::selectFirst(['uri-id'], ['id' => $id]);
3825 if (!empty($shared_item['uri-id'])) {
3826 Logger::debug('Fetched shared post', ['id' => $id, 'url' => $url, 'uid' => $uid]);
3827 return $shared_item['uri-id'];
3830 Logger::warning('Post does not exist although it was supposed to had been fetched.', ['id' => $id, 'url' => $url, 'uid' => $uid]);