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\Protocol\Activity;
35 use Friendica\Protocol\ActivityPub;
36 use Friendica\Protocol\Delivery;
37 use Friendica\Protocol\Diaspora;
38 use Friendica\Util\DateTimeFormat;
39 use Friendica\Util\Map;
40 use Friendica\Util\Network;
41 use Friendica\Util\Proxy;
42 use Friendica\Util\Strings;
43 use Friendica\Util\Temporal;
44 use GuzzleHttp\Psr7\Uri;
45 use LanguageDetection\Language;
49 // Posting types, inspired by https://www.w3.org/TR/activitystreams-vocabulary/#object-types
56 const PT_DOCUMENT = 19;
59 const PT_PERSONAL_NOTE = 128;
61 // Posting reasons (Why had a post been stored for a user?)
68 const PR_FOLLOWER = 69;
69 const PR_ANNOUNCEMENT = 70;
70 const PR_COMMENT = 71;
74 const PR_FETCHED = 75;
75 const PR_COMPLETION = 76;
77 const PR_ACTIVITY = 78;
78 const PR_DISTRIBUTE = 79;
82 // system.accept_only_sharer setting values
83 const COMPLETION_NONE = 1;
84 const COMPLETION_COMMENT = 0;
85 const COMPLETION_LIKE = 2;
87 // Field list that is used to display the items
88 const DISPLAY_FIELDLIST = [
89 'uid', 'id', 'parent', 'guid', 'network', 'gravity',
90 'uri-id', 'uri', 'thr-parent-id', 'thr-parent', 'parent-uri-id', 'parent-uri', 'conversation',
91 'commented', 'created', 'edited', 'received', 'verb', 'object-type', 'postopts', 'plink',
92 'wall', 'private', 'starred', 'origin', 'parent-origin', 'title', 'body', 'language',
93 'content-warning', 'location', 'coord', 'app', 'rendered-hash', 'rendered-html', 'object',
94 'quote-uri', 'quote-uri-id', 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid', 'mention', 'global',
95 'author-id', 'author-link', 'author-name', 'author-avatar', 'author-network', 'author-updated', 'author-gsid', 'author-addr', 'author-uri-id',
96 'owner-id', 'owner-link', 'owner-name', 'owner-avatar', 'owner-network', 'owner-contact-type', 'owner-updated',
97 'causer-id', 'causer-link', 'causer-name', 'causer-avatar', 'causer-contact-type', 'causer-network',
98 'contact-id', 'contact-uid', 'contact-link', 'contact-name', 'contact-avatar',
99 'writable', 'self', 'cid', 'alias',
100 'event-created', 'event-edited', 'event-start', 'event-finish',
101 'event-summary', 'event-desc', 'event-location', 'event-type',
102 'event-nofinish', 'event-ignore', 'event-id',
103 'question-id', 'question-multiple', 'question-voters', 'question-end-time',
104 'has-categories', 'has-media',
105 'delivery_queue_count', 'delivery_queue_done', 'delivery_queue_failed'
108 // Field list that is used to deliver items via the protocols
109 const DELIVER_FIELDLIST = ['uid', 'id', 'parent', 'uri-id', 'uri', 'thr-parent', 'parent-uri', 'guid',
110 'parent-guid', 'conversation', 'received', 'created', 'edited', 'verb', 'object-type', 'object', 'target',
111 'private', 'title', 'body', 'raw-body', 'location', 'coord', 'app',
112 'inform', 'deleted', 'extid', 'post-type', 'post-reason', 'gravity',
113 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid',
114 'author-id', 'author-addr', 'author-link', 'author-name', 'author-avatar', 'owner-id', 'owner-link', 'contact-uid',
115 'signed_text', 'network', 'wall', 'contact-id', 'plink', 'origin',
116 'thr-parent-id', 'parent-uri-id', 'quote-uri', 'quote-uri-id', 'postopts', 'pubmail',
117 'event-created', 'event-edited', 'event-start', 'event-finish',
118 'event-summary', 'event-desc', 'event-location', 'event-type',
119 'event-nofinish', 'event-ignore', 'event-id'];
121 // All fields in the item table
122 const ITEM_FIELDLIST = ['id', 'uid', 'parent', 'uri', 'parent-uri', 'thr-parent',
123 'guid', 'uri-id', 'parent-uri-id', 'thr-parent-id', 'conversation', 'vid',
124 'quote-uri', 'quote-uri-id', 'contact-id', 'wall', 'gravity', 'extid', 'psid',
125 'created', 'edited', 'commented', 'received', 'changed', 'verb',
126 'postopts', 'plink', 'resource-id', 'event-id', 'inform',
127 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid', 'post-type', 'post-reason',
128 'private', 'pubmail', 'visible', 'starred',
129 'unseen', 'deleted', 'origin', 'mention', 'global', 'network',
130 'title', 'content-warning', 'body', 'location', 'coord', 'app',
131 'rendered-hash', 'rendered-html', 'object-type', 'object', 'target-type', 'target',
132 'author-id', 'author-link', 'author-name', 'author-avatar', 'author-network',
133 'owner-id', 'owner-link', 'owner-name', 'owner-avatar', 'causer-id'];
135 // List of all verbs that don't need additional content data.
136 // Never reorder or remove entries from this list. Just add new ones at the end, if needed.
138 Activity::LIKE, Activity::DISLIKE,
139 Activity::ATTEND, Activity::ATTENDNO, Activity::ATTENDMAYBE,
148 // Item weight for query ordering
149 const GRAVITY_PARENT = 0;
150 const GRAVITY_ACTIVITY = 3;
151 const GRAVITY_COMMENT = 6;
152 const GRAVITY_UNKNOWN = 9;
155 * Update existing item entries
157 * @param array $fields The fields that are to be changed
158 * @param array $condition The condition for finding the item entries
160 * In the future we may have to change permissions as well.
161 * Then we had to add the user id as third parameter.
163 * A return value of "0" doesn't mean an error - but that 0 rows had been changed.
165 * @return integer|boolean number of affected rows - or "false" if there was an error
166 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
168 public static function update(array $fields, array $condition)
170 if (empty($condition) || empty($fields)) {
174 if (isset($fields['extid'])) {
175 $fields['external-id'] = ItemURI::getIdByURI($fields['extid']);
178 if (!empty($fields['verb'])) {
179 $fields['vid'] = Verb::getID($fields['verb']);
182 if (!empty($fields['edited'])) {
183 $previous = Post::selectFirst(['edited'], $condition);
186 $rows = Post::update($fields, $condition);
187 if (is_bool($rows)) {
191 // We only need to call the line by line update for specific fields
192 if (empty($fields['body']) && empty($fields['file']) &&
193 empty($fields['attach']) && empty($fields['edited'])) {
197 Logger::info('Updating per single row method', ['fields' => $fields, 'condition' => $condition]);
199 $items = Post::select(['id', 'origin', 'uri-id', 'uid', 'author-network', 'quote-uri-id'], $condition);
203 while ($item = DBA::fetch($items)) {
204 if (!empty($fields['body'])) {
205 if (!empty($item['quote-uri-id'])) {
206 $fields['body'] = BBCode::removeSharedData($fields['body']);
208 if (!empty($fields['raw-body'])) {
209 $fields['raw-body'] = BBCode::removeSharedData($fields['raw-body']);
213 Post\Media::insertFromAttachmentData($item['uri-id'], $fields['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']);
223 Post\Content::update($item['uri-id'], $content_fields);
226 if (!empty($fields['file'])) {
227 Post\Category::storeTextByURIId($item['uri-id'], $item['uid'], $fields['file']);
230 if (!empty($fields['attach'])) {
231 Post\Media::insertFromAttachment($item['uri-id'], $fields['attach']);
234 // We only need to notfiy others when it is an original entry from us.
235 // Only call the notifier when the item had been edited and records had been changed.
236 if ($item['origin'] && !empty($fields['edited']) && ($previous['edited'] != $fields['edited'])) {
237 $notify_items[] = $item['id'];
243 foreach ($notify_items as $notify_item) {
244 $post = Post::selectFirst(['uri-id', 'uid'], ['id' => $notify_item]);
245 Worker::add(Worker::PRIORITY_HIGH, 'Notifier', Delivery::POST, (int)$post['uri-id'], (int)$post['uid']);
252 * Delete an item and notify others about it - if it was ours
254 * @param array $condition The condition for finding the item entries
255 * @param integer $priority Priority for the notification
257 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
259 public static function markForDeletion(array $condition, int $priority = Worker::PRIORITY_HIGH)
261 $items = Post::select(['id'], $condition);
262 while ($item = Post::fetch($items)) {
263 self::markForDeletionById($item['id'], $priority);
269 * Delete an item for an user and notify others about it - if it was ours
271 * @param array $condition The condition for finding the item entries
272 * @param integer $uid User who wants to delete this item
274 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
276 public static function deleteForUser(array $condition, int $uid)
282 $items = Post::select(['id', 'uid', 'uri-id'], $condition);
283 while ($item = Post::fetch($items)) {
284 if (in_array($item['uid'], [$uid, 0])) {
285 Post\User::update($item['uri-id'], $uid, ['hidden' => true], true);
286 Post\ThreadUser::update($item['uri-id'], $uid, ['hidden' => true], true);
289 if ($item['uid'] == $uid) {
290 self::markForDeletionById($item['id'], Worker::PRIORITY_HIGH);
291 } elseif ($item['uid'] != 0) {
292 Logger::warning('Wrong ownership. Not deleting item', ['id' => $item['id']]);
299 * Mark an item for deletion, delete related data and notify others about it - if it was ours
301 * @param integer $item_id
302 * @param integer $priority Priority for the notification
303 * @return boolean success
304 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
306 public static function markForDeletionById(int $item_id, int $priority = Worker::PRIORITY_HIGH): bool
308 Logger::info('Mark item for deletion by id', ['id' => $item_id, 'callstack' => System::callstack()]);
309 // locate item to be deleted
310 $fields = ['id', 'uri', 'uri-id', 'uid', 'parent', 'parent-uri-id', 'origin',
311 'deleted', 'resource-id', 'event-id',
312 'verb', 'object-type', 'object', 'target', 'contact-id', 'psid', 'gravity'];
313 $item = Post::selectFirst($fields, ['id' => $item_id]);
314 if (!DBA::isResult($item)) {
315 Logger::info('Item not found.', ['id' => $item_id]);
319 if ($item['deleted']) {
320 Logger::info('Item has already been marked for deletion.', ['id' => $item_id]);
324 $parent = Post::selectFirst(['origin'], ['id' => $item['parent']]);
325 if (!DBA::isResult($parent)) {
326 $parent = ['origin' => false];
329 // clean up categories and tags so they don't end up as orphans
330 Post\Category::deleteByURIId($item['uri-id'], $item['uid']);
333 * If item is a link to a photo resource, nuke all the associated photos
334 * (visitors will not have photo resources)
335 * This only applies to photos uploaded from the photos page. Photos inserted into a post do not
336 * generate a resource-id and therefore aren't intimately linked to the item.
338 /// @TODO: this should first check if photo is used elsewhere
339 if ($item['resource-id']) {
340 Photo::delete(['resource-id' => $item['resource-id'], 'uid' => $item['uid']]);
343 // If item is a link to an event, delete the event.
344 if (intval($item['event-id'])) {
345 Event::delete($item['event-id']);
348 // If item has attachments, drop them
349 $attachments = Post\Media::getByURIId($item['uri-id'], [Post\Media::DOCUMENT]);
350 foreach($attachments as $attachment) {
351 if (preg_match('|attach/(\d+)|', $attachment['url'], $matches)) {
352 Attach::delete(['id' => $matches[1], 'uid' => $item['uid']]);
356 // Set the item to "deleted"
357 $item_fields = ['deleted' => true, 'edited' => DateTimeFormat::utcNow(), 'changed' => DateTimeFormat::utcNow()];
358 Post::update($item_fields, ['id' => $item['id']]);
360 Post\Category::storeTextByURIId($item['uri-id'], $item['uid'], '');
362 if (!Post::exists(["`uri-id` = ? AND `uid` != 0 AND NOT `deleted`", $item['uri-id']])) {
363 self::markForDeletion(['uri-id' => $item['uri-id'], 'uid' => 0, 'deleted' => false], $priority);
366 Post\DeliveryData::delete($item['uri-id']);
368 // If it's the parent of a comment thread, kill all the kids
369 if ($item['gravity'] == self::GRAVITY_PARENT) {
370 self::markForDeletion(['parent' => $item['parent'], 'deleted' => false], $priority);
373 // Is it our comment and/or our thread?
374 if (($item['origin'] || $parent['origin']) && ($item['uid'] != 0)) {
375 // When we delete the original post we will delete all existing copies on the server as well
376 self::markForDeletion(['uri-id' => $item['uri-id'], 'deleted' => false], $priority);
378 // send the notification upstream/downstream
380 Worker::add(['priority' => $priority, 'dont_fork' => true], 'Notifier', Delivery::DELETION, (int)$item['uri-id'], (int)$item['uid']);
382 } elseif ($item['uid'] != 0) {
383 Post\User::update($item['uri-id'], $item['uid'], ['hidden' => true]);
384 Post\ThreadUser::update($item['uri-id'], $item['uid'], ['hidden' => true]);
387 DI::notify()->deleteForItem($item['uri-id']);
388 DI::notification()->deleteForItem($item['uri-id']);
390 Logger::info('Item has been marked for deletion.', ['id' => $item_id]);
396 * Get guid from given item record
398 * @param array $item Item record
399 * @param bool Whether to notify (?)
400 * @return string Guid
402 public static function guid(array $item, bool $notify): string
404 if (!empty($item['guid'])) {
405 return trim($item['guid']);
409 // We have to avoid duplicates. So we create the GUID in form of a hash of the plink or uri.
410 // We add the hash of our own host because our host is the original creator of the post.
411 $prefix_host = DI::baseUrl()->getHostname();
415 // We are only storing the post so we create a GUID from the original hostname.
416 if (!empty($item['author-link'])) {
417 $parsed = parse_url($item['author-link']);
418 if (!empty($parsed['host'])) {
419 $prefix_host = $parsed['host'];
423 if (empty($prefix_host) && !empty($item['plink'])) {
424 $parsed = parse_url($item['plink']);
425 if (!empty($parsed['host'])) {
426 $prefix_host = $parsed['host'];
430 if (empty($prefix_host) && !empty($item['uri'])) {
431 $parsed = parse_url($item['uri']);
432 if (!empty($parsed['host'])) {
433 $prefix_host = $parsed['host'];
437 // Is it in the format data@host.tld? - Used for mail contacts
438 if (empty($prefix_host) && !empty($item['author-link']) && strstr($item['author-link'], '@')) {
439 $mailparts = explode('@', $item['author-link']);
440 $prefix_host = array_pop($mailparts);
444 if (!empty($item['plink'])) {
445 $guid = self::guidFromUri($item['plink'], $prefix_host);
446 } elseif (!empty($item['uri'])) {
447 $guid = self::guidFromUri($item['uri'], $prefix_host);
449 $guid = System::createUUID(hash('crc32', $prefix_host));
456 * Returns contact id from given item record
458 * @param array $item Item record
459 * @return int Contact id
461 private static function contactId(array $item): int
463 if ($item['uid'] == 0) {
464 return $item['author-id'];
467 if ($item['origin']) {
468 $owner = User::getOwnerDataById($item['uid']);
472 if (!empty($item['causer-id']) && Contact::isSharing($item['causer-id'], $item['uid'], true)) {
473 $cdata = Contact::getPublicAndUserContactID($item['causer-id'], $item['uid']);
474 if (!empty($cdata['user'])) {
475 return $cdata['user'];
479 if ($item['gravity'] == self::GRAVITY_PARENT) {
480 if (Contact::isSharingByURL($item['owner-link'], $item['uid'], true)) {
481 $contact_id = Contact::getIdForURL($item['owner-link'], $item['uid']);
483 $contact_id = Contact::getIdForURL($item['owner-link']);
485 if (!empty($contact_id)) {
490 if (Contact::isSharingByURL($item['author-link'], $item['uid'], true)) {
491 $contact_id = Contact::getIdForURL($item['author-link'], $item['uid']);
493 $contact_id = Contact::getIdForURL($item['author-link']);
496 if (!empty($contact_id)) {
500 Logger::warning('contact-id could not be fetched, using self contact instead.', ['uid' => $item['uid'], 'item' => $item]);
501 $self = Contact::selectFirst(['id'], ['self' => true, 'uid' => $item['uid']]);
506 * Write an item array into a spool file to be inserted later.
507 * This command is called whenever there are issues storing an item.
509 * @param array $item The item fields that are to be inserted
512 private static function spool(array $item)
514 // Now we store the data in the spool directory
515 // We use "microtime" to keep the arrival order and "mt_rand" to avoid duplicates
516 $file = 'item-' . round(microtime(true) * 10000) . '-' . mt_rand() . '.msg';
518 $spoolpath = System::getSpoolPath();
519 if ($spoolpath != '') {
520 $spool = $spoolpath . '/' . $file;
522 file_put_contents($spool, json_encode($item));
523 Logger::warning("Item wasn't stored - Item was spooled into file", ['file' => $file]);
528 * Check if the item array is a duplicate
530 * @param array $item Item record
531 * @return boolean is it a duplicate?
533 private static function isDuplicate(array $item): bool
535 // Checking if there is already an item with the same guid
536 $condition = ['guid' => $item['guid'], 'network' => $item['network'], 'uid' => $item['uid']];
537 if (Post::exists($condition)) {
538 Logger::notice('Found already existing item', $condition);
542 $condition = ['uri-id' => $item['uri-id'], 'uid' => $item['uid'],
543 'network' => [$item['network'], Protocol::DFRN]];
544 if (Post::exists($condition)) {
545 Logger::notice('duplicated item with the same uri found.', $condition);
549 // On Friendica and Diaspora the GUID is unique
550 if (in_array($item['network'], [Protocol::DFRN, Protocol::DIASPORA])) {
551 $condition = ['guid' => $item['guid'], 'uid' => $item['uid']];
552 if (Post::exists($condition)) {
553 Logger::notice('duplicated item with the same guid found.', $condition);
556 } elseif ($item['network'] == Protocol::OSTATUS) {
557 // Check for an existing post with the same content. There seems to be a problem with OStatus.
558 $condition = ["`body` = ? AND `network` = ? AND `created` = ? AND `contact-id` = ? AND `uid` = ?",
559 $item['body'], $item['network'], $item['created'], $item['contact-id'], $item['uid']];
560 if (Post::exists($condition)) {
561 Logger::notice('duplicated item with the same body found.', $item);
567 * Check for already added items.
568 * There is a timing issue here that sometimes creates double postings.
569 * An unique index would help - but the limitations of MySQL (maximum size of index values) prevent this.
571 if (($item['uid'] == 0) && Post::exists(['uri-id' => $item['uri-id'], 'uid' => 0])) {
572 Logger::notice('Global item already stored.', ['uri-id' => $item['uri-id'], 'network' => $item['network']]);
580 * Check if the item array is valid
582 * @param array $item Item record
583 * @return boolean item is valid
585 public static function isValid(array $item): bool
587 // When there is no content then we don't post it
588 if (($item['body'] . $item['title'] == '') && empty($item['quote-uri-id']) && (empty($item['uri-id']) || !Post\Media::existsByURIId($item['uri-id']))) {
589 Logger::notice('No body, no title.');
593 if (!empty($item['uid'])) {
594 $owner = User::getOwnerDataById($item['uid'], false);
596 Logger::warning('Missing item user owner data', ['uid' => $item['uid']]);
600 if ($owner['account_expired'] || $owner['account_removed']) {
601 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']]);
606 if (!empty($item['author-id']) && Contact::isBlocked($item['author-id'])) {
607 Logger::notice('Author is blocked node-wide', ['author-link' => $item['author-link'], 'item-uri' => $item['uri']]);
611 if (!empty($item['author-link']) && Network::isUrlBlocked($item['author-link'])) {
612 Logger::notice('Author server is blocked', ['author-link' => $item['author-link'], 'item-uri' => $item['uri']]);
616 if (!empty($item['owner-id']) && Contact::isBlocked($item['owner-id'])) {
617 Logger::notice('Owner is blocked node-wide', ['owner-link' => $item['owner-link'], 'item-uri' => $item['uri']]);
621 if (!empty($item['owner-link']) && Network::isUrlBlocked($item['owner-link'])) {
622 Logger::notice('Owner server is blocked', ['owner-link' => $item['owner-link'], 'item-uri' => $item['uri']]);
626 if (!empty($item['uid']) && !self::isAllowedByUser($item, $item['uid'])) {
630 if ($item['verb'] == Activity::FOLLOW) {
631 if (!$item['origin'] && ($item['author-id'] == Contact::getPublicIdByUserId($item['uid']))) {
632 // Our own follow request can be relayed to us. We don't store it to avoid notification chaos.
633 Logger::info("Follow: Don't store not origin follow request", ['parent-uri' => $item['parent-uri']]);
637 $condition = ['verb' => Activity::FOLLOW, 'uid' => $item['uid'],
638 'parent-uri' => $item['parent-uri'], 'author-id' => $item['author-id']];
639 if (Post::exists($condition)) {
640 // It happens that we receive multiple follow requests by the same author - we only store one.
641 Logger::info('Follow: Found existing follow request from author', ['author-id' => $item['author-id'], 'parent-uri' => $item['parent-uri']]);
650 * Check if the item array is too old
652 * @param array $item Item record
653 * @return boolean item is too old
655 public static function isTooOld(array $item): bool
657 // check for create date and expire time
658 $expire_interval = DI::config()->get('system', 'dbclean-expire-days', 0);
660 $user = DBA::selectFirst('user', ['expire'], ['uid' => $item['uid']]);
661 if (DBA::isResult($user) && ($user['expire'] > 0) && (($user['expire'] < $expire_interval) || ($expire_interval == 0))) {
662 $expire_interval = $user['expire'];
665 if (($expire_interval > 0) && !empty($item['created'])) {
666 $expire_date = time() - ($expire_interval * 86400);
667 $created_date = strtotime($item['created']);
668 if ($created_date < $expire_date) {
669 Logger::notice('Item created before expiration interval.', [
670 'created' => date('c', $created_date),
671 'expired' => date('c', $expire_date),
682 * Return the id of the given item array if it has been stored before
684 * @param array $item Item record
685 * @return integer Item id or zero on error
687 private static function getDuplicateID(array $item): int
689 if (empty($item['network']) || in_array($item['network'], Protocol::FEDERATED)) {
690 $condition = ['`uri-id` = ? AND `uid` = ? AND `network` IN (?, ?, ?, ?)',
693 Protocol::ACTIVITYPUB,
698 $existing = Post::selectFirst(['id', 'network'], $condition);
699 if (DBA::isResult($existing)) {
700 // We only log the entries with a different user id than 0. Otherwise we would have too many false positives
701 if ($item['uid'] != 0) {
702 Logger::notice('Item already existed for user', [
703 'uri-id' => $item['uri-id'],
704 'uid' => $item['uid'],
705 'network' => $item['network'],
706 'existing_id' => $existing['id'],
707 'existing_network' => $existing['network']
711 return $existing['id'];
718 * Fetch the uri-id of the parent for the given uri-id
720 * @param integer $uriid
723 public static function getParent(int $uriid): int
725 $thread_parent = Post::selectFirstPost(['thr-parent-id', 'gravity'], ['uri-id' => $uriid]);
726 if (empty($thread_parent)) {
730 if ($thread_parent['gravity'] == Item::GRAVITY_PARENT) {
734 return self::getParent($thread_parent['thr-parent-id']);
738 * Fetch top-level parent data for the given item array
741 * @return array item array with parent data
744 private static function getTopLevelParent(array $item): array
746 $fields = ['uid', 'uri', 'parent-uri', 'id', 'deleted',
747 'uri-id', 'parent-uri-id',
748 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid',
749 'wall', 'private', 'origin', 'author-id'];
750 $condition = ['uri-id' => [$item['thr-parent-id'], $item['parent-uri-id']], 'uid' => $item['uid']];
751 $params = ['order' => ['id' => false]];
752 $parent = Post::selectFirst($fields, $condition, $params);
754 if (!DBA::isResult($parent) && Post::exists(['uri-id' => [$item['thr-parent-id'], $item['parent-uri-id']], 'uid' => 0])) {
755 $stored = Item::storeForUserByUriId($item['thr-parent-id'], $item['uid'], ['post-reason' => Item::PR_COMPLETION]);
756 if (!$stored && ($item['thr-parent-id'] != $item['parent-uri-id'])) {
757 $stored = Item::storeForUserByUriId($item['parent-uri-id'], $item['uid'], ['post-reason' => Item::PR_COMPLETION]);
760 Logger::info('Stored thread parent item for user', ['uri-id' => $item['thr-parent-id'], 'uid' => $item['uid'], 'stored' => $stored]);
761 $parent = Post::selectFirst($fields, $condition, $params);
765 if (!DBA::isResult($parent)) {
766 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)]);
770 if ($parent['uri-id'] == $parent['parent-uri-id']) {
774 $condition = ['uri-id' => $parent['parent-uri-id'],
775 'parent-uri-id' => $parent['parent-uri-id'],
776 'uid' => $parent['uid']];
777 $params = ['order' => ['id' => false]];
778 $toplevel_parent = Post::selectFirst($fields, $condition, $params);
780 if (!DBA::isResult($toplevel_parent) && $item['origin']) {
781 $stored = Item::storeForUserByUriId($item['parent-uri-id'], $item['uid'], ['post-reason' => Item::PR_COMPLETION]);
782 Logger::info('Stored parent item for user', ['uri-id' => $item['parent-uri-id'], 'uid' => $item['uid'], 'stored' => $stored]);
783 $toplevel_parent = Post::selectFirst($fields, $condition, $params);
786 if (!DBA::isResult($toplevel_parent)) {
787 Logger::notice('item top level parent was not found - ignoring item', ['parent-uri-id' => $parent['parent-uri-id'], 'uid' => $parent['uid']]);
791 return $toplevel_parent;
795 * Get the gravity for the given item array
798 * @return integer gravity
800 private static function getGravity(array $item): int
802 $activity = DI::activity();
804 if (isset($item['gravity'])) {
805 return intval($item['gravity']);
806 } elseif ($item['parent-uri-id'] === $item['uri-id']) {
807 return self::GRAVITY_PARENT;
808 } elseif ($activity->match($item['verb'], Activity::POST)) {
809 return self::GRAVITY_COMMENT;
810 } elseif ($activity->match($item['verb'], Activity::FOLLOW)) {
811 return self::GRAVITY_ACTIVITY;
812 } elseif ($activity->match($item['verb'], Activity::ANNOUNCE)) {
813 return self::GRAVITY_ACTIVITY;
816 Logger::info('Unknown gravity for verb', ['verb' => $item['verb']]);
817 return self::GRAVITY_UNKNOWN; // Should not happen
820 private static function prepareOriginPost(array $item): array
822 $item = DI::contentItem()->initializePost($item);
824 if (Photo::setPermissionFromBody($item['body'], $item['uid'], $item['contact-id'], $item['allow_cid'], $item['allow_gid'], $item['deny_cid'], $item['deny_gid'])) {
825 $item['object-type'] = Activity\ObjectType::IMAGE;
828 $item = DI::contentItem()->moveAttachmentsFromBodyToAttach($item);
829 $item = DI::contentItem()->finalizePost($item);
835 * Inserts item record
837 * @param array $item Item array to be inserted
838 * @param int $notify Notification (type?)
839 * @param bool $post_local (???)
840 * @return int Zero means error, otherwise primary key (id) is being returned
842 public static function insert(array $item, int $notify = 0, bool $post_local = true): int
846 $priority = Worker::PRIORITY_HIGH;
848 // If it is a posting where users should get notifications, then define it as wall posting
850 $item = self::prepareOriginPost($item);
852 if (is_int($notify) && in_array($notify, Worker::PRIORITIES)) {
856 $item['network'] = trim(($item['network'] ?? '') ?: Protocol::PHANTOM);
859 $uid = intval($item['uid']);
861 $item['guid'] = self::guid($item, $notify);
862 $item['uri'] = substr(trim($item['uri'] ?? '') ?: self::newURI($item['guid']), 0, 255);
865 $item['uri-id'] = ItemURI::insert(['uri' => $item['uri'], 'guid' => $item['guid']]);
867 // Backward compatibility: parent-uri used to be the direct parent uri.
868 // If it is provided without a thr-parent, it probably is the old behavior.
869 if (empty($item['thr-parent']) || empty($item['parent-uri'])) {
870 $item['thr-parent'] = trim($item['thr-parent'] ?? $item['parent-uri'] ?? $item['uri']);
871 $item['parent-uri'] = $item['thr-parent'];
874 $item['thr-parent-id'] = ItemURI::getIdByURI($item['thr-parent']);
875 $item['parent-uri-id'] = ItemURI::getIdByURI($item['parent-uri']);
877 // Store conversation data
878 $source = $item['source'] ?? '';
879 unset($item['conversation-uri']);
880 unset($item['conversation-href']);
881 unset($item['source']);
884 * Do we already have this item?
885 * We have to check several networks since Friendica posts could be repeated
886 * via OStatus (maybe Diasporsa as well)
888 $duplicate = self::getDuplicateID($item);
893 // Additional duplicate checks
894 /// @todo Check why the first duplication check returns the item number and the second a 0
895 if (self::isDuplicate($item)) {
899 if (!isset($item['post-type'])) {
900 $item['post-type'] = empty($item['title']) ? self::PT_NOTE : self::PT_ARTICLE;
903 $item['wall'] = intval($item['wall'] ?? 0);
904 $item['extid'] = trim($item['extid'] ?? '');
905 $item['author-name'] = trim($item['author-name'] ?? '');
906 $item['author-link'] = trim($item['author-link'] ?? '');
907 $item['author-avatar'] = trim($item['author-avatar'] ?? '');
908 $item['owner-name'] = trim($item['owner-name'] ?? '');
909 $item['owner-link'] = trim($item['owner-link'] ?? '');
910 $item['owner-avatar'] = trim($item['owner-avatar'] ?? '');
911 $item['received'] = (isset($item['received']) ? DateTimeFormat::utc($item['received']) : DateTimeFormat::utcNow());
912 $item['created'] = (isset($item['created']) ? DateTimeFormat::utc($item['created']) : $item['received']);
913 $item['edited'] = (isset($item['edited']) ? DateTimeFormat::utc($item['edited']) : $item['created']);
914 $item['changed'] = (isset($item['changed']) ? DateTimeFormat::utc($item['changed']) : $item['created']);
915 $item['commented'] = (isset($item['commented']) ? DateTimeFormat::utc($item['commented']) : $item['created']);
916 $item['title'] = substr(trim($item['title'] ?? ''), 0, 255);
917 $item['location'] = trim($item['location'] ?? '');
918 $item['coord'] = trim($item['coord'] ?? '');
919 $item['visible'] = (isset($item['visible']) ? intval($item['visible']) : 1);
920 $item['deleted'] = 0;
921 $item['verb'] = trim($item['verb'] ?? '');
922 $item['object-type'] = trim($item['object-type'] ?? '');
923 $item['object'] = trim($item['object'] ?? '');
924 $item['target-type'] = trim($item['target-type'] ?? '');
925 $item['target'] = trim($item['target'] ?? '');
926 $item['plink'] = substr(trim($item['plink'] ?? ''), 0, 255);
927 $item['allow_cid'] = trim($item['allow_cid'] ?? '');
928 $item['allow_gid'] = trim($item['allow_gid'] ?? '');
929 $item['deny_cid'] = trim($item['deny_cid'] ?? '');
930 $item['deny_gid'] = trim($item['deny_gid'] ?? '');
931 $item['private'] = intval($item['private'] ?? self::PUBLIC);
932 $item['body'] = trim($item['body'] ?? '');
933 $item['raw-body'] = trim($item['raw-body'] ?? $item['body']);
934 $item['app'] = trim($item['app'] ?? '');
935 $item['origin'] = intval($item['origin'] ?? 0);
936 $item['postopts'] = trim($item['postopts'] ?? '');
937 $item['resource-id'] = trim($item['resource-id'] ?? '');
938 $item['event-id'] = intval($item['event-id'] ?? 0);
939 $item['inform'] = trim($item['inform'] ?? '');
940 $item['file'] = trim($item['file'] ?? '');
942 // Communities aren't working with the Diaspora protoccol
943 if (($uid != 0) && ($item['network'] == Protocol::DIASPORA)) {
944 $user = User::getById($uid, ['account-type']);
945 if ($user['account-type'] == Contact::TYPE_COMMUNITY) {
946 Logger::info('Community posts are not supported via Diaspora');
951 // Items cannot be stored before they happen ...
952 if ($item['created'] > DateTimeFormat::utcNow()) {
953 $item['created'] = DateTimeFormat::utcNow();
956 // We haven't invented time travel by now.
957 if ($item['edited'] > DateTimeFormat::utcNow()) {
958 $item['edited'] = DateTimeFormat::utcNow();
961 $item['plink'] = ($item['plink'] ?? '') ?: DI::baseUrl() . '/display/' . urlencode($item['guid']);
963 $item['gravity'] = self::getGravity($item);
965 $default = ['url' => $item['author-link'], 'name' => $item['author-name'],
966 'photo' => $item['author-avatar'], 'network' => $item['network']];
967 $item['author-id'] = ($item['author-id'] ?? 0) ?: Contact::getIdForURL($item['author-link'], 0, null, $default);
969 $default = ['url' => $item['owner-link'], 'name' => $item['owner-name'],
970 'photo' => $item['owner-avatar'], 'network' => $item['network']];
971 $item['owner-id'] = ($item['owner-id'] ?? 0) ?: Contact::getIdForURL($item['owner-link'], 0, null, $default);
973 $item['post-reason'] = self::getPostReason($item);
975 // Ensure that there is an avatar cache
976 Contact::checkAvatarCache($item['author-id']);
977 Contact::checkAvatarCache($item['owner-id']);
979 $item['contact-id'] = self::contactId($item);
981 if (!empty($item['direction']) && in_array($item['direction'], [Conversation::PUSH, Conversation::RELAY]) &&
982 empty($item['origin']) && self::isTooOld($item)) {
983 Logger::info('Item is too old', ['item' => $item]);
987 if (!self::isValid($item)) {
991 if ($item['gravity'] !== self::GRAVITY_PARENT) {
992 $toplevel_parent = self::getTopLevelParent($item);
993 if (empty($toplevel_parent)) {
997 // If the thread originated from this node, we check the permission against the thread starter
998 $condition = ['uri-id' => $toplevel_parent['uri-id'], 'wall' => true];
999 $localTopLevelParent = Post::selectFirst(['uid'], $condition);
1000 if (!empty($localTopLevelParent['uid']) && !self::isAllowedByUser($item, $localTopLevelParent['uid'])) {
1004 $parent_id = $toplevel_parent['id'];
1005 $item['parent-uri'] = $toplevel_parent['uri'];
1006 $item['parent-uri-id'] = $toplevel_parent['uri-id'];
1007 $item['deleted'] = $toplevel_parent['deleted'];
1008 $item['wall'] = $toplevel_parent['wall'];
1010 // Reshares have to keep their permissions to allow forums to work
1011 if (!$item['origin'] || ($item['verb'] != Activity::ANNOUNCE)) {
1012 $item['allow_cid'] = $toplevel_parent['allow_cid'];
1013 $item['allow_gid'] = $toplevel_parent['allow_gid'];
1014 $item['deny_cid'] = $toplevel_parent['deny_cid'];
1015 $item['deny_gid'] = $toplevel_parent['deny_gid'];
1018 $parent_origin = $toplevel_parent['origin'];
1020 // Don't federate received participation messages
1021 if ($item['verb'] != Activity::FOLLOW) {
1022 $item['wall'] = $toplevel_parent['wall'];
1024 $item['wall'] = false;
1025 // Participations are technical messages, so they are set to "seen" automatically
1026 $item['unseen'] = false;
1030 * If the parent is private, force privacy for the entire conversation
1031 * This differs from the above settings as it subtly allows comments from
1032 * email correspondents to be private even if the overall thread is not.
1034 if ($toplevel_parent['private']) {
1035 $item['private'] = $toplevel_parent['private'];
1038 // If its a post that originated here then tag the thread as "mention"
1039 if ($item['origin'] && $item['uid']) {
1040 DBA::update('post-thread-user', ['mention' => true], ['uri-id' => $item['parent-uri-id'], 'uid' => $item['uid']]);
1041 Logger::info('tagged thread as mention', ['parent' => $parent_id, 'parent-uri-id' => $item['parent-uri-id'], 'uid' => $item['uid']]);
1044 // Update the contact relations
1045 Contact\Relation::store($toplevel_parent['author-id'], $item['author-id'], $item['created']);
1048 $parent_origin = $item['origin'];
1050 if ($item['wall'] && empty($item['conversation'])) {
1051 $item['conversation'] = $item['parent-uri'] . '#context';
1055 $item['parent-uri-id'] = ItemURI::getIdByURI($item['parent-uri']);
1056 $item['thr-parent-id'] = ItemURI::getIdByURI($item['thr-parent']);
1058 if (!empty($item['conversation']) && empty($item['conversation-id'])) {
1059 $item['conversation-id'] = ItemURI::getIdByURI($item['conversation']);
1062 // Is this item available in the global items (with uid=0)?
1063 if ($item['uid'] == 0) {
1064 $item['global'] = true;
1066 // Set the global flag on all items if this was a global item entry
1067 Post::update(['global' => true], ['uri-id' => $item['uri-id']]);
1069 $item['global'] = Post::exists(['uid' => 0, 'uri-id' => $item['uri-id']]);
1073 if (!empty($item['allow_cid'] . $item['allow_gid'] . $item['deny_cid'] . $item['deny_gid'])) {
1074 $item['private'] = self::PRIVATE;
1077 if ($notify && $post_local) {
1078 $item['edit'] = false;
1079 $item['parent'] = $parent_id;
1081 // Trigger automatic reactions for addons
1082 if (!isset($item['api_source'])) {
1083 $item['api_source'] = true;
1086 // We have to tell the hooks who we are - this really should be improved
1087 if (!DI::userSession()->getLocalUserId()) {
1088 $_SESSION['authenticated'] = true;
1089 $_SESSION['uid'] = $uid;
1090 $dummy_session = true;
1092 $dummy_session = false;
1095 Hook::callAll('post_local', $item);
1097 if ($dummy_session) {
1098 unset($_SESSION['authenticated']);
1099 unset($_SESSION['uid']);
1101 } elseif (!$notify) {
1102 Hook::callAll('post_remote', $item);
1105 if (!empty($item['cancel'])) {
1106 Logger::notice('post cancelled by addon.');
1110 if (empty($item['vid']) && !empty($item['verb'])) {
1111 $item['vid'] = Verb::getID($item['verb']);
1114 // Creates or assigns the permission set
1115 $item['psid'] = DI::permissionSet()->selectOrCreate(
1116 DI::permissionSetFactory()->createFromString(
1124 if (!empty($item['extid'])) {
1125 $item['external-id'] = ItemURI::getIdByURI($item['extid']);
1128 if ($item['verb'] == Activity::ANNOUNCE) {
1129 self::setOwnerforResharedItem($item);
1132 if (isset($item['attachments'])) {
1133 foreach ($item['attachments'] as $attachment) {
1134 $attachment['uri-id'] = $item['uri-id'];
1135 Post\Media::insert($attachment);
1137 unset($item['attachments']);
1140 if (empty($item['quote-uri-id'])) {
1141 $quote_id = self::getQuoteUriId($item['body']);
1142 if (!empty($quote_id)) {
1143 // This is one of these "should not happen" situations.
1144 // The protocol implementations should already have done this job.
1145 Logger::notice('Quote-uri-id detected in post', ['id' => $quote_id, 'guid' => $item['guid'], 'uri-id' => $item['uri-id'], 'callstack' => System::callstack(20)]);
1146 $item['quote-uri-id'] = $quote_id;
1150 if (!empty($item['quote-uri-id'])) {
1151 $item['raw-body'] = BBCode::removeSharedData($item['raw-body']);
1152 $item['body'] = BBCode::removeSharedData($item['body']);
1155 Post\Media::insertFromAttachmentData($item['uri-id'], $item['body']);
1157 // Remove all media attachments from the body and store them in the post-media table
1158 $item['raw-body'] = Post\Media::insertFromBody($item['uri-id'], $item['raw-body']);
1159 $item['raw-body'] = self::setHashtags($item['raw-body']);
1161 $author = Contact::getById($item['author-id'], ['network']);
1162 Post\Media::insertFromRelevantUrl($item['uri-id'], $item['raw-body'], $item['body'], $author['network'] ?? '');
1164 // Check for hashtags in the body and repair or add hashtag links
1165 $item['body'] = self::setHashtags($item['body']);
1167 $item['language'] = self::getLanguage($item);
1169 $notify_type = Delivery::POST;
1171 // Filling item related side tables
1172 if (!empty($item['attach'])) {
1173 Post\Media::insertFromAttachment($item['uri-id'], $item['attach']);
1176 if (empty($item['event-id'])) {
1177 unset($item['event-id']);
1179 $ev = Event::fromBBCode($item['body']);
1180 if ((!empty($ev['desc']) || !empty($ev['summary'])) && !empty($ev['start'])) {
1181 Logger::info('Event found.');
1182 $ev['cid'] = $item['contact-id'];
1183 $ev['uid'] = $item['uid'];
1184 $ev['uri'] = $item['uri'];
1185 $ev['edited'] = $item['edited'];
1186 $ev['private'] = $item['private'];
1187 $ev['guid'] = $item['guid'];
1188 $ev['plink'] = $item['plink'];
1189 $ev['network'] = $item['network'];
1190 $ev['protocol'] = $item['protocol'] ?? Conversation::PARCEL_UNKNOWN;
1191 $ev['direction'] = $item['direction'] ?? Conversation::UNKNOWN;
1192 $ev['source'] = $item['source'] ?? '';
1194 $event = DBA::selectFirst('event', ['id'], ['uri' => $item['uri'], 'uid' => $item['uid']]);
1195 if (DBA::isResult($event)) {
1196 $ev['id'] = $event['id'];
1199 $event_id = Event::store($ev);
1200 $item = Event::getItemArrayForImportedId($event_id, $item);
1202 Logger::info('Event was stored', ['id' => $event_id]);
1206 if (empty($item['causer-id'])) {
1207 unset($item['causer-id']);
1210 if (in_array($item['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN])) {
1211 $content_warning = BBCode::getAbstract($item['body'], Protocol::ACTIVITYPUB);
1212 if (!empty($content_warning) && empty($item['content-warning'])) {
1213 $item['content-warning'] = BBCode::toPlaintext($content_warning);
1217 Post::insert($item['uri-id'], $item);
1219 if ($item['gravity'] == self::GRAVITY_PARENT) {
1220 Post\Thread::insert($item['uri-id'], $item);
1223 if (!in_array($item['verb'], self::ACTIVITIES)) {
1224 Post\Content::insert($item['uri-id'], $item);
1227 // Create Diaspora signature
1228 if ($item['origin'] && empty($item['diaspora_signed_text']) && ($item['gravity'] != self::GRAVITY_PARENT)) {
1229 $signed = Diaspora::createCommentSignature($item);
1230 if (!empty($signed)) {
1231 $item['diaspora_signed_text'] = json_encode($signed);
1235 if (!empty($item['diaspora_signed_text'])) {
1236 DBA::replace('diaspora-interaction', ['uri-id' => $item['uri-id'], 'interaction' => $item['diaspora_signed_text']]);
1239 // Attached file links
1240 if (!empty($item['file'])) {
1241 Post\Category::storeTextByURIId($item['uri-id'], $item['uid'], $item['file']);
1244 // Delivery relevant data
1245 $delivery_data = Post\DeliveryData::extractFields($item);
1247 if (!empty($item['origin']) || !empty($item['wall']) || !empty($delivery_data['postopts']) || !empty($delivery_data['inform'])) {
1248 Post\DeliveryData::insert($item['uri-id'], $delivery_data);
1251 // Store tags from the body if this hadn't been handled previously in the protocol classes
1252 if (!Tag::existsForPost($item['uri-id'])) {
1253 Tag::storeFromBody($item['uri-id'], $item['body']);
1256 $condition = ['uri-id' => $item['uri-id'], 'uid' => $item['uid']];
1257 if (Post::exists($condition)) {
1258 Logger::notice('Item is already inserted - aborting', $condition);
1262 $post_user_id = Post\User::insert($item['uri-id'], $item['uid'], $item);
1263 if (!$post_user_id) {
1264 Logger::notice('Post-User is already inserted - aborting', ['uid' => $item['uid'], 'uri-id' => $item['uri-id']]);
1268 if ($item['gravity'] == self::GRAVITY_PARENT) {
1269 $item['post-user-id'] = $post_user_id;
1270 Post\ThreadUser::insert($item['uri-id'], $item['uid'], $item);
1273 Logger::notice('created item', ['post-id' => $post_user_id, 'uid' => $item['uid'], 'network' => $item['network'], 'uri-id' => $item['uri-id'], 'guid' => $item['guid']]);
1275 $posted_item = Post::selectFirst(self::ITEM_FIELDLIST, ['post-user-id' => $post_user_id]);
1276 if (!DBA::isResult($posted_item)) {
1277 // On failure store the data into a spool file so that the "SpoolPost" worker can try again later.
1278 Logger::warning('Could not store item. it will be spooled', ['id' => $post_user_id]);
1279 self::spool($orig_item);
1283 // update the commented timestamp on the parent
1284 if (DI::config()->get('system', 'like_no_comment')) {
1285 // Update when it is a comment
1286 $update_commented = in_array($posted_item['gravity'], [self::GRAVITY_PARENT, self::GRAVITY_COMMENT]);
1288 // Update when it isn't a follow or tag verb
1289 $update_commented = !in_array($posted_item['verb'], [Activity::FOLLOW, Activity::TAG]);
1292 if ($update_commented) {
1293 $fields = ['commented' => DateTimeFormat::utcNow(), 'changed' => DateTimeFormat::utcNow()];
1295 $fields = ['changed' => DateTimeFormat::utcNow()];
1298 Post::update($fields, ['uri-id' => $posted_item['parent-uri-id'], 'uid' => $posted_item['uid']]);
1300 // In that function we check if this is a forum post. Additionally we delete the item under certain circumstances
1301 if (self::tagDeliver($posted_item['uid'], $post_user_id)) {
1302 // Get the user information for the logging
1303 $user = User::getById($uid);
1305 Logger::notice('Item had been deleted', ['id' => $post_user_id, 'user' => $uid, 'account-type' => $user['account-type']]);
1310 DI::contentItem()->postProcessPost($posted_item);
1312 Hook::callAll('post_remote_end', $posted_item);
1315 if ($posted_item['gravity'] === self::GRAVITY_PARENT) {
1316 self::addShadow($post_user_id);
1318 self::addShadowPost($post_user_id);
1321 self::updateContact($posted_item);
1323 Post\UserNotification::setNotification($posted_item['uri-id'], $posted_item['uid']);
1325 // Distribute items to users who subscribed to their tags
1326 self::distributeByTags($posted_item);
1328 // Automatically reshare the item if the "remote_self" option is selected
1329 self::autoReshare($posted_item);
1331 $transmit = $notify || ($posted_item['visible'] && ($parent_origin || $posted_item['origin']));
1334 // Don't relay participation messages
1335 if (($posted_item['verb'] == Activity::FOLLOW) &&
1336 (!$posted_item['origin'] || ($posted_item['author-id'] != Contact::getPublicIdByUserId($uid)))) {
1337 Logger::info('Participation messages will not be relayed', ['item' => $posted_item['id'], 'uri' => $posted_item['uri'], 'verb' => $posted_item['verb']]);
1342 if (!empty($source) && ($transmit || DI::config()->get('debug', 'store_source'))) {
1343 Post\Activity::insert($item['uri-id'], $source);
1347 Worker::add(['priority' => $priority, 'dont_fork' => true], 'Notifier', $notify_type, (int)$posted_item['uri-id'], (int)$posted_item['uid']);
1350 // Fill the cache with the rendered content.
1351 if (in_array($posted_item['gravity'], [self::GRAVITY_PARENT, self::GRAVITY_COMMENT]) && ($posted_item['uid'] == 0)) {
1352 self::updateDisplayCache($posted_item['uri-id']);
1355 return $post_user_id;
1359 * Fetch the post reason for a given item array
1361 * @param array $item
1365 public static function getPostReason(array $item): int
1367 $actor = ($item['gravity'] == self::GRAVITY_PARENT) ? $item['owner-id'] : $item['author-id'];
1368 if (empty($item['origin']) && ($item['uid'] != 0) && Contact::isSharing($actor, $item['uid'])) {
1369 return self::PR_FOLLOWER;
1372 if (!empty($item['origin']) && empty($item['post-reason'])) {
1373 return self::PR_LOCAL;
1376 return $item['post-reason'] ?? self::PR_NONE;
1380 * Update the display cache
1382 * @param integer $uri_id
1385 public static function updateDisplayCache(int $uri_id)
1387 $item = Post::selectFirst(self::DISPLAY_FIELDLIST, ['uri-id' => $uri_id]);
1388 self::prepareBody($item, false, false, true);
1392 * Change the owner of a parent item if it had been shared by a forum
1394 * (public) forum posts in the new format consist of the regular post by the author
1395 * followed by an announce message sent from the forum account.
1396 * Changing the owner helps in grouping forum posts.
1398 * @param array $item
1401 private static function setOwnerforResharedItem(array $item)
1403 $parent = Post::selectFirst(['id', 'causer-id', 'owner-id', 'author-id', 'author-link', 'origin', 'post-reason'],
1404 ['uri-id' => $item['thr-parent-id'], 'uid' => $item['uid']]);
1405 if (!DBA::isResult($parent)) {
1406 Logger::error('Parent not found', ['uri-id' => $item['thr-parent-id'], 'uid' => $item['uid']]);
1410 $author = Contact::selectFirst(['url', 'contact-type', 'network'], ['id' => $item['author-id']]);
1411 if (!DBA::isResult($author)) {
1412 Logger::error('Author not found', ['id' => $item['author-id']]);
1416 $self_contact = Contact::selectFirst(['id'], ['uid' => $item['uid'], 'self' => true]);
1417 $self = !empty($self_contact) ? $self_contact['id'] : 0;
1419 $cid = Contact::getIdForURL($author['url'], $item['uid']);
1420 if (empty($cid) || (!Contact::isSharing($cid, $item['uid']) && ($cid != $self))) {
1421 Logger::info('The resharer is not a following contact: quit', ['resharer' => $author['url'], 'uid' => $item['uid'], 'cid' => $cid]);
1425 if ($author['contact-type'] != Contact::TYPE_COMMUNITY) {
1426 if ($parent['post-reason'] == self::PR_ANNOUNCEMENT) {
1427 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']]);
1431 if (Contact::isSharing($parent['owner-id'], $item['uid'])) {
1432 Logger::info('The resharer is no forum: quit', ['resharer' => $item['author-id'], 'owner' => $parent['owner-id'], 'author' => $parent['author-id'], 'uid' => $item['uid']]);
1437 self::update(['post-reason' => self::PR_ANNOUNCEMENT, 'causer-id' => $item['author-id']], ['id' => $parent['id']]);
1438 Logger::info('Set announcement post-reason', ['uri-id' => $item['uri-id'], 'thr-parent-id' => $item['thr-parent-id'], 'uid' => $item['uid']]);
1442 * Distribute the given item to users who subscribed to their tags
1444 * @param array $item Processed item
1446 private static function distributeByTags(array $item)
1448 if (($item['uid'] != 0) || ($item['gravity'] != self::GRAVITY_PARENT) || !in_array($item['network'], Protocol::FEDERATED)) {
1452 $uids = Tag::getUIDListByURIId($item['uri-id']);
1453 foreach ($uids as $uid) {
1454 $stored = self::storeForUserByUriId($item['uri-id'], $uid, ['post-reason' => self::PR_TAG]);
1455 Logger::info('Stored item for users', ['uri-id' => $item['uri-id'], 'uid' => $uid, 'stored' => $stored]);
1460 * Distributes public items to the receivers
1462 * @param integer $itemid Item ID that should be added
1463 * @param string $signed_text Original text (for Diaspora signatures), JSON encoded.
1464 * @throws \Exception
1466 public static function distribute(int $itemid, string $signed_text = '')
1468 $condition = ["`id` IN (SELECT `parent` FROM `post-user-view` WHERE `id` = ?)", $itemid];
1469 $parent = Post::selectFirst(['owner-id'], $condition);
1470 if (!DBA::isResult($parent)) {
1471 Logger::warning('Item not found', ['condition' => $condition]);
1475 // Only distribute public items from native networks
1476 $condition = ['id' => $itemid, 'uid' => 0,
1477 'network' => array_merge(Protocol::FEDERATED ,['']),
1478 'visible' => true, 'deleted' => false, 'private' => [self::PUBLIC, self::UNLISTED]];
1479 $item = Post::selectFirst(array_merge(self::ITEM_FIELDLIST, ['protocol']), $condition);
1480 if (!DBA::isResult($item)) {
1481 Logger::warning('Item not found', ['condition' => $condition]);
1485 $origin = $item['origin'];
1489 /// @todo add a field "pcid" in the contact table that referrs to the public contact id.
1490 $owner = DBA::selectFirst('contact', ['url', 'nurl', 'alias'], ['id' => $parent['owner-id']]);
1491 if (!DBA::isResult($owner)) {
1495 $condition = ['nurl' => $owner['nurl'], 'rel' => [Contact::SHARING, Contact::FRIEND]];
1496 $contacts = DBA::select('contact', ['uid'], $condition);
1497 while ($contact = DBA::fetch($contacts)) {
1498 if ($contact['uid'] == 0) {
1502 $users[$contact['uid']] = $contact['uid'];
1504 DBA::close($contacts);
1506 $condition = ['alias' => $owner['url'], 'rel' => [Contact::SHARING, Contact::FRIEND]];
1507 $contacts = DBA::select('contact', ['uid'], $condition);
1508 while ($contact = DBA::fetch($contacts)) {
1509 if ($contact['uid'] == 0) {
1513 $users[$contact['uid']] = $contact['uid'];
1515 DBA::close($contacts);
1517 if (!empty($owner['alias'])) {
1518 $condition = ['nurl' => Strings::normaliseLink($owner['alias']), 'rel' => [Contact::SHARING, Contact::FRIEND]];
1519 $contacts = DBA::select('contact', ['uid'], $condition);
1520 while ($contact = DBA::fetch($contacts)) {
1521 if ($contact['uid'] == 0) {
1525 $users[$contact['uid']] = $contact['uid'];
1527 DBA::close($contacts);
1532 if ($item['uri-id'] != $item['parent-uri-id']) {
1533 $parents = Post::select(['uid', 'origin'], ["`uri-id` = ? AND `uid` != 0", $item['parent-uri-id']]);
1534 while ($parent = Post::fetch($parents)) {
1535 $users[$parent['uid']] = $parent['uid'];
1536 if ($parent['origin'] && !$origin) {
1537 $origin_uid = $parent['uid'];
1540 DBA::close($parents);
1543 foreach ($users as $uid) {
1544 if ($origin_uid == $uid) {
1545 $item['diaspora_signed_text'] = $signed_text;
1547 $item['post-reason'] = self::PR_DISTRIBUTE;
1548 self::storeForUser($item, $uid);
1553 * Store a public item defined by their URI-ID for the given users
1555 * @param integer $uri_id URI-ID of the given item
1556 * @param integer $uid The user that will receive the item entry
1557 * @param array $fields Additional fields to be stored
1558 * @param integer $source_uid User id of the source post
1559 * @return integer stored item id
1561 public static function storeForUserByUriId(int $uri_id, int $uid, array $fields = [], int $source_uid = 0): int
1563 if ($uid == $source_uid) {
1564 Logger::warning('target UID must not be be equal to the source UID', ['uri-id' => $uri_id, 'uid' => $uid]);
1568 $item = Post::selectFirst(array_merge(self::ITEM_FIELDLIST, ['protocol']), ['uri-id' => $uri_id, 'uid' => $source_uid]);
1569 if (!DBA::isResult($item)) {
1570 Logger::warning('Item could not be fetched', ['uri-id' => $uri_id, 'uid' => $source_uid]);
1574 if (($uid != 0) && ($item['gravity'] == self::GRAVITY_PARENT)) {
1575 $owner = User::getOwnerDataById($uid);
1576 if (($owner['contact-type'] == User::ACCOUNT_TYPE_COMMUNITY) && !Tag::isMentioned($uri_id, $owner['url'])) {
1577 Logger::info('Target user is a forum but is not mentioned here, thread will not be stored', ['uid' => $uid, 'uri-id' => $uri_id]);
1582 if (($source_uid == 0) && (($item['private'] == self::PRIVATE) || !in_array($item['network'], Protocol::FEDERATED))) {
1583 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']]);
1587 $item['post-reason'] = self::PR_STORED;
1589 $item = array_merge($item, $fields);
1591 if (($uid != 0) && Contact::isSharing(($item['gravity'] == Item::GRAVITY_PARENT) ? $item['owner-id'] : $item['author-id'], $uid)) {
1592 $item['post-reason'] = self::PR_FOLLOWER;
1595 $is_reshare = ($item['gravity'] == self::GRAVITY_ACTIVITY) && ($item['verb'] == Activity::ANNOUNCE);
1597 if (($uid != 0) && (($item['gravity'] == self::GRAVITY_PARENT) || $is_reshare) &&
1598 DI::pConfig()->get($uid, 'system', 'accept_only_sharer') == self::COMPLETION_NONE &&
1599 !in_array($item['post-reason'], [self::PR_FOLLOWER, self::PR_TAG, self::PR_TO, self::PR_CC, self::PR_ACTIVITY])) {
1600 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']]);
1604 $causer = $item['causer-id'] ?: $item['author-id'];
1606 if (($uri_id != $item['parent-uri-id']) && ($item['gravity'] == self::GRAVITY_COMMENT) && !Post::exists(['uri-id' => $item['parent-uri-id'], 'uid' => $uid])) {
1607 if (!self::fetchParent($item['parent-uri-id'], $uid, $causer)) {
1608 Logger::info('Parent post had not been added', ['uri-id' => $item['parent-uri-id'], 'uid' => $uid, 'causer' => $causer]);
1611 Logger::info('Fetched parent post', ['uri-id' => $item['parent-uri-id'], 'uid' => $uid, 'causer' => $causer]);
1612 } elseif (($uri_id != $item['thr-parent-id']) && $is_reshare && !Post::exists(['uri-id' => $item['thr-parent-id'], 'uid' => $uid])) {
1613 if (!self::fetchParent($item['thr-parent-id'], $uid, $causer)) {
1614 Logger::info('Thread parent had not been added', ['uri-id' => $item['thr-parent-id'], 'uid' => $uid, 'causer' => $causer]);
1617 Logger::info('Fetched thread parent', ['uri-id' => $item['thr-parent-id'], 'uid' => $uid, 'causer' => $causer]);
1620 $stored = self::storeForUser($item, $uid);
1621 Logger::info('Item stored for user', ['uri-id' => $item['uri-id'], 'uid' => $uid, 'causer' => $causer, 'source-uid' => $source_uid, 'stored' => $stored]);
1626 * Fetch the parent with the given uri-id
1628 * @param integer $uri_id
1629 * @param integer $uid
1630 * @param integer $causer
1634 private static function fetchParent(int $uri_id, int $uid, int $causer): int
1636 // Fetch the origin user for the post
1637 $origin_uid = self::GetOriginUidForUriId($uri_id, $uid);
1638 if (is_null($origin_uid)) {
1639 Logger::info('Origin item was not found', ['uid' => $uid, 'uri-id' => $uri_id]);
1643 return self::storeForUserByUriId($uri_id, $uid, ['causer-id' => $causer, 'post-reason' => self::PR_FETCHED], $origin_uid);
1647 * Returns the origin uid of a post if the given user is allowed to see it.
1653 private static function GetOriginUidForUriId(int $uriid, int $uid)
1655 if (Post::exists(['uri-id' => $uriid, 'uid' => $uid])) {
1659 $post = Post::selectFirst(['uid', 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid', 'private'], ['uri-id' => $uriid, 'origin' => true]);
1660 if (!empty($post)) {
1661 if (in_array($post['private'], [Item::PUBLIC, Item::UNLISTED])) {
1662 return $post['uid'];
1665 $pcid = Contact::getPublicIdByUserId($uid);
1670 foreach (Item::enumeratePermissions($post, true) as $receiver) {
1671 if ($receiver == $pcid) {
1672 return $post['uid'];
1679 if (Post::exists(['uri-id' => $uriid, 'uid' => 0])) {
1683 // When the post belongs to a a forum then all forum users are allowed to access it
1684 foreach (Tag::getByURIId($uriid, [Tag::MENTION, Tag::EXCLUSIVE_MENTION]) as $tag) {
1685 if (DBA::exists('contact', ['uid' => $uid, 'nurl' => Strings::normaliseLink($tag['url']), 'contact-type' => Contact::TYPE_COMMUNITY])) {
1686 $target_uid = User::getIdForURL($tag['url']);
1687 if (!empty($target_uid)) {
1697 * Store a public item array for the given users
1699 * @param array $item The item entry that will be stored
1700 * @param integer $uid The user that will receive the item entry
1701 * @return integer stored item id
1702 * @throws \Exception
1704 private static function storeForUser(array $item, int $uid): int
1706 $post = Post::selectFirst(['id'], ['uri-id' => $item['uri-id'], 'uid' => $uid]);
1707 if (!empty($post['id'])) {
1708 if (!empty($item['event-id'])) {
1709 $event_post = Post::selectFirst(['event-id'], ['uri-id' => $item['uri-id'], 'uid' => $uid]);
1710 if (!empty($event_post['event-id'])) {
1711 $event = DBA::selectFirst('event', ['edited', 'start', 'finish', 'summary', 'desc', 'location', 'nofinish', 'adjust'], ['id' => $item['event-id']]);
1712 if (!empty($event)) {
1713 // We aren't using "Event::store" here, since we don't want to trigger any further action
1714 $ret = DBA::update('event', $event, ['id' => $event_post['event-id']]);
1715 Logger::info('Event updated', ['uid' => $uid, 'source-event' => $item['event-id'], 'target-event' => $event_post['event-id'], 'ret' => $ret]);
1719 Logger::info('Item already exists', ['uri-id' => $item['uri-id'], 'uid' => $uid, 'id' => $post['id']]);
1723 // Data from the "post-user" table
1725 unset($item['mention']);
1726 unset($item['starred']);
1727 unset($item['unseen']);
1728 unset($item['psid']);
1729 unset($item['pinned']);
1730 unset($item['ignored']);
1731 unset($item['pubmail']);
1732 unset($item['event-id']);
1733 unset($item['hidden']);
1734 unset($item['notification-type']);
1736 // Data from the "post-delivery-data" table
1737 unset($item['postopts']);
1738 unset($item['inform']);
1740 $item['uid'] = $uid;
1741 $item['origin'] = 0;
1744 $item['contact-id'] = self::contactId($item);
1747 if ($item['gravity'] == self::GRAVITY_PARENT) {
1748 $contact = DBA::selectFirst('contact', [], ['id' => $item['contact-id'], 'self' => false]);
1749 if (DBA::isResult($contact)) {
1750 $notify = self::isRemoteSelf($contact, $item);
1754 $distributed = self::insert($item, $notify);
1756 if (!$distributed) {
1757 Logger::info("Distributed item wasn't stored", ['uri-id' => $item['uri-id'], 'user' => $uid]);
1759 Logger::info('Distributed item was stored', ['uri-id' => $item['uri-id'], 'user' => $uid, 'stored' => $distributed]);
1761 return $distributed;
1765 * Add a shadow entry for a given item id that is a thread starter
1767 * We store every public item entry additionally with the user id "0".
1768 * This is used for the community page and for the search.
1769 * It is planned that in the future we will store public item entries only once.
1771 * @param integer $itemid Item ID that should be added
1772 * @throws \Exception
1774 private static function addShadow(int $itemid)
1776 $fields = ['uid', 'private', 'visible', 'deleted', 'network', 'uri-id'];
1777 $condition = ['id' => $itemid, 'gravity' => self::GRAVITY_PARENT];
1778 $item = Post::selectFirst($fields, $condition);
1780 if (!DBA::isResult($item)) {
1784 // is it already a copy?
1785 if (($itemid == 0) || ($item['uid'] == 0)) {
1789 // Is it a visible public post?
1790 if (!$item["visible"] || $item["deleted"] || ($item["private"] == self::PRIVATE)) {
1794 // is it an entry from a connector? Only add an entry for natively connected networks
1795 if (!in_array($item["network"], array_merge(Protocol::FEDERATED ,['']))) {
1799 if (Post::exists(['uri-id' => $item['uri-id'], 'uid' => 0])) {
1803 $item = Post::selectFirst(array_merge(self::ITEM_FIELDLIST, ['protocol']), ['id' => $itemid]);
1805 if (DBA::isResult($item)) {
1806 // Preparing public shadow (removing user specific data)
1809 unset($item['parent']);
1810 unset($item['wall']);
1811 unset($item['mention']);
1812 unset($item['origin']);
1813 unset($item['starred']);
1814 unset($item['postopts']);
1815 unset($item['inform']);
1816 unset($item['post-reason']);
1817 if ($item['uri-id'] == $item['parent-uri-id']) {
1818 $item['contact-id'] = $item['owner-id'];
1820 $item['contact-id'] = $item['author-id'];
1823 $public_shadow = self::insert($item);
1825 Logger::info('Stored public shadow', ['thread' => $itemid, 'id' => $public_shadow]);
1830 * Add a shadow entry for a given item id that is a comment
1832 * This function does the same like the function above - but for comments
1834 * @param integer $itemid Item ID that should be added
1835 * @throws \Exception
1837 private static function addShadowPost(int $itemid)
1839 $item = Post::selectFirst(array_merge(self::ITEM_FIELDLIST, ['protocol']), ['id' => $itemid]);
1840 if (!DBA::isResult($item)) {
1844 // Is it a toplevel post?
1845 if ($item['gravity'] == self::GRAVITY_PARENT) {
1846 self::addShadow($itemid);
1850 // Is this a shadow entry?
1851 if ($item['uid'] == 0) {
1855 // Is there a shadow parent?
1856 if (!Post::exists(['uri-id' => $item['parent-uri-id'], 'uid' => 0])) {
1860 // Is there already a shadow entry?
1861 if (Post::exists(['uri-id' => $item['uri-id'], 'uid' => 0])) {
1865 // Save "origin" and "parent" state
1866 $origin = $item['origin'];
1867 $parent = $item['parent'];
1869 // Preparing public shadow (removing user specific data)
1872 unset($item['parent']);
1873 unset($item['wall']);
1874 unset($item['mention']);
1875 unset($item['origin']);
1876 unset($item['starred']);
1877 unset($item['postopts']);
1878 unset($item['inform']);
1879 unset($item['post-reason']);
1880 $item['contact-id'] = Contact::getIdForURL($item['author-link']);
1882 $public_shadow = self::insert($item);
1884 Logger::info('Stored public shadow', ['uri-id' => $item['uri-id'], 'id' => $public_shadow]);
1886 // If this was a comment to a Diaspora post we don't get our comment back.
1887 // This means that we have to distribute the comment by ourselves.
1888 if ($origin && Post::exists(['id' => $parent, 'network' => Protocol::DIASPORA])) {
1889 self::distribute($public_shadow);
1894 * Adds a language specification in a "language" element of given $arr.
1895 * Expects "body" element to exist in $arr.
1897 * @param array $item
1898 * @return string detected language
1899 * @throws \Text_LanguageDetect_Exception
1901 private static function getLanguage(array $item): string
1903 if (!empty($item['language'])) {
1904 return $item['language'];
1907 if (!in_array($item['gravity'], [self::GRAVITY_PARENT, self::GRAVITY_COMMENT]) || empty($item['body'])) {
1911 $languages = self::getLanguageArray(trim($item['title'] . "\n" . $item['body']), 3);
1912 if (empty($languages)) {
1916 return json_encode($languages);
1920 * Get a language array from a given text
1922 * @param string $body
1923 * @param integer $count
1926 public static function getLanguageArray(string $body, int $count): array
1928 // Convert attachments to links
1929 $naked_body = BBCode::removeAttachment($body);
1930 if (empty($naked_body)) {
1934 // Remove links and pictures
1935 $naked_body = BBCode::removeLinks($naked_body);
1937 // Convert the title and the body to plain text
1938 $naked_body = BBCode::toPlaintext($naked_body);
1940 // Remove possibly remaining links
1941 $naked_body = preg_replace(Strings::autoLinkRegEx(), '', $naked_body);
1943 if (empty($naked_body)) {
1947 $naked_body = self::getDominantLanguage($naked_body);
1949 $availableLanguages = DI::l10n()->getAvailableLanguages();
1950 // See https://github.com/friendica/friendica/issues/10511
1951 // Persian is manually added to language detection until a persian translation is provided for the interface, at
1952 // which point it will be automatically available through `getAvailableLanguages()` and this should be removed.
1953 $availableLanguages['fa'] = 'fa';
1955 $ld = new Language(array_keys($availableLanguages));
1956 return $ld->detect($naked_body)->limit(0, $count)->close() ?: [];
1960 * Check if latin or non latin are dominant in the body and only return the dominant one
1962 * @param string $body
1965 private static function getDominantLanguage(string $body): string
1969 for ($i = 0; $i < mb_strlen($body); $i++) {
1970 $character = mb_substr($body, $i, 1);
1971 $ord = mb_ord($character);
1973 // We add the most common characters to both strings.
1974 if (($ord <= 64) || ($ord >= 91 && $ord <= 96) || ($ord >= 123 && $ord <= 191) || in_array($ord, [215, 247]) || ($ord >= 697 && $ord <= 735) || ($ord > 65535)) {
1975 $latin .= $character;
1976 $non_latin .= $character;
1977 } elseif ($ord < 768) {
1978 $latin .= $character;
1980 $non_latin .= $character;
1983 return (mb_strlen($latin) > mb_strlen($non_latin)) ? $latin : $non_latin;
1986 public static function getLanguageMessage(array $item): string
1988 $iso639 = new \Matriphe\ISO639\ISO639;
1990 $used_languages = '';
1991 foreach (json_decode($item['language'], true) as $language => $reliability) {
1992 $used_languages .= $iso639->languageByCode1($language) . ' (' . $language . "): " . number_format($reliability, 5) . '\n';
1994 $used_languages = DI::l10n()->t('Detected languages in this post:\n%s', $used_languages);
1995 return $used_languages;
1999 * Creates an unique guid out of a given uri.
2000 * This function is used for messages outside the fediverse (Connector posts, feeds, Mails, ...)
2001 * Posts that are created on this system are using System::createUUID.
2002 * Received ActivityPub posts are using Processor::getGUIDByURL.
2004 * @param string $uri uri of an item entry
2005 * @param string|null $host hostname for the GUID prefix
2006 * @return string Unique guid
2007 * @throws \Exception
2009 public static function guidFromUri(string $uri, string $host = null): string
2011 // Our regular guid routine is using this kind of prefix as well
2012 // We have to avoid that different routines could accidentally create the same value
2013 $parsed = parse_url($uri);
2015 // Remove the scheme to make sure that "https" and "http" doesn't make a difference
2016 unset($parsed['scheme']);
2018 $hostPart = $host ?? $parsed['host'] ?? '';
2020 Logger::warning('Empty host GUID part', ['uri' => $uri, 'host' => $host, 'parsed' => $parsed, 'callstack' => System::callstack(10)]);
2023 // Glue it together to be able to make a hash from it
2024 $host_id = implode('/', $parsed);
2026 // Use a mixture of several hashes to provide some GUID like experience
2027 return hash('crc32', $hostPart) . '-' . hash('joaat', $host_id) . '-' . hash('fnv164', $host_id);
2031 * generate an unique URI
2033 * @param string $guid An existing GUID (Otherwise it will be generated)
2036 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2038 public static function newURI(string $guid = ''): string
2041 $guid = System::createUUID();
2044 return DI::baseUrl()->get() . '/objects/' . $guid;
2048 * Set "success_update" and "last-item" to the date of the last time we heard from this contact
2050 * This can be used to filter for inactive contacts.
2051 * Only do this for public postings to avoid privacy problems, since poco data is public.
2052 * Don't set this value if it isn't from the owner (could be an author that we don't know)
2054 * @param array $arr Contains the just posted item record
2055 * @throws \Exception
2057 private static function updateContact(array $arr)
2059 // Unarchive the author
2060 $contact = DBA::selectFirst('contact', [], ['id' => $arr["author-id"]]);
2061 if (DBA::isResult($contact)) {
2062 Contact::unmarkForArchival($contact);
2065 // Unarchive the contact if it's not our own contact
2066 $contact = DBA::selectFirst('contact', [], ['id' => $arr["contact-id"], 'self' => false]);
2067 if (DBA::isResult($contact)) {
2068 Contact::unmarkForArchival($contact);
2071 /// @todo On private posts we could obfuscate the date
2072 $update = ($arr['private'] != self::PRIVATE) || in_array($arr['network'], Protocol::FEDERATED);
2074 // Is it a forum? Then we don't care about the rules from above
2075 if (!$update && in_array($arr["network"], [Protocol::ACTIVITYPUB, Protocol::DFRN]) && ($arr["parent-uri-id"] === $arr["uri-id"])) {
2076 if (DBA::exists('contact', ['id' => $arr['contact-id'], 'forum' => true])) {
2082 // The "self" contact id is used (for example in the connectors) when the contact is unknown
2083 // So we have to ensure to only update the last item when it had been our own post,
2084 // or it had been done by a "regular" contact.
2085 if (!empty($arr['wall'])) {
2086 $condition = ['id' => $arr['contact-id']];
2088 $condition = ['id' => $arr['contact-id'], 'self' => false];
2090 Contact::update(['failed' => false, 'local-data' => true, 'success_update' => $arr['received'], 'last-item' => $arr['received']], $condition);
2092 // Now do the same for the system wide contacts with uid=0
2093 if ($arr['private'] != self::PRIVATE) {
2094 Contact::update(['failed' => false, 'local-data' => true, 'success_update' => $arr['received'], 'last-item' => $arr['received']],
2095 ['id' => $arr['owner-id']]);
2097 if ($arr['owner-id'] != $arr['author-id']) {
2098 Contact::update(['failed' => false, 'local-data' => true, 'success_update' => $arr['received'], 'last-item' => $arr['received']],
2099 ['id' => $arr['author-id']]);
2104 public static function setHashtags(string $body): string
2106 $body = BBCode::performWithEscapedTags($body, ['noparse', 'pre', 'code', 'img'], function ($body) {
2107 $tags = BBCode::getTags($body);
2110 if (!count($tags)) {
2114 // This sorting is important when there are hashtags that are part of other hashtags
2115 // Otherwise there could be problems with hashtags like #test and #test2
2116 // Because of this we are sorting from the longest to the shortest tag.
2117 usort($tags, function ($a, $b) {
2118 return strlen($b) <=> strlen($a);
2121 $URLSearchString = "^\[\]";
2123 // All hashtags should point to the home server if "local_tags" is activated
2124 if (DI::config()->get('system', 'local_tags')) {
2125 $body = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
2126 "#[url=" . DI::baseUrl() . "/search?tag=$2]$2[/url]", $body);
2129 // mask hashtags inside of url, bookmarks and attachments to avoid urls in urls
2130 $body = preg_replace_callback("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
2132 return ("[url=" . str_replace("#", "#", $match[1]) . "]" . str_replace("#", "#", $match[2]) . "[/url]");
2135 $body = preg_replace_callback("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism",
2137 return ("[bookmark=" . str_replace("#", "#", $match[1]) . "]" . str_replace("#", "#", $match[2]) . "[/bookmark]");
2140 $body = preg_replace_callback("/\[attachment (.*?)\](.*?)\[\/attachment\]/ism",
2142 return ("[attachment " . str_replace("#", "#", $match[1]) . "]" . $match[2] . "[/attachment]");
2145 // Repair recursive urls
2146 $body = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
2149 foreach ($tags as $tag) {
2150 if ((strpos($tag, '#') !== 0) || strpos($tag, '[url=') || strlen($tag) < 2 || $tag[1] == '#') {
2154 $basetag = str_replace('_', ' ', substr($tag, 1));
2155 $newtag = '#[url=' . DI::baseUrl() . '/search?tag=' . $basetag . ']' . $basetag . '[/url]';
2157 $body = str_replace($tag, $newtag, $body);
2160 // Convert back the masked hashtags
2161 $body = str_replace("#", "#", $body);
2170 * look for mention tags and setup a second delivery chain for forum/community posts if appropriate
2173 * @param int $item_id
2174 * @return boolean true if item was deleted, else false
2175 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2176 * @throws \ImagickException
2178 private static function tagDeliver(int $uid, int $item_id): bool
2182 $owner = User::getOwnerDataById($uid);
2183 if (!DBA::isResult($owner)) {
2184 Logger::warning('User not found, quitting here.', ['uid' => $uid]);
2188 if ($owner['contact-type'] != User::ACCOUNT_TYPE_COMMUNITY) {
2189 Logger::debug('Owner is no community, quitting here.', ['uid' => $uid, 'id' => $item_id]);
2193 $item = Post::selectFirst(self::ITEM_FIELDLIST, ['id' => $item_id, 'gravity' => [self::GRAVITY_PARENT, self::GRAVITY_COMMENT], 'origin' => false]);
2194 if (!DBA::isResult($item)) {
2195 Logger::debug('Post is an activity or origin or not found at all, quitting here.', ['id' => $item_id]);
2199 if ($item['gravity'] == self::GRAVITY_PARENT) {
2200 if (Tag::isMentioned($item['uri-id'], $owner['url'])) {
2201 Logger::info('Mention found in tag.', ['uri' => $item['uri'], 'uid' => $uid, 'id' => $item_id, 'uri-id' => $item['uri-id'], 'guid' => $item['guid']]);
2203 Logger::info('Top-level post without mention is deleted.', ['uri' => $item['uri'], $uid, 'id' => $item_id, 'uri-id' => $item['uri-id'], 'guid' => $item['guid']]);
2204 Post\User::delete(['uri-id' => $item['uri-id'], 'uid' => $item['uid']]);
2208 $arr = ['item' => $item, 'user' => $owner];
2210 Hook::callAll('tagged', $arr);
2212 if (Tag::isMentioned($item['parent-uri-id'], $owner['url'])) {
2213 Logger::info('Mention found in parent tag.', ['uri' => $item['uri'], 'uid' => $uid, 'id' => $item_id, 'uri-id' => $item['uri-id'], 'guid' => $item['guid']]);
2215 Logger::debug('No mentions found in parent, quitting here.', ['id' => $item_id, 'uri-id' => $item['uri-id'], 'guid' => $item['guid']]);
2220 Logger::info('Community post will be distributed', ['uri' => $item['uri'], 'uid' => $uid, 'id' => $item_id, 'uri-id' => $item['uri-id'], 'guid' => $item['guid']]);
2222 if ($owner['page-flags'] == User::PAGE_FLAGS_PRVGROUP) {
2224 $allow_gid = '<' . Group::FOLLOWERS . '>';
2227 self::performActivity($item['id'], 'announce', $uid, $allow_cid, $allow_gid, $deny_cid, $deny_gid);
2229 self::performActivity($item['id'], 'announce', $uid);
2232 Logger::info('Community post had been distributed', ['uri' => $item['uri'], 'uid' => $uid, 'id' => $item_id, 'uri-id' => $item['uri-id'], 'guid' => $item['guid']]);
2237 * Automatically reshare the item if the "remote_self" option is selected
2239 * @param array $item
2242 private static function autoReshare(array $item)
2244 if ($item['gravity'] != self::GRAVITY_PARENT) {
2248 $cdata = Contact::getPublicAndUserContactID($item['author-id'], $item['uid']);
2249 if (empty($cdata['user']) || ($cdata['user'] != $item['contact-id'])) {
2253 $cdata = Contact::getPublicAndUserContactID($item['author-id'], $item['uid']);
2254 if (empty($cdata['user']) || ($cdata['user'] != $item['contact-id'])) {
2258 if (!DBA::exists('contact', ['id' => $cdata['user'], 'remote_self' => Contact::MIRROR_NATIVE_RESHARE])) {
2262 if (!in_array($item['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN])) {
2266 Logger::info('Automatically reshare item', ['uid' => $item['uid'], 'id' => $item['id'], 'guid' => $item['guid'], 'uri-id' => $item['uri-id']]);
2268 self::performActivity($item['id'], 'announce', $item['uid']);
2271 public static function isRemoteSelf(array $contact, array &$datarray): bool
2273 if ($contact['remote_self'] != Contact::MIRROR_OWN_POST) {
2277 // Prevent the forwarding of posts that are forwarded
2278 if (!empty($datarray['extid']) && ($datarray['extid'] == Protocol::DFRN)) {
2279 Logger::info('Already forwarded');
2283 // Prevent to forward already forwarded posts
2284 if ($datarray['app'] == DI::baseUrl()->getHostname()) {
2285 Logger::info('Already forwarded (second test)');
2289 // Only forward posts
2290 if ($datarray['verb'] != Activity::POST) {
2291 Logger::info('No post');
2295 if (($contact['network'] != Protocol::FEED) && ($datarray['private'] == self::PRIVATE)) {
2296 Logger::info('Not public');
2300 $datarray2 = $datarray;
2301 Logger::info('remote-self start', ['contact' => $contact['url'], 'remote_self'=> $contact['remote_self'], 'item' => $datarray]);
2303 $self = DBA::selectFirst('contact', ['id', 'name', 'url', 'thumb'],
2304 ['uid' => $contact['uid'], 'self' => true]);
2305 if (!DBA::isResult($self)) {
2306 Logger::error('Self contact not found', ['uid' => $contact['uid']]);
2310 $datarray['contact-id'] = $self['id'];
2312 $datarray['author-name'] = $datarray['owner-name'] = $self['name'];
2313 $datarray['author-link'] = $datarray['owner-link'] = $self['url'];
2314 $datarray['author-avatar'] = $datarray['owner-avatar'] = $self['thumb'];
2316 unset($datarray['edited']);
2318 unset($datarray['network']);
2319 unset($datarray['owner-id']);
2320 unset($datarray['author-id']);
2322 if ($contact['network'] != Protocol::FEED) {
2323 $old_uri_id = $datarray['uri-id'] ?? 0;
2324 $datarray['guid'] = System::createUUID();
2325 unset($datarray['plink']);
2326 $datarray['uri'] = self::newURI($datarray['guid']);
2327 $datarray['uri-id'] = ItemURI::getIdByURI($datarray['uri']);
2328 $datarray['extid'] = Protocol::DFRN;
2329 $urlpart = parse_url($datarray2['author-link']);
2330 $datarray['app'] = $urlpart['host'];
2331 if (!empty($old_uri_id)) {
2332 Post\Media::copy($old_uri_id, $datarray['uri-id']);
2335 unset($datarray['parent-uri']);
2336 unset($datarray['thr-parent']);
2338 // Store the original post
2339 $result = self::insert($datarray2);
2340 Logger::info('remote-self post original item', ['contact' => $contact['url'], 'result'=> $result, 'item' => $datarray2]);
2342 $datarray['private'] = self::PUBLIC;
2343 $datarray['app'] = 'Feed';
2347 return (bool)$result;
2354 * @param array $item
2357 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2358 * @throws \ImagickException
2360 public static function fixPrivatePhotos(string $s, int $uid, array $item = null, int $cid = 0): string
2362 if (DI::config()->get('system', 'disable_embedded')) {
2366 Logger::info('check for photos');
2367 $site = substr(DI::baseUrl(), strpos(DI::baseUrl(), '://'));
2372 $img_start = strpos($orig_body, '[img');
2373 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
2374 $img_len = ($img_start !== false ? strpos(substr($orig_body, $img_start + $img_st_close + 1), '[/img]') : false);
2376 while (($img_st_close !== false) && ($img_len !== false)) {
2377 $img_st_close++; // make it point to AFTER the closing bracket
2378 $image = substr($orig_body, $img_start + $img_st_close, $img_len);
2380 Logger::info('found photo', ['image' => $image]);
2382 if (stristr($image, $site . '/photo/')) {
2383 // Only embed locally hosted photos
2385 $i = basename($image);
2386 $i = str_replace(['.jpg', '.png', '.gif'], ['', '', ''], $i);
2387 $x = strpos($i, '-');
2390 $res = substr($i, $x + 1);
2391 $i = substr($i, 0, $x);
2392 $photo = Photo::getPhotoForUser($uid, $i, $res);
2393 if (DBA::isResult($photo)) {
2395 * Check to see if we should replace this photo link with an embedded image
2396 * 1. No need to do so if the photo is public
2397 * 2. If there's a contact-id provided, see if they're in the access list
2398 * for the photo. If so, embed it.
2399 * 3. Otherwise, if we have an item, see if the item permissions match the photo
2400 * permissions, regardless of order but first check to see if they're an exact
2401 * match to save some processing overhead.
2403 if (self::hasPermissions($photo)) {
2405 $recips = self::enumeratePermissions($photo);
2406 if (in_array($cid, $recips)) {
2410 if (self::samePermissions($uid, $item, $photo)) {
2416 $photo_img = Photo::getImageForPhoto($photo);
2417 // If a custom width and height were specified, apply before embedding
2418 if (preg_match("/\[img\=([0-9]*)x([0-9]*)\]/is", substr($orig_body, $img_start, $img_st_close), $match)) {
2419 Logger::info('scaling photo');
2421 $width = intval($match[1]);
2422 $height = intval($match[2]);
2424 $photo_img->scaleDown(max($width, $height));
2427 $data = $photo_img->asString();
2428 $type = $photo_img->getType();
2430 Logger::info('replacing photo');
2431 $image = 'data:' . $type . ';base64,' . base64_encode($data);
2432 Logger::debug('replaced', ['image' => $image]);
2438 $new_body = $new_body . substr($orig_body, 0, $img_start + $img_st_close) . $image . '[/img]';
2439 $orig_body = substr($orig_body, $img_start + $img_st_close + $img_len + strlen('[/img]'));
2440 if ($orig_body === false) {
2444 $img_start = strpos($orig_body, '[img');
2445 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
2446 $img_len = ($img_start !== false ? strpos(substr($orig_body, $img_start + $img_st_close + 1), '[/img]') : false);
2449 $new_body = $new_body . $orig_body;
2454 private static function hasPermissions(array $obj)
2456 return !empty($obj['allow_cid']) || !empty($obj['allow_gid']) ||
2457 !empty($obj['deny_cid']) || !empty($obj['deny_gid']);
2460 // @TODO $uid is unused parameter
2461 private static function samePermissions($uid, array $obj1, array $obj2): bool
2463 // first part is easy. Check that these are exactly the same.
2464 if (($obj1['allow_cid'] == $obj2['allow_cid'])
2465 && ($obj1['allow_gid'] == $obj2['allow_gid'])
2466 && ($obj1['deny_cid'] == $obj2['deny_cid'])
2467 && ($obj1['deny_gid'] == $obj2['deny_gid'])) {
2471 // This is harder. Parse all the permissions and compare the resulting set.
2472 $recipients1 = self::enumeratePermissions($obj1);
2473 $recipients2 = self::enumeratePermissions($obj2);
2477 /// @TODO Comparison of arrays, maybe use array_diff_assoc() here?
2478 return ($recipients1 == $recipients2);
2482 * Returns an array of contact-ids that are allowed to see this object
2484 * @param array $obj Item array with at least uid, allow_cid, allow_gid, deny_cid and deny_gid
2485 * @param bool $check_dead Prunes unavailable contacts from the result
2487 * @throws \Exception
2489 public static function enumeratePermissions(array $obj, bool $check_dead = false): array
2491 $aclFormater = DI::aclFormatter();
2493 $allow_people = $aclFormater->expand($obj['allow_cid']);
2494 $allow_groups = Group::expand($obj['uid'], $aclFormater->expand($obj['allow_gid']), $check_dead);
2495 $deny_people = $aclFormater->expand($obj['deny_cid']);
2496 $deny_groups = Group::expand($obj['uid'], $aclFormater->expand($obj['deny_gid']), $check_dead);
2497 $recipients = array_unique(array_merge($allow_people, $allow_groups));
2498 $deny = array_unique(array_merge($deny_people, $deny_groups));
2499 $recipients = array_diff($recipients, $deny);
2503 public static function expire(int $uid, int $days, string $network = "", bool $force = false)
2505 if (!$uid || ($days < 1)) {
2509 $condition = ["`uid` = ? AND NOT `deleted` AND `gravity` = ?",
2510 $uid, self::GRAVITY_PARENT];
2513 * $expire_network_only = save your own wall posts
2514 * and just expire conversations started by others
2516 $expire_network_only = DI::pConfig()->get($uid, 'expire', 'network_only', false);
2518 if ($expire_network_only) {
2519 $condition[0] .= " AND NOT `wall`";
2522 if ($network != "") {
2523 $condition[0] .= " AND `network` = ?";
2524 $condition[] = $network;
2527 $condition[0] .= " AND `received` < ?";
2528 $condition[] = DateTimeFormat::utc('now - ' . $days . ' day');
2530 $items = Post::select(['resource-id', 'starred', 'id', 'post-type', 'uid', 'uri-id'], $condition);
2532 if (!DBA::isResult($items)) {
2536 $expire_items = (bool)DI::pConfig()->get($uid, 'expire', 'items', true);
2538 // Forcing expiring of items - but not notes and marked items
2540 $expire_items = true;
2543 $expire_notes = (bool)DI::pConfig()->get($uid, 'expire', 'notes', true);
2544 $expire_starred = (bool)DI::pConfig()->get($uid, 'expire', 'starred', true);
2545 $expire_photos = (bool)DI::pConfig()->get($uid, 'expire', 'photos', false);
2549 $priority = DI::config()->get('system', 'expire-notify-priority');
2551 while ($item = Post::fetch($items)) {
2552 // don't expire filed items
2553 if (DBA::exists('post-category', ['uri-id' => $item['uri-id'], 'uid' => $item['uid'], 'type' => Post\Category::FILE])) {
2557 // Only expire posts, not photos and photo comments
2559 if (!$expire_photos && !empty($item['resource-id'])) {
2561 } elseif (!$expire_starred && intval($item['starred'])) {
2563 } elseif (!$expire_notes && ($item['post-type'] == self::PT_PERSONAL_NOTE)) {
2565 } elseif (!$expire_items && ($item['post-type'] != self::PT_PERSONAL_NOTE)) {
2569 self::markForDeletionById($item['id'], $priority);
2574 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]);
2577 public static function firstPostDate(int $uid, bool $wall = false)
2579 $user = User::getById($uid, ['register_date']);
2584 $condition = ["`uid` = ? AND `wall` = ? AND NOT `deleted` AND `visible` AND `received` >= ?",
2585 $uid, $wall, $user['register_date']];
2586 $params = ['order' => ['received' => false]];
2587 $thread = Post::selectFirstThread(['received'], $condition, $params);
2588 if (DBA::isResult($thread)) {
2589 $postdate = substr(DateTimeFormat::local($thread['received']), 0, 10);
2596 * add/remove activity to an item
2598 * Toggle activities as like,dislike,attend of an item
2600 * @param int $item_id
2601 * @param string $verb
2602 * Activity verb. One of
2603 * like, unlike, dislike, undislike, attendyes, unattendyes,
2604 * attendno, unattendno, attendmaybe, unattendmaybe,
2605 * announce, unannouce
2607 * @param string $allow_cid
2608 * @param string $allow_gid
2609 * @param string $deny_cid
2610 * @param string $deny_gid
2612 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2613 * @throws \ImagickException
2614 * @hook 'post_local_end'
2616 * 'post_id' => ID of posted item
2618 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
2624 Logger::notice('Start create activity', ['verb' => $verb, 'item' => $item_id, 'user' => $uid]);
2626 $item = Post::selectFirst(self::ITEM_FIELDLIST, ['id' => $item_id]);
2627 if (!DBA::isResult($item)) {
2628 Logger::warning('Post had not been fetched', ['id' => $item_id]);
2632 $uri_id = $item['uri-id'];
2634 if (!in_array($item['uid'], [0, $uid])) {
2638 if (!Post::exists(['uri-id' => $item['parent-uri-id'], 'uid' => $uid])) {
2639 $stored = self::storeForUserByUriId($item['parent-uri-id'], $uid, ['post-reason' => Item::PR_ACTIVITY]);
2640 if (($item['parent-uri-id'] == $item['uri-id']) && !empty($stored)) {
2641 $item = Post::selectFirst(self::ITEM_FIELDLIST, ['id' => $stored]);
2642 if (!DBA::isResult($item)) {
2643 Logger::info('Could not fetch just created item - should not happen', ['stored' => $stored, 'uid' => $uid, 'uri-id' => $uri_id]);
2649 // Retrieves the local post owner
2650 $owner = User::getOwnerDataById($uid);
2651 if (empty($owner)) {
2652 Logger::info('Empty owner for user', ['uid' => $uid]);
2656 // Retrieve the current logged in user's public contact
2657 $author_id = Contact::getPublicIdByUserId($uid);
2658 if (empty($author_id)) {
2659 Logger::info('Empty public contact');
2667 $activity = Activity::LIKE;
2671 $activity = Activity::DISLIKE;
2675 $activity = Activity::ATTEND;
2679 $activity = Activity::ATTENDNO;
2682 case 'unattendmaybe':
2683 $activity = Activity::ATTENDMAYBE;
2687 $activity = Activity::FOLLOW;
2691 $activity = Activity::ANNOUNCE;
2694 Logger::warning('unknown verb', ['verb' => $verb, 'item' => $item_id]);
2698 $mode = Strings::startsWith($verb, 'un') ? 'delete' : 'create';
2700 // Enable activity toggling instead of on/off
2701 $event_verb_flag = $activity === Activity::ATTEND || $activity === Activity::ATTENDNO || $activity === Activity::ATTENDMAYBE;
2703 // Look for an existing verb row
2704 // Event participation activities are mutually exclusive, only one of them can exist at all times.
2705 if ($event_verb_flag) {
2706 $verbs = [Activity::ATTEND, Activity::ATTENDNO, Activity::ATTENDMAYBE];
2708 // Translate to the index based activity index
2710 foreach ($verbs as $verb) {
2711 $vids[] = Verb::getID($verb);
2714 $vids = Verb::getID($activity);
2717 $condition = ['vid' => $vids, 'deleted' => false, 'gravity' => self::GRAVITY_ACTIVITY,
2718 'author-id' => $author_id, 'uid' => $uid, 'thr-parent-id' => $uri_id];
2719 $like_item = Post::selectFirst(['id', 'guid', 'verb'], $condition);
2721 if (DBA::isResult($like_item)) {
2723 * Truth table for existing activities
2725 * | Inputs || Outputs |
2726 * |----------------------------||-------------------|
2727 * | Mode | Event | Same verb || Delete? | Return? |
2728 * |--------|-------|-----------||---------|---------|
2729 * | create | Yes | Yes || No | Yes |
2730 * | create | Yes | No || Yes | No |
2731 * | create | No | Yes || No | Yes |
2732 * | create | No | No || N/A†|
2733 * | delete | Yes | Yes || Yes | N/A‡ |
2734 * | delete | Yes | No || No | N/A‡ |
2735 * | delete | No | Yes || Yes | N/A‡ |
2736 * | delete | No | No || N/A†|
2737 * |--------|-------|-----------||---------|---------|
2738 * | A | B | C || A xor C | !B or C |
2740 * †Can't happen: It's impossible to find an existing non-event activity without
2741 * the same verb because we are only looking for this single verb.
2743 * ‡ The "mode = delete" is returning early whether an existing activity was found or not.
2745 if ($mode == 'create' xor $like_item['verb'] == $activity) {
2746 self::markForDeletionById($like_item['id']);
2749 if (!$event_verb_flag || $like_item['verb'] == $activity) {
2754 // No need to go further if we aren't creating anything
2755 if ($mode == 'delete') {
2759 $objtype = $item['resource-id'] ? Activity\ObjectType::IMAGE : Activity\ObjectType::NOTE;
2762 'guid' => System::createUUID(),
2763 'uri' => self::newURI(),
2765 'contact-id' => $owner['id'],
2766 'wall' => $item['wall'],
2768 'network' => Protocol::DFRN,
2769 'protocol' => Conversation::PARCEL_DIRECT,
2770 'direction' => Conversation::PUSH,
2771 'gravity' => self::GRAVITY_ACTIVITY,
2772 'parent' => $item['id'],
2773 'thr-parent' => $item['uri'],
2774 'owner-id' => $author_id,
2775 'author-id' => $author_id,
2776 'body' => $activity,
2777 'verb' => $activity,
2778 'object-type' => $objtype,
2779 'allow_cid' => $allow_cid ?? $item['allow_cid'],
2780 'allow_gid' => $allow_gid ?? $item['allow_gid'],
2781 'deny_cid' => $deny_cid ?? $item['deny_cid'],
2782 'deny_gid' => $deny_gid ?? $item['deny_gid'],
2787 if (in_array($activity, [Activity::LIKE, Activity::DISLIKE])) {
2788 $signed = Diaspora::createLikeSignature($uid, $new_item);
2789 if (!empty($signed)) {
2790 $new_item['diaspora_signed_text'] = json_encode($signed);
2794 self::insert($new_item, true);
2796 // If the parent item isn't visible then set it to visible
2797 // @todo Check if this is still needed
2798 if (!$item['visible']) {
2799 self::update(['visible' => true], ['id' => $item['id']]);
2805 * Fetch the SQL condition for the given user id
2807 * @param integer $owner_id User ID for which the permissions should be fetched
2808 * @return array condition
2810 public static function getPermissionsConditionArrayByUserId(int $owner_id): array
2812 $local_user = DI::userSession()->getLocalUserId();
2813 $remote_user = DI::userSession()->getRemoteContactID($owner_id);
2815 // default permissions - anonymous user
2816 $condition = ["`private` != ?", self::PRIVATE];
2818 if ($local_user && ($local_user == $owner_id)) {
2819 // Profile owner - everything is visible
2821 } elseif ($remote_user) {
2822 // Authenticated visitor - fetch the matching permissionsets
2823 $permissionSets = DI::permissionSet()->selectByContactId($remote_user, $owner_id);
2825 $condition = ["(`private` != ? OR (`private` = ? AND `wall`
2826 AND `psid` IN (" . implode(', ', array_fill(0, count($set), '?')) . ")))",
2827 self::PRIVATE, self::PRIVATE];
2828 $condition = array_merge($condition, $permissionSets->column('id'));
2836 * Get a permission SQL string for the given user
2838 * @param int $owner_id
2839 * @param string $table
2842 public static function getPermissionsSQLByUserId(int $owner_id, string $table = ''): string
2844 $local_user = DI::userSession()->getLocalUserId();
2845 $remote_user = DI::userSession()->getRemoteContactID($owner_id);
2847 if (!empty($table)) {
2848 $table = DBA::quoteIdentifier($table) . '.';
2852 * Construct permissions
2854 * default permissions - anonymous user
2856 $sql = sprintf(" AND " . $table . "`private` != %d", self::PRIVATE);
2858 // Profile owner - everything is visible
2859 if ($local_user && ($local_user == $owner_id)) {
2861 } elseif ($remote_user) {
2863 * Authenticated visitor. Unless pre-verified,
2864 * check that the contact belongs to this $owner_id
2865 * and load the groups the visitor belongs to.
2866 * If pre-verified, the caller is expected to have already
2867 * done this and passed the groups into this function.
2869 $permissionSets = DI::permissionSet()->selectByContactId($remote_user, $owner_id);
2872 $sql_set = sprintf(" OR (" . $table . "`private` = %d AND " . $table . "`wall` AND " . $table . "`psid` IN (", self::PRIVATE) . implode(',', $permissionSets->column('id')) . "))";
2877 $sql = sprintf(" AND (" . $table . "`private` != %d", self::PRIVATE) . $sql_set . ")";
2884 * get translated item type
2886 * @param array $item
2887 * @param \Friendica\Core\L10n $l10n
2890 public static function postType(array $item, \Friendica\Core\L10n $l10n): string
2892 if (!empty($item['event-id'])) {
2893 return $l10n->t('event');
2894 } elseif (!empty($item['resource-id'])) {
2895 return $l10n->t('photo');
2896 } elseif ($item['gravity'] == self::GRAVITY_ACTIVITY) {
2897 return $l10n->t('activity');
2898 } elseif ($item['gravity'] == self::GRAVITY_COMMENT) {
2899 return $l10n->t('comment');
2902 return $l10n->t('post');
2906 * Sets the "rendered-html" field of the provided item
2908 * Body is preserved to avoid side-effects as we modify it just-in-time for spoilers and private image links
2910 * @param array $item
2912 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2913 * @todo Remove reference, simply return "rendered-html" and "rendered-hash"
2915 private static function putInCache(&$item)
2917 // Save original body to prevent addons to modify it
2918 $body = $item['body'];
2920 $rendered_hash = $item['rendered-hash'] ?? '';
2921 $rendered_html = $item['rendered-html'] ?? '';
2923 if ($rendered_hash == ''
2924 || $rendered_html == ''
2925 || $rendered_hash != hash('md5', BBCode::VERSION . '::' . $body)
2926 || DI::config()->get('system', 'ignore_cache')
2928 $item['rendered-html'] = BBCode::convertForUriId($item['uri-id'], $item['body']);
2929 $item['rendered-hash'] = hash('md5', BBCode::VERSION . '::' . $body);
2931 $hook_data = ['item' => $item, 'rendered-html' => $item['rendered-html'], 'rendered-hash' => $item['rendered-hash']];
2932 Hook::callAll('put_item_in_cache', $hook_data);
2933 $item['rendered-html'] = $hook_data['rendered-html'];
2934 $item['rendered-hash'] = $hook_data['rendered-hash'];
2937 // Update if the generated values differ from the existing ones
2938 if ((($rendered_hash != $item['rendered-hash']) || ($rendered_html != $item['rendered-html'])) && !empty($item['id'])) {
2941 'rendered-html' => $item['rendered-html'],
2942 'rendered-hash' => $item['rendered-hash']
2944 ['id' => $item['id']]
2949 $item['body'] = $body;
2953 * Given an item array, convert the body element from bbcode to html and add smilie icons.
2954 * If attach is true, also add icons for item attachments.
2956 * @param array $item Record from item table
2957 * @param boolean $attach If true, add icons for item attachments as well
2958 * @param boolean $is_preview Whether this is a preview
2959 * @param boolean $only_cache Whether only cached HTML should be updated
2960 * @return string item body html
2961 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2962 * @throws \ImagickException
2963 * @hook prepare_body_init item array before any work
2964 * @hook prepare_body_content_filter ('item'=>item array, 'filter_reasons'=>string array) before first bbcode to html
2965 * @hook prepare_body ('item'=>item array, 'html'=>body string, 'is_preview'=>boolean, 'filter_reasons'=>string array) after first bbcode to html
2966 * @hook prepare_body_final ('item'=>item array, 'html'=>body string) after attach icons and blockquote special case handling (spoiler, author)
2968 public static function prepareBody(array &$item, bool $attach = false, bool $is_preview = false, bool $only_cache = false): string
2971 Hook::callAll('prepare_body_init', $item);
2974 // In order to provide theme developers more possibilities, event items
2975 // are treated differently.
2976 if ($item['object-type'] === Activity\ObjectType::EVENT && isset($item['event-id'])) {
2977 $ev = Event::getItemHTML($item);
2981 $tags = Tag::populateFromItem($item);
2983 $item['tags'] = $tags['tags'];
2984 $item['hashtags'] = $tags['hashtags'];
2985 $item['mentions'] = $tags['mentions'];
2988 $item['body'] = preg_replace("#\s*\[attachment .*?].*?\[/attachment]\s*#ism", "\n", $item['body']);
2989 $item['body'] = Post\Media::removeFromEndOfBody($item['body'] ?? '');
2992 $body = $item['body'];
2994 $item['body'] = preg_replace("#\s*\[attachment .*?].*?\[/attachment]\s*#ism", "\n", $item['body']);
2997 $fields = ['uri-id', 'uri', 'body', 'title', 'author-name', 'author-link', 'author-avatar', 'guid', 'created', 'plink', 'network', 'has-media', 'quote-uri-id', 'post-type'];
3002 $shared = DI::contentItem()->getSharedPost($item, $fields);
3003 if (!empty($shared['post'])) {
3004 $shared_item = $shared['post'];
3005 $shared_item['body'] = Post\Media::removeFromEndOfBody($shared_item['body']);
3006 $quote_uri_id = $shared['post']['uri-id'];
3007 $shared_links[] = strtolower($shared['post']['uri']);
3008 $item['body'] = BBCode::removeSharedData($item['body']);
3009 } elseif (empty($shared_item['uri-id']) && empty($item['quote-uri-id']) && ($item['network'] != Protocol::DIASPORA)) {
3010 $media = Post\Media::getByURIId($item['uri-id'], [Post\Media::ACTIVITY]);
3011 if (!empty($media)) {
3012 $shared_item = Post::selectFirst($fields, ['plink' => $media[0]['url'], 'uid' => [$item['uid'], 0]]);
3014 if (empty($shared_item['uri-id'])) {
3015 $shared_item = Post::selectFirst($fields, ['uri' => $media[0]['url'], 'uid' => [$item['uid'], 0]]);
3016 $shared_links[] = strtolower($media[0]['url']);
3019 $quote_uri_id = $shared_item['uri-id'] ?? 0;
3023 if (!empty($quote_uri_id)) {
3024 $item['body'] .= "\n" . DI::contentItem()->createSharedBlockByArray($shared_item);
3027 if (!empty($shared_item['uri-id'])) {
3028 $shared_uri_id = $shared_item['uri-id'];
3029 $shared_links[] = strtolower($shared_item['plink']);
3030 $shared_attachments = Post\Media::splitAttachments($shared_uri_id, [], $shared_item['has-media']);
3031 $shared_links = array_merge($shared_links, array_column($shared_attachments['visual'], 'url'));
3032 $shared_links = array_merge($shared_links, array_column($shared_attachments['link'], 'url'));
3033 $shared_links = array_merge($shared_links, array_column($shared_attachments['additional'], 'url'));
3034 $item['body'] = self::replaceVisualAttachments($shared_attachments, $item['body']);
3037 $attachments = Post\Media::splitAttachments($item['uri-id'], $shared_links, $item['has-media'] ?? false);
3038 $item['body'] = self::replaceVisualAttachments($attachments, $item['body'] ?? '');
3040 self::putInCache($item);
3041 $item['body'] = $body;
3042 $s = $item["rendered-html"];
3048 // Compile eventual content filter reasons
3049 $filter_reasons = [];
3050 if (!$is_preview && DI::userSession()->getPublicContactId() != $item['author-id']) {
3051 if (Contact\User::isCollapsed($item['author-id'], $item['uid'])) {
3052 $filter_reasons[] = DI::l10n()->t('Content from %s is collapsed', $item['author-name']);
3055 if (!empty($item['content-warning']) && (!DI::userSession()->getLocalUserId() || !DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'system', 'disable_cw', false))) {
3056 $filter_reasons[] = DI::l10n()->t('Content warning: %s', $item['content-warning']);
3059 $item['attachments'] = $attachments;
3063 'filter_reasons' => $filter_reasons
3065 Hook::callAll('prepare_body_content_filter', $hook_data);
3066 $filter_reasons = $hook_data['filter_reasons'];
3073 'preview' => $is_preview,
3074 'filter_reasons' => $filter_reasons
3076 Hook::callAll('prepare_body', $hook_data);
3077 $s = $hook_data['html'];
3082 // Replace the blockquotes with quotes that are used in mails.
3083 $mailquote = '<blockquote type="cite" class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex;">';
3084 $s = str_replace(['<blockquote>', '<blockquote class="spoiler">', '<blockquote class="author">'], [$mailquote, $mailquote, $mailquote], $s);
3088 if (!empty($shared_attachments)) {
3089 $s = self::addVisualAttachments($shared_attachments, $shared_item, $s, true);
3090 $s = self::addLinkAttachment($shared_uri_id ?: $item['uri-id'], $shared_attachments, $body, $s, true, []);
3091 $s = self::addNonVisualAttachments($shared_attachments, $item, $s, true);
3092 $body = BBCode::removeSharedData($body);
3095 $s = self::addVisualAttachments($attachments, $item, $s, false);
3096 $s = self::addLinkAttachment($item['uri-id'], $attachments, $body, $s, false, $shared_links);
3097 $s = self::addNonVisualAttachments($attachments, $item, $s, false);
3098 $s = self::addQuestions($item, $s);
3101 if (strpos($s, '<div class="map">') !== false && !empty($item['coord'])) {
3102 $x = Map::byCoordinates(trim($item['coord']));
3104 $s = preg_replace('/\<div class\=\"map\"\>/', '$0' . $x, $s);
3108 // Replace friendica image url size with theme preference.
3109 if (!empty($a->getThemeInfoValue('item_image_size'))) {
3110 $ps = $a->getThemeInfoValue('item_image_size');
3111 $s = preg_replace('|(<img[^>]+src="[^"]+/photo/[0-9a-f]+)-[0-9]|', "$1-" . $ps, $s);
3114 $s = HTML::applyContentFilter($s, $filter_reasons);
3116 $hook_data = ['item' => $item, 'html' => $s];
3117 Hook::callAll('prepare_body_final', $hook_data);
3118 return $hook_data['html'];
3122 * @param array $images
3124 * @throws \Friendica\Network\HTTPException\ServiceUnavailableException
3126 private static function makeImageGrid(array $images): string
3128 // Image for first column (fc) and second column (sc)
3132 for ($i = 0; $i < count($images); $i++) {
3133 ($i % 2 == 0) ? ($images_fc[] = $images[$i]) : ($images_sc[] = $images[$i]);
3136 return Renderer::replaceMacros(Renderer::getMarkupTemplate('content/image_grid.tpl'), [
3146 * Check if the body contains a link
3148 * @param string $body
3149 * @param string $url
3153 public static function containsLink(string $body, string $url, int $type = 0): bool
3155 // Make sure that for example site parameters aren't used when testing if the link is contained in the body
3156 $urlparts = parse_url($url);
3157 if (empty($urlparts)) {
3161 unset($urlparts['query']);
3162 unset($urlparts['fragment']);
3165 $url = (string)Uri::fromParts($urlparts);
3166 } catch (\InvalidArgumentException $e) {
3167 DI::logger()->notice('Invalid URL', ['$url' => $url, '$urlparts' => $urlparts]);
3168 /* See https://github.com/friendica/friendica/issues/12113
3169 * Malformed URLs will result in a Fatal Error
3174 // Remove media links to only search in embedded content
3175 // @todo Check images for image link, audio for audio links, ...
3176 if (in_array($type, [Post\Media::AUDIO, Post\Media::VIDEO, Post\Media::IMAGE])) {
3177 $body = preg_replace("/\[url=[^\[\]]*\](.*)\[\/url\]/Usi", ' $1 ', $body);
3180 if (strpos($body, $url)) {
3184 foreach ([0, 1, 2] as $size) {
3185 if (preg_match('#/photo/.*-' . $size . '\.#ism', $url) &&
3186 strpos(preg_replace('#(/photo/.*)-[012]\.#ism', '$1-' . $size . '.', $body), $url)) {
3195 * Replace visual attachments in the body
3197 * @param array $attachments
3198 * @param string $body
3199 * @return string modified body
3201 private static function replaceVisualAttachments(array $attachments, string $body): string
3203 DI::profiler()->startRecording('rendering');
3205 foreach ($attachments['visual'] as $attachment) {
3206 if (!empty($attachment['preview'])) {
3207 $proxy = Post\Media::getPreviewUrlForId($attachment['id'], Proxy::SIZE_LARGE);
3208 $search = ['[img=' . $attachment['preview'] . ']', ']' . $attachment['preview'] . '[/img]'];
3209 $replace = ['[img=' . $proxy . ']', ']' . $proxy . '[/img]'];
3211 $body = str_replace($search, $replace, $body);
3212 } elseif ($attachment['filetype'] == 'image') {
3213 $proxy = Post\Media::getUrlForId($attachment['id']);
3214 $search = ['[img=' . $attachment['url'] . ']', ']' . $attachment['url'] . '[/img]'];
3215 $replace = ['[img=' . $proxy . ']', ']' . $proxy . '[/img]'];
3217 $body = str_replace($search, $replace, $body);
3220 DI::profiler()->stopRecording();
3225 * Add visual attachments to the content
3227 * @param array $attachments
3228 * @param array $item
3229 * @param string $content
3230 * @return string modified content
3232 private static function addVisualAttachments(array $attachments, array $item, string $content, bool $shared): string
3234 DI::profiler()->startRecording('rendering');
3239 // @todo In the future we should make a single for the template engine with all media in it. This allows more flexibilty.
3240 foreach ($attachments['visual'] as $attachment) {
3241 if (self::containsLink($item['body'], $attachment['preview'] ?? $attachment['url'], $attachment['type'])) {
3245 if ($attachment['filetype'] == 'image') {
3246 $preview_url = Post\Media::getPreviewUrlForId($attachment['id'], ($attachment['width'] > $attachment['height']) ? Proxy::SIZE_MEDIUM : Proxy::SIZE_LARGE);
3247 } elseif (!empty($attachment['preview'])) {
3248 $preview_url = Post\Media::getPreviewUrlForId($attachment['id'], Proxy::SIZE_LARGE);
3253 if ($preview_url && self::containsLink($item['body'], $preview_url)) {
3257 if (($attachment['filetype'] == 'video')) {
3258 /// @todo Move the template to /content as well
3259 $media = Renderer::replaceMacros(Renderer::getMarkupTemplate('video_top.tpl'), [
3261 'id' => $attachment['id'],
3262 'src' => $attachment['url'],
3263 'name' => $attachment['name'] ?: $attachment['url'],
3264 'preview' => $preview_url,
3265 'mime' => $attachment['mimetype'],
3268 if (($item['post-type'] ?? null) == Item::PT_VIDEO) {
3271 $trailing .= $media;
3273 } elseif ($attachment['filetype'] == 'audio') {
3274 $media = Renderer::replaceMacros(Renderer::getMarkupTemplate('content/audio.tpl'), [
3276 'id' => $attachment['id'],
3277 'src' => $attachment['url'],
3278 'name' => $attachment['name'] ?: $attachment['url'],
3279 'mime' => $attachment['mimetype'],
3282 if (($item['post-type'] ?? null) == Item::PT_AUDIO) {
3285 $trailing .= $media;
3287 } elseif ($attachment['filetype'] == 'image') {
3288 $src_url = Post\Media::getUrlForId($attachment['id']);
3289 if (self::containsLink($item['body'], $src_url)) {
3292 $images[] = ['src' => $src_url, 'preview' => $preview_url, 'attachment' => $attachment];
3297 if (count($images) > 1) {
3298 $media = self::makeImageGrid($images);
3299 } elseif (count($images) == 1) {
3300 $media = Renderer::replaceMacros(Renderer::getMarkupTemplate('content/image.tpl'), [
3301 '$image' => $images[0],
3305 // On Diaspora posts the attached pictures are leading
3306 if ($item['network'] == Protocol::DIASPORA) {
3309 $trailing .= $media;
3313 $content = str_replace(BBCode::TOP_ANCHOR, '<div class="body-attach">' . $leading . '</div>' . BBCode::TOP_ANCHOR, $content);
3314 $content = str_replace(BBCode::BOTTOM_ANCHOR, '<div class="body-attach">' . $trailing . '</div>' . BBCode::BOTTOM_ANCHOR, $content);
3316 if ($leading != '') {
3317 $content = '<div class="body-attach">' . $leading . '</div>' . $content;
3320 if ($trailing != '') {
3321 $content .= '<div class="body-attach">' . $trailing . '</div>';
3325 DI::profiler()->stopRecording();
3330 * Add link attachment to the content
3332 * @param array $attachments
3333 * @param string $body
3334 * @param string $content
3335 * @param bool $shared
3336 * @param array $ignore_links A list of URLs to ignore
3337 * @return string modified content
3339 private static function addLinkAttachment(int $uriid, array $attachments, string $body, string $content, bool $shared, array $ignore_links): string
3341 DI::profiler()->startRecording('rendering');
3342 // Don't show a preview when there is a visual attachment (audio or video)
3343 $types = array_column($attachments['visual'], 'type');
3344 $preview = !in_array(Post\Media::IMAGE, $types) && !in_array(Post\Media::VIDEO, $types);
3346 if (!empty($attachments['link'])) {
3347 foreach ($attachments['link'] as $link) {
3349 foreach ($ignore_links as $ignore_link) {
3350 if (Strings::compareLink($link['url'], $ignore_link)) {
3354 // @todo Judge between the links to use the one with most information
3355 if (!$found && (empty($attachment) || !empty($link['author-name']) ||
3356 (empty($attachment['name']) && !empty($link['name'])) ||
3357 (empty($attachment['description']) && !empty($link['description'])) ||
3358 (empty($attachment['preview']) && !empty($link['preview'])))) {
3359 $attachment = $link;
3364 if (!empty($attachment)) {
3367 'author_name' => $attachment['author-name'] ?? '',
3368 'author_url' => $attachment['author-url'] ?? '',
3369 'description' => $attachment['description'] ?? '',
3372 'provider_name' => $attachment['publisher-name'] ?? '',
3373 'provider_url' => $attachment['publisher-url'] ?? '',
3375 'title' => $attachment['name'] ?? '',
3377 'url' => $attachment['url']];
3379 if ($preview && !empty($attachment['preview'])) {
3380 if ($attachment['preview-width'] >= 500) {
3381 $data['image'] = Post\Media::getPreviewUrlForId($attachment['id'], Proxy::SIZE_MEDIUM);
3383 $data['preview'] = Post\Media::getPreviewUrlForId($attachment['id'], Proxy::SIZE_MEDIUM);
3387 if (!empty($data['description']) && !empty($content)) {
3388 similar_text($data['description'], $content, $percent);
3393 if (!empty($data['description']) && (($data['title'] == $data['description']) || ($percent > 95) || (strpos($content, $data['description']) !== false))) {
3394 $data['description'] = '';
3397 if (($data['author_name'] ?? '') == ($data['provider_name'] ?? '')) {
3398 $data['author_name'] = '';
3401 if (($data['author_url'] ?? '') == ($data['provider_url'] ?? '')) {
3402 $data['author_url'] = '';
3404 } elseif (preg_match("/.*(\[attachment.*?\].*?\[\/attachment\]).*/ism", $body, $match)) {
3405 $data = BBCode::getAttachmentData($match[1]);
3407 DI::profiler()->stopRecording();
3409 if (isset($data['url']) && !in_array(strtolower($data['url']), $ignore_links)) {
3410 if (!empty($data['description']) || !empty($data['image']) || !empty($data['preview'])) {
3411 $parts = parse_url($data['url']);
3412 if (!empty($parts['scheme']) && !empty($parts['host'])) {
3413 if (empty($data['provider_name'])) {
3414 $data['provider_name'] = $parts['host'];
3416 if (empty($data['provider_url']) || empty(parse_url($data['provider_url'], PHP_URL_SCHEME))) {
3417 $data['provider_url'] = $parts['scheme'] . '://' . $parts['host'];
3419 if (!empty($parts['port'])) {
3420 $data['provider_url'] .= ':' . $parts['port'];
3425 // @todo Use a template
3426 $preview_mode = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'system', 'preview_mode', BBCode::PREVIEW_LARGE);
3427 if ($preview_mode != BBCode::PREVIEW_NONE) {
3428 $rendered = BBCode::convertAttachment('', BBCode::INTERNAL, false, $data, $uriid, $preview_mode);
3432 } elseif (!self::containsLink($content, $data['url'], Post\Media::HTML)) {
3433 $rendered = Renderer::replaceMacros(Renderer::getMarkupTemplate('content/link.tpl'), [
3434 '$url' => $data['url'],
3435 '$title' => $data['title'],
3442 return str_replace(BBCode::BOTTOM_ANCHOR, BBCode::BOTTOM_ANCHOR . $rendered, $content);
3444 return $content . $rendered;
3451 * Add non visual attachments to the content
3453 * @param array $attachments
3454 * @param array $item
3455 * @param string $content
3456 * @return string modified content
3458 private static function addNonVisualAttachments(array $attachments, array $item, string $content): string
3460 DI::profiler()->startRecording('rendering');
3462 foreach ($attachments['additional'] as $attachment) {
3463 if (strpos($item['body'], $attachment['url'])) {
3467 $author = ['uid' => 0, 'id' => $item['author-id'],
3468 'network' => $item['author-network'], 'url' => $item['author-link']];
3469 $the_url = Contact::magicLinkByContact($author, $attachment['url']);
3471 $title = Strings::escapeHtml(trim(($attachment['description'] ?? '') ?: $attachment['url']));
3473 if (!empty($attachment['size'])) {
3474 $title .= ' ' . $attachment['size'] . ' ' . DI::l10n()->t('bytes');
3477 /// @todo Use a template
3478 $icon = '<div class="attachtype icon s22 type-' . $attachment['filetype'] . ' subtype-' . $attachment['subtype'] . '"></div>';
3479 $trailing .= '<a href="' . strip_tags($the_url) . '" title="' . $title . '" class="attachlink" target="_blank" rel="noopener noreferrer" >' . $icon . '</a>';
3482 if ($trailing != '') {
3483 $content .= '<div class="body-attach">' . $trailing . '</div>';
3486 DI::profiler()->stopRecording();
3490 private static function addQuestions(array $item, string $content): string
3492 DI::profiler()->startRecording('rendering');
3493 if (!empty($item['question-id'])) {
3495 'id' => $item['question-id'],
3496 'multiple' => $item['question-multiple'],
3497 'voters' => $item['question-voters'],
3498 'endtime' => $item['question-end-time']
3501 $options = Post\QuestionOption::getByURIId($item['uri-id']);
3502 foreach ($options as $key => $option) {
3503 if ($question['voters'] > 0) {
3504 $percent = $option['replies'] / $question['voters'] * 100;
3505 $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));
3507 $options[$key]['vote'] = DI::l10n()->tt('%2$s (%1$d vote)', '%2$s (%1$d votes)', $option['replies'], $option['name']);
3511 if (!empty($question['voters']) && !empty($question['endtime'])) {
3512 $summary = DI::l10n()->tt('%d voter. Poll end: %s', '%d voters. Poll end: %s', $question['voters'], Temporal::getRelativeDate($question['endtime']));
3513 } elseif (!empty($question['voters'])) {
3514 $summary = DI::l10n()->tt('%d voter.', '%d voters.', $question['voters']);
3515 } elseif (!empty($question['endtime'])) {
3516 $summary = DI::l10n()->t('Poll end: %s', Temporal::getRelativeDate($question['endtime']));
3521 $content .= Renderer::replaceMacros(Renderer::getMarkupTemplate('content/question.tpl'), [
3522 '$question' => $question,
3523 '$options' => $options,
3524 '$summary' => $summary,
3527 DI::profiler()->stopRecording();
3532 * get private link for item
3534 * @param array $item
3535 * @return boolean|array False if item has not plink, otherwise array('href'=>plink url, 'title'=>translated title)
3536 * @throws \Exception
3538 public static function getPlink(array $item)
3540 if (!empty($item['plink']) && Network::isValidHttpUrl($item['plink'])) {
3541 $plink = $item['plink'];
3542 } elseif (!empty($item['uri']) && Network::isValidHttpUrl($item['uri']) && !Network::isLocalLink($item['uri'])) {
3543 $plink = $item['uri'];
3546 if (DI::userSession()->getLocalUserId()) {
3548 'href' => "display/" . $item['guid'],
3549 'orig' => "display/" . $item['guid'],
3550 'title' => DI::l10n()->t('View on separate page'),
3551 'orig_title' => DI::l10n()->t('View on separate page'),
3554 if (!empty($plink) && ($item['private'] == self::PRIVATE)) {
3555 $author = ['uid' => 0, 'id' => $item['author-id'],
3556 'network' => $item['author-network'], 'url' => $item['author-link']];
3557 $plink = Contact::magicLinkByContact($author, $plink);
3560 if (!empty($plink)) {
3561 $ret['href'] = DI::baseUrl()->remove($plink);
3562 $ret['title'] = DI::l10n()->t('Link to source');
3564 } elseif (!empty($plink) && ($item['private'] != self::PRIVATE)) {
3568 'title' => DI::l10n()->t('Link to source'),
3569 'orig_title' => DI::l10n()->t('Link to source'),
3579 * Does the given uri-id belongs to a post that is sent as starting post to a forum?
3581 * @param int $uri_id
3583 * @return boolean "true" when it is a forum post
3585 public static function isForumPost(int $uri_id): bool
3587 foreach (Tag::getByURIId($uri_id, [Tag::EXCLUSIVE_MENTION]) as $tag) {
3588 if (DBA::exists('contact', ['uid' => 0, 'nurl' => Strings::normaliseLink($tag['url']), 'contact-type' => Contact::TYPE_COMMUNITY])) {
3596 * Search item id for given URI or plink
3598 * @param string $uri
3599 * @param integer $uid
3601 * @return integer item id
3603 public static function searchByLink(string $uri, int $uid = 0): int
3605 $ssl_uri = str_replace('http://', 'https://', $uri);
3606 $uris = [$uri, $ssl_uri, Strings::normaliseLink($uri)];
3608 $item = Post::selectFirst(['id'], ['uri' => $uris, 'uid' => $uid]);
3609 if (DBA::isResult($item)) {
3613 $item = Post::selectFirst(['id'], ['plink' => $uris, 'uid' => $uid]);
3614 if (DBA::isResult($item)) {
3622 * Return the URI for a link to the post
3624 * @param string $uri URI or link to post
3626 * @return string URI
3628 public static function getURIByLink(string $uri): string
3630 $ssl_uri = str_replace('http://', 'https://', $uri);
3631 $uris = [$uri, $ssl_uri, Strings::normaliseLink($uri)];
3633 $item = Post::selectFirst(['uri'], ['uri' => $uris]);
3634 if (DBA::isResult($item)) {
3635 return $item['uri'];
3638 $item = Post::selectFirst(['uri'], ['plink' => $uris]);
3639 if (DBA::isResult($item)) {
3640 return $item['uri'];
3647 * Fetches item for given URI or plink
3649 * @param string $uri
3650 * @param integer $uid
3652 * @return integer item id
3654 public static function fetchByLink(string $uri, int $uid = 0): int
3656 Logger::info('Trying to fetch link', ['uid' => $uid, 'uri' => $uri]);
3657 $item_id = self::searchByLink($uri, $uid);
3658 if (!empty($item_id)) {
3659 Logger::info('Link found', ['uid' => $uid, 'uri' => $uri, 'id' => $item_id]);
3669 Hook::callAll('item_by_link', $hookData);
3671 if (isset($hookData['item_id'])) {
3672 return is_numeric($hookData['item_id']) ? $hookData['item_id'] : 0;
3675 $fetched_uri = ActivityPub\Processor::fetchMissingActivity($uri);
3678 $item_id = self::searchByLink($fetched_uri, $uid);
3680 $item_id = Diaspora::fetchByURL($uri);
3683 if (!empty($item_id)) {
3684 Logger::info('Link fetched', ['uid' => $uid, 'uri' => $uri, 'id' => $item_id]);
3688 Logger::info('Link not found', ['uid' => $uid, 'uri' => $uri]);
3693 * Check a prospective item array against user-level permissions
3695 * @param array $item Expected keys: uri, gravity, and
3696 * author-link if is author-id is set,
3697 * owner-link if is owner-id is set,
3698 * causer-link if is causer-id is set.
3699 * @param int $user_id Local user ID
3701 * @throws \Exception
3703 protected static function isAllowedByUser(array $item, int $user_id): bool
3705 if (!empty($item['author-id']) && Contact\User::isBlocked($item['author-id'], $user_id)) {
3706 Logger::notice('Author is blocked by user', ['author-link' => $item['author-link'], 'uid' => $user_id, 'item-uri' => $item['uri']]);
3710 if (!empty($item['owner-id']) && Contact\User::isBlocked($item['owner-id'], $user_id)) {
3711 Logger::notice('Owner is blocked by user', ['owner-link' => $item['owner-link'], 'uid' => $user_id, 'item-uri' => $item['uri']]);
3715 // The causer is set during a thread completion, for example because of a reshare. It countains the responsible actor.
3716 if (!empty($item['causer-id']) && Contact\User::isBlocked($item['causer-id'], $user_id)) {
3717 Logger::notice('Causer is blocked by user', ['causer-link' => $item['causer-link'] ?? $item['causer-id'], 'uid' => $user_id, 'item-uri' => $item['uri']]);
3721 if (!empty($item['causer-id']) && ($item['gravity'] === self::GRAVITY_PARENT) && Contact\User::isIgnored($item['causer-id'], $user_id)) {
3722 Logger::notice('Causer is ignored by user', ['causer-link' => $item['causer-link'] ?? $item['causer-id'], 'uid' => $user_id, 'item-uri' => $item['uri']]);
3730 * Fetch the uri-id of a quote
3732 * @param string $body
3735 public static function getQuoteUriId(string $body, int $uid = 0): int
3737 $shared = BBCode::fetchShareAttributes($body);
3738 if (empty($shared['guid']) && empty($shared['message_id'])) {
3742 if (empty($shared['link']) && empty($shared['message_id'])) {
3743 Logger::notice('Invalid share block.', ['share' => $shared]);
3747 if (!empty($shared['guid'])) {
3748 $shared_item = Post::selectFirst(['uri-id'], ['guid' => $shared['guid'], 'uid' => [0, $uid]]);
3749 if (!empty($shared_item['uri-id'])) {
3750 Logger::debug('Found post by guid', ['guid' => $shared['guid'], 'uid' => $uid]);
3751 return $shared_item['uri-id'];
3755 if (!empty($shared['message_id'])) {
3756 $shared_item = Post::selectFirst(['uri-id'], ['uri' => $shared['message_id'], 'uid' => [0, $uid]]);
3757 if (!empty($shared_item['uri-id'])) {
3758 Logger::debug('Found post by message_id', ['message_id' => $shared['message_id'], 'uid' => $uid]);
3759 return $shared_item['uri-id'];
3763 if (!empty($shared['link'])) {
3764 $shared_item = Post::selectFirst(['uri-id'], ['plink' => $shared['link'], 'uid' => [0, $uid]]);
3765 if (!empty($shared_item['uri-id'])) {
3766 Logger::debug('Found post by link', ['link' => $shared['link'], 'uid' => $uid]);
3767 return $shared_item['uri-id'];
3771 $url = $shared['message_id'] ?: $shared['link'];
3772 $id = self::fetchByLink($url);
3774 Logger::notice('Post could not be fetched.', ['url' => $url, 'uid' => $uid]);
3778 $shared_item = Post::selectFirst(['uri-id'], ['id' => $id]);
3779 if (!empty($shared_item['uri-id'])) {
3780 Logger::debug('Fetched shared post', ['id' => $id, 'url' => $url, 'uid' => $uid]);
3781 return $shared_item['uri-id'];
3784 Logger::warning('Post does not exist although it was supposed to had been fetched.', ['id' => $id, 'url' => $url, 'uid' => $uid]);