3 * @copyright Copyright (C) 2010-2023, the Friendica project
5 * @license GNU AGPL version 3 or any later version
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU Affero General Public License as
9 * published by the Free Software Foundation, either version 3 of the
10 * License, or (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU Affero General Public License for more details.
17 * You should have received a copy of the GNU Affero General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
22 namespace Friendica\Model;
24 use Friendica\Content\Text\BBCode;
25 use Friendica\Content\Text\HTML;
26 use Friendica\Core\Hook;
27 use Friendica\Core\Logger;
28 use Friendica\Core\Protocol;
29 use Friendica\Core\Renderer;
30 use Friendica\Core\System;
31 use Friendica\Core\Worker;
32 use Friendica\Database\DBA;
34 use Friendica\Network\HTTPException\InternalServerErrorException;
35 use Friendica\Protocol\Activity;
36 use Friendica\Protocol\ActivityPub;
37 use Friendica\Protocol\Delivery;
38 use Friendica\Protocol\Diaspora;
39 use Friendica\Util\DateTimeFormat;
40 use Friendica\Util\Map;
41 use Friendica\Util\Network;
42 use Friendica\Util\Proxy;
43 use Friendica\Util\Strings;
44 use Friendica\Util\Temporal;
45 use GuzzleHttp\Psr7\Uri;
46 use LanguageDetection\Language;
50 // Posting types, inspired by https://www.w3.org/TR/activitystreams-vocabulary/#object-types
57 const PT_DOCUMENT = 19;
60 const PT_PERSONAL_NOTE = 128;
62 // Posting reasons (Why had a post been stored for a user?)
69 const PR_FOLLOWER = 69;
70 const PR_ANNOUNCEMENT = 70;
71 const PR_COMMENT = 71;
75 const PR_FETCHED = 75;
76 const PR_COMPLETION = 76;
78 const PR_ACTIVITY = 78;
79 const PR_DISTRIBUTE = 79;
83 // system.accept_only_sharer setting values
84 const COMPLETION_NONE = 1;
85 const COMPLETION_COMMENT = 0;
86 const COMPLETION_LIKE = 2;
88 // Field list that is used to display the items
89 const DISPLAY_FIELDLIST = [
90 'uid', 'id', 'parent', 'guid', 'network', 'gravity',
91 'uri-id', 'uri', 'thr-parent-id', 'thr-parent', 'parent-uri-id', 'parent-uri', 'conversation',
92 'commented', 'created', 'edited', 'received', 'verb', 'object-type', 'postopts', 'plink',
93 'wall', 'private', 'starred', 'origin', 'parent-origin', 'title', 'body', 'language',
94 'content-warning', 'location', 'coord', 'app', 'rendered-hash', 'rendered-html', 'object',
95 'quote-uri', 'quote-uri-id', 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid', 'mention', 'global',
96 'author-id', 'author-link', 'author-name', 'author-avatar', 'author-network', 'author-updated', 'author-gsid', 'author-addr', 'author-uri-id',
97 'owner-id', 'owner-link', 'owner-name', 'owner-avatar', 'owner-network', 'owner-contact-type', 'owner-updated',
98 'causer-id', 'causer-link', 'causer-name', 'causer-avatar', 'causer-contact-type', 'causer-network',
99 'contact-id', 'contact-uid', 'contact-link', 'contact-name', 'contact-avatar',
100 'writable', 'self', 'cid', 'alias',
101 'event-created', 'event-edited', 'event-start', 'event-finish',
102 'event-summary', 'event-desc', 'event-location', 'event-type',
103 'event-nofinish', 'event-ignore', 'event-id',
104 'question-id', 'question-multiple', 'question-voters', 'question-end-time',
105 'has-categories', 'has-media',
106 'delivery_queue_count', 'delivery_queue_done', 'delivery_queue_failed'
109 // Field list that is used to deliver items via the protocols
110 const DELIVER_FIELDLIST = ['uid', 'id', 'parent', 'uri-id', 'uri', 'thr-parent', 'parent-uri', 'guid',
111 'parent-guid', 'conversation', 'received', 'created', 'edited', 'verb', 'object-type', 'object', 'target',
112 'private', 'title', 'body', 'raw-body', 'location', 'coord', 'app',
113 'inform', 'deleted', 'extid', 'post-type', 'post-reason', 'gravity',
114 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid',
115 'author-id', 'author-addr', 'author-link', 'author-name', 'author-avatar', 'owner-id', 'owner-link', 'contact-uid',
116 'signed_text', 'network', 'wall', 'contact-id', 'plink', 'origin',
117 'thr-parent-id', 'parent-uri-id', 'quote-uri', 'quote-uri-id', 'postopts', 'pubmail',
118 'event-created', 'event-edited', 'event-start', 'event-finish',
119 'event-summary', 'event-desc', 'event-location', 'event-type',
120 'event-nofinish', 'event-ignore', 'event-id'];
122 // All fields in the item table
123 const ITEM_FIELDLIST = ['id', 'uid', 'parent', 'uri', 'parent-uri', 'thr-parent',
124 'guid', 'uri-id', 'parent-uri-id', 'thr-parent-id', 'conversation', 'vid',
125 'quote-uri', 'quote-uri-id', 'contact-id', 'wall', 'gravity', 'extid', 'psid',
126 'created', 'edited', 'commented', 'received', 'changed', 'verb',
127 'postopts', 'plink', 'resource-id', 'event-id', 'inform',
128 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid', 'post-type', 'post-reason',
129 'private', 'pubmail', 'visible', 'starred',
130 'unseen', 'deleted', 'origin', 'mention', 'global', 'network',
131 'title', 'content-warning', 'body', 'location', 'coord', 'app',
132 'rendered-hash', 'rendered-html', 'object-type', 'object', 'target-type', 'target',
133 'author-id', 'author-link', 'author-name', 'author-avatar', 'author-network',
134 'owner-id', 'owner-link', 'owner-name', 'owner-avatar', 'causer-id'];
136 // List of all verbs that don't need additional content data.
137 // Never reorder or remove entries from this list. Just add new ones at the end, if needed.
139 Activity::LIKE, Activity::DISLIKE,
140 Activity::ATTEND, Activity::ATTENDNO, Activity::ATTENDMAYBE,
149 // Item weight for query ordering
150 const GRAVITY_PARENT = 0;
151 const GRAVITY_ACTIVITY = 3;
152 const GRAVITY_COMMENT = 6;
153 const GRAVITY_UNKNOWN = 9;
156 * Update existing item entries
158 * @param array $fields The fields that are to be changed
159 * @param array $condition The condition for finding the item entries
161 * In the future we may have to change permissions as well.
162 * Then we had to add the user id as third parameter.
164 * A return value of "0" doesn't mean an error - but that 0 rows had been changed.
166 * @return integer|boolean number of affected rows - or "false" if there was an error
167 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
169 public static function update(array $fields, array $condition)
171 if (empty($condition) || empty($fields)) {
175 if (isset($fields['extid'])) {
176 $fields['external-id'] = ItemURI::getIdByURI($fields['extid']);
179 if (!empty($fields['verb'])) {
180 $fields['vid'] = Verb::getID($fields['verb']);
183 if (!empty($fields['edited'])) {
184 $previous = Post::selectFirst(['edited'], $condition);
187 $rows = Post::update($fields, $condition);
188 if (is_bool($rows)) {
192 // We only need to call the line by line update for specific fields
193 if (empty($fields['body']) && empty($fields['file']) &&
194 empty($fields['attach']) && empty($fields['edited'])) {
198 Logger::info('Updating per single row method', ['fields' => $fields, 'condition' => $condition]);
200 $items = Post::select(['id', 'origin', 'uri-id', 'uid', 'author-network', 'quote-uri-id'], $condition);
204 while ($item = DBA::fetch($items)) {
205 if (!empty($fields['body'])) {
206 if (!empty($item['quote-uri-id'])) {
207 $fields['body'] = BBCode::removeSharedData($fields['body']);
209 if (!empty($fields['raw-body'])) {
210 $fields['raw-body'] = BBCode::removeSharedData($fields['raw-body']);
214 $content_fields = ['raw-body' => trim($fields['raw-body'] ?? $fields['body'])];
216 // Remove all media attachments from the body and store them in the post-media table
217 // @todo On shared postings (Diaspora style and commented reshare) don't fetch content from the shared part
218 $content_fields['raw-body'] = Post\Media::insertFromBody($item['uri-id'], $content_fields['raw-body']);
219 $content_fields['raw-body'] = self::setHashtags($content_fields['raw-body']);
221 Post\Media::insertFromRelevantUrl($item['uri-id'], $content_fields['raw-body'], $fields['body'], $item['author-network']);
223 Post\Media::insertFromAttachmentData($item['uri-id'], $fields['body']);
224 $content_fields['raw-body'] = BBCode::removeAttachment($content_fields['raw-body']);
226 Post\Content::update($item['uri-id'], $content_fields);
229 if (!empty($fields['file'])) {
230 Post\Category::storeTextByURIId($item['uri-id'], $item['uid'], $fields['file']);
233 if (!empty($fields['attach'])) {
234 Post\Media::insertFromAttachment($item['uri-id'], $fields['attach']);
237 // We only need to notify others when it is an original entry from us.
238 // Only call the notifier when the item had been edited and records had been changed.
239 if ($item['origin'] && !empty($fields['edited']) && ($previous['edited'] != $fields['edited'])) {
240 $notify_items[] = $item['id'];
246 foreach ($notify_items as $notify_item) {
247 $post = Post::selectFirst(['uri-id', 'uid'], ['id' => $notify_item]);
248 Worker::add(Worker::PRIORITY_HIGH, 'Notifier', Delivery::POST, (int)$post['uri-id'], (int)$post['uid']);
255 * Delete an item and notify others about it - if it was ours
257 * @param array $condition The condition for finding the item entries
258 * @param integer $priority Priority for the notification
260 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
262 public static function markForDeletion(array $condition, int $priority = Worker::PRIORITY_HIGH)
264 $items = Post::select(['id'], $condition);
265 while ($item = Post::fetch($items)) {
266 self::markForDeletionById($item['id'], $priority);
272 * Delete an item for an user and notify others about it - if it was ours
274 * @param array $condition The condition for finding the item entries
275 * @param integer $uid User who wants to delete this item
277 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
279 public static function deleteForUser(array $condition, int $uid)
285 $items = Post::select(['id', 'uid', 'uri-id'], $condition);
286 while ($item = Post::fetch($items)) {
287 if (in_array($item['uid'], [$uid, 0])) {
288 Post\User::update($item['uri-id'], $uid, ['hidden' => true], true);
289 Post\ThreadUser::update($item['uri-id'], $uid, ['hidden' => true], true);
292 if ($item['uid'] == $uid) {
293 self::markForDeletionById($item['id'], Worker::PRIORITY_HIGH);
294 } elseif ($item['uid'] != 0) {
295 Logger::warning('Wrong ownership. Not deleting item', ['id' => $item['id']]);
302 * Mark an item for deletion, delete related data and notify others about it - if it was ours
304 * @param integer $item_id
305 * @param integer $priority Priority for the notification
306 * @return boolean success
307 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
309 public static function markForDeletionById(int $item_id, int $priority = Worker::PRIORITY_HIGH): bool
311 Logger::info('Mark item for deletion by id', ['id' => $item_id, 'callstack' => System::callstack()]);
312 // locate item to be deleted
313 $fields = ['id', 'uri', 'uri-id', 'uid', 'parent', 'parent-uri-id', 'origin',
314 'deleted', 'resource-id', 'event-id',
315 'verb', 'object-type', 'object', 'target', 'contact-id', 'psid', 'gravity'];
316 $item = Post::selectFirst($fields, ['id' => $item_id]);
317 if (!DBA::isResult($item)) {
318 Logger::info('Item not found.', ['id' => $item_id]);
322 if ($item['deleted']) {
323 Logger::info('Item has already been marked for deletion.', ['id' => $item_id]);
327 $parent = Post::selectFirst(['origin'], ['id' => $item['parent']]);
328 if (!DBA::isResult($parent)) {
329 $parent = ['origin' => false];
332 // clean up categories and tags so they don't end up as orphans
333 Post\Category::deleteByURIId($item['uri-id'], $item['uid']);
336 * If item is a link to a photo resource, nuke all the associated photos
337 * (visitors will not have photo resources)
338 * This only applies to photos uploaded from the photos page. Photos inserted into a post do not
339 * generate a resource-id and therefore aren't intimately linked to the item.
341 /// @TODO: this should first check if photo is used elsewhere
342 if ($item['resource-id']) {
343 Photo::delete(['resource-id' => $item['resource-id'], 'uid' => $item['uid']]);
346 // If item is a link to an event, delete the event.
347 if (intval($item['event-id'])) {
348 Event::delete($item['event-id']);
351 // If item has attachments, drop them
352 $attachments = Post\Media::getByURIId($item['uri-id'], [Post\Media::DOCUMENT]);
353 foreach($attachments as $attachment) {
354 if (preg_match('|attach/(\d+)|', $attachment['url'], $matches)) {
355 Attach::delete(['id' => $matches[1], 'uid' => $item['uid']]);
359 // Set the item to "deleted"
360 $item_fields = ['deleted' => true, 'edited' => DateTimeFormat::utcNow(), 'changed' => DateTimeFormat::utcNow()];
361 Post::update($item_fields, ['id' => $item['id']]);
363 Post\Category::storeTextByURIId($item['uri-id'], $item['uid'], '');
365 if (!Post::exists(["`uri-id` = ? AND `uid` != 0 AND NOT `deleted`", $item['uri-id']])) {
366 self::markForDeletion(['uri-id' => $item['uri-id'], 'uid' => 0, 'deleted' => false], $priority);
369 Post\DeliveryData::delete($item['uri-id']);
371 // If it's the parent of a comment thread, kill all the kids
372 if ($item['gravity'] == self::GRAVITY_PARENT) {
373 self::markForDeletion(['parent' => $item['parent'], 'deleted' => false], $priority);
376 // Is it our comment and/or our thread?
377 if (($item['origin'] || $parent['origin']) && ($item['uid'] != 0)) {
378 // When we delete the original post we will delete all existing copies on the server as well
379 self::markForDeletion(['uri-id' => $item['uri-id'], 'deleted' => false], $priority);
381 // send the notification upstream/downstream
383 Worker::add(['priority' => $priority, 'dont_fork' => true], 'Notifier', Delivery::DELETION, (int)$item['uri-id'], (int)$item['uid']);
385 } elseif ($item['uid'] != 0) {
386 Post\User::update($item['uri-id'], $item['uid'], ['hidden' => true]);
387 Post\ThreadUser::update($item['uri-id'], $item['uid'], ['hidden' => true]);
390 DI::notify()->deleteForItem($item['uri-id']);
391 DI::notification()->deleteForItem($item['uri-id']);
393 Logger::info('Item has been marked for deletion.', ['id' => $item_id]);
399 * Get guid from given item record
401 * @param array $item Item record
402 * @param bool Whether to notify (?)
403 * @return string Guid
405 public static function guid(array $item, bool $notify): string
407 if (!empty($item['guid'])) {
408 return trim($item['guid']);
412 // We have to avoid duplicates. So we create the GUID in form of a hash of the plink or uri.
413 // We add the hash of our own host because our host is the original creator of the post.
414 $prefix_host = DI::baseUrl()->getHost();
418 // We are only storing the post so we create a GUID from the original hostname.
419 if (!empty($item['author-link'])) {
420 $parsed = parse_url($item['author-link']);
421 if (!empty($parsed['host'])) {
422 $prefix_host = $parsed['host'];
426 if (empty($prefix_host) && !empty($item['plink'])) {
427 $parsed = parse_url($item['plink']);
428 if (!empty($parsed['host'])) {
429 $prefix_host = $parsed['host'];
433 if (empty($prefix_host) && !empty($item['uri'])) {
434 $parsed = parse_url($item['uri']);
435 if (!empty($parsed['host'])) {
436 $prefix_host = $parsed['host'];
440 // Is it in the format data@host.tld? - Used for mail contacts
441 if (empty($prefix_host) && !empty($item['author-link']) && strstr($item['author-link'], '@')) {
442 $mailparts = explode('@', $item['author-link']);
443 $prefix_host = array_pop($mailparts);
447 if (!empty($item['plink'])) {
448 $guid = self::guidFromUri($item['plink'], $prefix_host);
449 } elseif (!empty($item['uri'])) {
450 $guid = self::guidFromUri($item['uri'], $prefix_host);
452 $guid = System::createUUID(hash('crc32', $prefix_host));
459 * Returns contact id from given item record
461 * @param array $item Item record
462 * @return int Contact id
464 private static function contactId(array $item): int
466 if ($item['uid'] == 0) {
467 return $item['author-id'];
470 if ($item['origin']) {
471 $owner = User::getOwnerDataById($item['uid']);
475 if (!empty($item['causer-id']) && Contact::isSharing($item['causer-id'], $item['uid'], true)) {
476 $cdata = Contact::getPublicAndUserContactID($item['causer-id'], $item['uid']);
477 if (!empty($cdata['user'])) {
478 return $cdata['user'];
482 if ($item['gravity'] == self::GRAVITY_PARENT) {
483 if (Contact::isSharingByURL($item['owner-link'], $item['uid'], true)) {
484 $contact_id = Contact::getIdForURL($item['owner-link'], $item['uid']);
486 $contact_id = Contact::getIdForURL($item['owner-link']);
488 if (!empty($contact_id)) {
493 if (Contact::isSharingByURL($item['author-link'], $item['uid'], true)) {
494 $contact_id = Contact::getIdForURL($item['author-link'], $item['uid']);
496 $contact_id = Contact::getIdForURL($item['author-link']);
499 if (!empty($contact_id)) {
503 Logger::warning('contact-id could not be fetched, using self contact instead.', ['uid' => $item['uid'], 'item' => $item]);
504 $self = Contact::selectFirst(['id'], ['self' => true, 'uid' => $item['uid']]);
509 * Write an item array into a spool file to be inserted later.
510 * This command is called whenever there are issues storing an item.
512 * @param array $item The item fields that are to be inserted
515 private static function spool(array $item)
517 // Now we store the data in the spool directory
518 // We use "microtime" to keep the arrival order and "mt_rand" to avoid duplicates
519 $file = 'item-' . round(microtime(true) * 10000) . '-' . mt_rand() . '.msg';
521 $spoolpath = System::getSpoolPath();
522 if ($spoolpath != '') {
523 $spool = $spoolpath . '/' . $file;
525 file_put_contents($spool, json_encode($item));
526 Logger::warning("Item wasn't stored - Item was spooled into file", ['file' => $file]);
531 * Check if the item array is a duplicate
533 * @param array $item Item record
534 * @return boolean is it a duplicate?
536 private static function isDuplicate(array $item): bool
538 // Checking if there is already an item with the same guid
539 $condition = ['guid' => $item['guid'], 'network' => $item['network'], 'uid' => $item['uid']];
540 if (Post::exists($condition)) {
541 Logger::notice('Found already existing item', $condition);
545 $condition = ['uri-id' => $item['uri-id'], 'uid' => $item['uid'],
546 'network' => [$item['network'], Protocol::DFRN]];
547 if (Post::exists($condition)) {
548 Logger::notice('duplicated item with the same uri found.', $condition);
552 // On Friendica and Diaspora the GUID is unique
553 if (in_array($item['network'], [Protocol::DFRN, Protocol::DIASPORA])) {
554 $condition = ['guid' => $item['guid'], 'uid' => $item['uid']];
555 if (Post::exists($condition)) {
556 Logger::notice('duplicated item with the same guid found.', $condition);
559 } elseif ($item['network'] == Protocol::OSTATUS) {
560 // Check for an existing post with the same content. There seems to be a problem with OStatus.
561 $condition = ["`body` = ? AND `network` = ? AND `created` = ? AND `contact-id` = ? AND `uid` = ?",
562 $item['body'], $item['network'], $item['created'], $item['contact-id'], $item['uid']];
563 if (Post::exists($condition)) {
564 Logger::notice('duplicated item with the same body found.', $item);
570 * Check for already added items.
571 * There is a timing issue here that sometimes creates double postings.
572 * An unique index would help - but the limitations of MySQL (maximum size of index values) prevent this.
574 if (($item['uid'] == 0) && Post::exists(['uri-id' => $item['uri-id'], 'uid' => 0])) {
575 Logger::notice('Global item already stored.', ['uri-id' => $item['uri-id'], 'network' => $item['network']]);
583 * Check if the item array is valid
585 * @param array $item Item record
586 * @return boolean item is valid
588 public static function isValid(array $item): bool
590 // When there is no content then we don't post it
591 if (($item['body'] . $item['title'] == '') && empty($item['quote-uri-id']) && empty($item['attachments']) && (empty($item['uri-id']) || !Post\Media::existsByURIId($item['uri-id']))) {
592 Logger::notice('No body, no title.');
596 if (!empty($item['uid'])) {
597 $owner = User::getOwnerDataById($item['uid'], false);
599 Logger::warning('Missing item user owner data', ['uid' => $item['uid']]);
603 if ($owner['account_expired'] || $owner['account_removed']) {
604 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']]);
609 if (!empty($item['author-id']) && Contact::isBlocked($item['author-id'])) {
610 Logger::notice('Author is blocked node-wide', ['author-link' => $item['author-link'], 'item-uri' => $item['uri']]);
614 if (!empty($item['author-link']) && Network::isUrlBlocked($item['author-link'])) {
615 Logger::notice('Author server is blocked', ['author-link' => $item['author-link'], 'item-uri' => $item['uri']]);
619 if (!empty($item['owner-id']) && Contact::isBlocked($item['owner-id'])) {
620 Logger::notice('Owner is blocked node-wide', ['owner-link' => $item['owner-link'], 'item-uri' => $item['uri']]);
624 if (!empty($item['owner-link']) && Network::isUrlBlocked($item['owner-link'])) {
625 Logger::notice('Owner server is blocked', ['owner-link' => $item['owner-link'], 'item-uri' => $item['uri']]);
629 if ($item['verb'] == Activity::FOLLOW) {
630 if (!$item['origin'] && ($item['author-id'] == Contact::getPublicIdByUserId($item['uid']))) {
631 // Our own follow request can be relayed to us. We don't store it to avoid notification chaos.
632 Logger::info("Follow: Don't store not origin follow request", ['parent-uri' => $item['parent-uri']]);
636 $condition = ['verb' => Activity::FOLLOW, 'uid' => $item['uid'],
637 'parent-uri' => $item['parent-uri'], 'author-id' => $item['author-id']];
638 if (Post::exists($condition)) {
639 // It happens that we receive multiple follow requests by the same author - we only store one.
640 Logger::info('Follow: Found existing follow request from author', ['author-id' => $item['author-id'], 'parent-uri' => $item['parent-uri']]);
649 * Check if the item array is too old
651 * @param array $item Item record
652 * @return boolean item is too old
654 public static function isTooOld(array $item): bool
656 // check for create date and expire time
657 $expire_interval = DI::config()->get('system', 'dbclean-expire-days', 0);
659 $user = DBA::selectFirst('user', ['expire'], ['uid' => $item['uid']]);
660 if (DBA::isResult($user) && ($user['expire'] > 0) && (($user['expire'] < $expire_interval) || ($expire_interval == 0))) {
661 $expire_interval = $user['expire'];
664 if (($expire_interval > 0) && !empty($item['created'])) {
665 $expire_date = time() - ($expire_interval * 86400);
666 $created_date = strtotime($item['created']);
667 if ($created_date < $expire_date) {
668 Logger::notice('Item created before expiration interval.', [
669 'created' => date('c', $created_date),
670 'expired' => date('c', $expire_date),
681 * Return the id of the given item array if it has been stored before
683 * @param array $item Item record
684 * @return integer Item id or zero on error
686 private static function getDuplicateID(array $item): int
688 if (empty($item['network']) || in_array($item['network'], Protocol::FEDERATED)) {
689 $condition = ['`uri-id` = ? AND `uid` = ? AND `network` IN (?, ?, ?, ?)',
692 Protocol::ACTIVITYPUB,
697 $existing = Post::selectFirst(['id', 'network'], $condition);
698 if (DBA::isResult($existing)) {
699 // We only log the entries with a different user id than 0. Otherwise we would have too many false positives
700 if ($item['uid'] != 0) {
701 Logger::notice('Item already existed for user', [
702 'uri-id' => $item['uri-id'],
703 'uid' => $item['uid'],
704 'network' => $item['network'],
705 'existing_id' => $existing['id'],
706 'existing_network' => $existing['network']
710 return $existing['id'];
717 * Fetch the uri-id of the parent for the given uri-id
719 * @param integer $uriid
722 public static function getParent(int $uriid): int
724 $thread_parent = Post::selectFirstPost(['thr-parent-id', 'gravity'], ['uri-id' => $uriid]);
725 if (empty($thread_parent)) {
729 if ($thread_parent['gravity'] == Item::GRAVITY_PARENT) {
733 return self::getParent($thread_parent['thr-parent-id']);
737 * Fetch top-level parent data for the given item array
740 * @return array item array with parent data
743 private static function getTopLevelParent(array $item): array
745 $fields = ['uid', 'uri', 'parent-uri', 'id', 'deleted',
746 'uri-id', 'parent-uri-id',
747 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid',
748 'wall', 'private', 'origin', 'author-id'];
749 $condition = ['uri-id' => [$item['thr-parent-id'], $item['parent-uri-id']], 'uid' => $item['uid']];
750 $params = ['order' => ['id' => false]];
751 $parent = Post::selectFirst($fields, $condition, $params);
753 if (!DBA::isResult($parent) && Post::exists(['uri-id' => [$item['thr-parent-id'], $item['parent-uri-id']], 'uid' => 0])) {
754 $stored = Item::storeForUserByUriId($item['thr-parent-id'], $item['uid'], ['post-reason' => Item::PR_COMPLETION]);
755 if (!$stored && ($item['thr-parent-id'] != $item['parent-uri-id'])) {
756 $stored = Item::storeForUserByUriId($item['parent-uri-id'], $item['uid'], ['post-reason' => Item::PR_COMPLETION]);
759 Logger::info('Stored thread parent item for user', ['uri-id' => $item['thr-parent-id'], 'uid' => $item['uid'], 'stored' => $stored]);
760 $parent = Post::selectFirst($fields, $condition, $params);
764 if (!DBA::isResult($parent)) {
765 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)]);
769 if ($parent['uri-id'] == $parent['parent-uri-id']) {
773 $condition = ['uri-id' => $parent['parent-uri-id'],
774 'parent-uri-id' => $parent['parent-uri-id'],
775 'uid' => $parent['uid']];
776 $params = ['order' => ['id' => false]];
777 $toplevel_parent = Post::selectFirst($fields, $condition, $params);
779 if (!DBA::isResult($toplevel_parent) && $item['origin']) {
780 $stored = Item::storeForUserByUriId($item['parent-uri-id'], $item['uid'], ['post-reason' => Item::PR_COMPLETION]);
781 Logger::info('Stored parent item for user', ['uri-id' => $item['parent-uri-id'], 'uid' => $item['uid'], 'stored' => $stored]);
782 $toplevel_parent = Post::selectFirst($fields, $condition, $params);
785 if (!DBA::isResult($toplevel_parent)) {
786 Logger::notice('item top level parent was not found - ignoring item', ['parent-uri-id' => $parent['parent-uri-id'], 'uid' => $parent['uid']]);
790 return $toplevel_parent;
794 * Get the gravity for the given item array
797 * @return integer gravity
799 private static function getGravity(array $item): int
801 $activity = DI::activity();
803 if (isset($item['gravity'])) {
804 return intval($item['gravity']);
805 } elseif ($item['parent-uri-id'] === $item['uri-id']) {
806 return self::GRAVITY_PARENT;
807 } elseif ($activity->match($item['verb'], Activity::POST)) {
808 return self::GRAVITY_COMMENT;
809 } elseif ($activity->match($item['verb'], Activity::FOLLOW)) {
810 return self::GRAVITY_ACTIVITY;
811 } elseif ($activity->match($item['verb'], Activity::ANNOUNCE)) {
812 return self::GRAVITY_ACTIVITY;
815 Logger::info('Unknown gravity for verb', ['verb' => $item['verb']]);
816 return self::GRAVITY_UNKNOWN; // Should not happen
819 private static function prepareOriginPost(array $item): array
821 $item = DI::contentItem()->initializePost($item);
822 $item = DI::contentItem()->finalizePost($item);
828 * Inserts item record
830 * @param array $item Item array to be inserted
831 * @param int $notify Notification (type?)
832 * @param bool $post_local (???)
833 * @return int Zero means error, otherwise primary key (id) is being returned
835 public static function insert(array $item, int $notify = 0, bool $post_local = true): int
839 $priority = Worker::PRIORITY_HIGH;
841 // If it is a posting where users should get notifications, then define it as wall posting
843 $item = self::prepareOriginPost($item);
845 if (is_int($notify) && in_array($notify, Worker::PRIORITIES)) {
849 $item['network'] = trim(($item['network'] ?? '') ?: Protocol::PHANTOM);
852 $uid = intval($item['uid']);
854 $item['guid'] = self::guid($item, $notify);
855 $item['uri'] = substr(trim($item['uri'] ?? '') ?: self::newURI($item['guid']), 0, 255);
858 $item['uri-id'] = ItemURI::insert(['uri' => $item['uri'], 'guid' => $item['guid']]);
860 // Backward compatibility: parent-uri used to be the direct parent uri.
861 // If it is provided without a thr-parent, it probably is the old behavior.
862 if (empty($item['thr-parent']) || empty($item['parent-uri'])) {
863 $item['thr-parent'] = trim($item['thr-parent'] ?? $item['parent-uri'] ?? $item['uri']);
864 $item['parent-uri'] = $item['thr-parent'];
867 $item['thr-parent-id'] = ItemURI::getIdByURI($item['thr-parent']);
868 $item['parent-uri-id'] = ItemURI::getIdByURI($item['parent-uri']);
870 // Store conversation data
871 $source = $item['source'] ?? '';
872 unset($item['conversation-uri']);
873 unset($item['conversation-href']);
874 unset($item['source']);
877 * Do we already have this item?
878 * We have to check several networks since Friendica posts could be repeated
879 * via OStatus (maybe Diaspora as well)
881 $duplicate = self::getDuplicateID($item);
886 // Additional duplicate checks
887 /// @todo Check why the first duplication check returns the item number and the second a 0
888 if (self::isDuplicate($item)) {
892 if (!isset($item['post-type'])) {
893 $item['post-type'] = empty($item['title']) ? self::PT_NOTE : self::PT_ARTICLE;
896 $defined_permissions = isset($item['allow_cid']) && isset($item['allow_gid']) && isset($item['deny_cid']) && isset($item['deny_gid']) && isset($item['private']);
898 $item['wall'] = intval($item['wall'] ?? 0);
899 $item['extid'] = trim($item['extid'] ?? '');
900 $item['author-name'] = trim($item['author-name'] ?? '');
901 $item['author-link'] = trim($item['author-link'] ?? '');
902 $item['author-avatar'] = trim($item['author-avatar'] ?? '');
903 $item['owner-name'] = trim($item['owner-name'] ?? '');
904 $item['owner-link'] = trim($item['owner-link'] ?? '');
905 $item['owner-avatar'] = trim($item['owner-avatar'] ?? '');
906 $item['received'] = (isset($item['received']) ? DateTimeFormat::utc($item['received']) : DateTimeFormat::utcNow());
907 $item['created'] = (isset($item['created']) ? DateTimeFormat::utc($item['created']) : $item['received']);
908 $item['edited'] = (isset($item['edited']) ? DateTimeFormat::utc($item['edited']) : $item['created']);
909 $item['changed'] = (isset($item['changed']) ? DateTimeFormat::utc($item['changed']) : $item['created']);
910 $item['commented'] = (isset($item['commented']) ? DateTimeFormat::utc($item['commented']) : $item['created']);
911 $item['title'] = substr(trim($item['title'] ?? ''), 0, 255);
912 $item['location'] = trim($item['location'] ?? '');
913 $item['coord'] = trim($item['coord'] ?? '');
914 $item['visible'] = (isset($item['visible']) ? intval($item['visible']) : 1);
915 $item['deleted'] = 0;
916 $item['verb'] = trim($item['verb'] ?? '');
917 $item['object-type'] = trim($item['object-type'] ?? '');
918 $item['object'] = trim($item['object'] ?? '');
919 $item['target-type'] = trim($item['target-type'] ?? '');
920 $item['target'] = trim($item['target'] ?? '');
921 $item['plink'] = substr(trim($item['plink'] ?? ''), 0, 255);
922 $item['allow_cid'] = trim($item['allow_cid'] ?? '');
923 $item['allow_gid'] = trim($item['allow_gid'] ?? '');
924 $item['deny_cid'] = trim($item['deny_cid'] ?? '');
925 $item['deny_gid'] = trim($item['deny_gid'] ?? '');
926 $item['private'] = intval($item['private'] ?? self::PUBLIC);
927 $item['body'] = trim($item['body'] ?? '');
928 $item['raw-body'] = trim($item['raw-body'] ?? $item['body']);
929 $item['app'] = trim($item['app'] ?? '');
930 $item['origin'] = intval($item['origin'] ?? 0);
931 $item['postopts'] = trim($item['postopts'] ?? '');
932 $item['resource-id'] = trim($item['resource-id'] ?? '');
933 $item['event-id'] = intval($item['event-id'] ?? 0);
934 $item['inform'] = trim($item['inform'] ?? '');
935 $item['file'] = trim($item['file'] ?? '');
937 // Communities aren't working with the Diaspora protocol
938 if (($uid != 0) && ($item['network'] == Protocol::DIASPORA)) {
939 $user = User::getById($uid, ['account-type']);
940 if ($user['account-type'] == Contact::TYPE_COMMUNITY) {
941 Logger::info('Community posts are not supported via Diaspora');
946 // Items cannot be stored before they happen ...
947 if ($item['created'] > DateTimeFormat::utcNow()) {
948 $item['created'] = DateTimeFormat::utcNow();
951 // We haven't invented time travel by now.
952 if ($item['edited'] > DateTimeFormat::utcNow()) {
953 $item['edited'] = DateTimeFormat::utcNow();
956 $item['plink'] = ($item['plink'] ?? '') ?: DI::baseUrl() . '/display/' . urlencode($item['guid']);
958 $item['gravity'] = self::getGravity($item);
960 $default = ['url' => $item['author-link'], 'name' => $item['author-name'],
961 'photo' => $item['author-avatar'], 'network' => $item['network']];
962 $item['author-id'] = ($item['author-id'] ?? 0) ?: Contact::getIdForURL($item['author-link'], 0, null, $default);
964 $default = ['url' => $item['owner-link'], 'name' => $item['owner-name'],
965 'photo' => $item['owner-avatar'], 'network' => $item['network']];
966 $item['owner-id'] = ($item['owner-id'] ?? 0) ?: Contact::getIdForURL($item['owner-link'], 0, null, $default);
968 $item['post-reason'] = self::getPostReason($item);
970 // Ensure that there is an avatar cache
971 Contact::checkAvatarCache($item['author-id']);
972 Contact::checkAvatarCache($item['owner-id']);
974 $item['contact-id'] = self::contactId($item);
976 if (!empty($item['direction']) && in_array($item['direction'], [Conversation::PUSH, Conversation::RELAY]) &&
977 empty($item['origin']) && self::isTooOld($item)) {
978 Logger::info('Item is too old', ['item' => $item]);
982 if (!self::isValid($item)) {
986 if ($item['gravity'] !== self::GRAVITY_PARENT) {
987 $toplevel_parent = self::getTopLevelParent($item);
988 if (empty($toplevel_parent)) {
992 $parent_id = $toplevel_parent['id'];
993 $item['parent-uri'] = $toplevel_parent['uri'];
994 $item['parent-uri-id'] = $toplevel_parent['uri-id'];
995 $item['deleted'] = $toplevel_parent['deleted'];
996 $item['wall'] = $toplevel_parent['wall'];
998 // Reshares have to keep their permissions to allow forums to work
999 if (!$defined_permissions && (!$item['origin'] || ($item['verb'] != Activity::ANNOUNCE))) {
1000 $item['allow_cid'] = $toplevel_parent['allow_cid'];
1001 $item['allow_gid'] = $toplevel_parent['allow_gid'];
1002 $item['deny_cid'] = $toplevel_parent['deny_cid'];
1003 $item['deny_gid'] = $toplevel_parent['deny_gid'];
1006 $parent_origin = $toplevel_parent['origin'];
1008 // Don't federate received participation messages
1009 if ($item['verb'] != Activity::FOLLOW) {
1010 $item['wall'] = $toplevel_parent['wall'];
1012 $item['wall'] = false;
1013 // Participations are technical messages, so they are set to "seen" automatically
1014 $item['unseen'] = false;
1018 * If the parent is private, force privacy for the entire conversation
1019 * This differs from the above settings as it subtly allows comments from
1020 * email correspondents to be private even if the overall thread is not.
1022 if (!$defined_permissions && $toplevel_parent['private']) {
1023 $item['private'] = $toplevel_parent['private'];
1026 // If its a post that originated here then tag the thread as "mention"
1027 if ($item['origin'] && $item['uid']) {
1028 DBA::update('post-thread-user', ['mention' => true], ['uri-id' => $item['parent-uri-id'], 'uid' => $item['uid']]);
1029 Logger::info('tagged thread as mention', ['parent' => $parent_id, 'parent-uri-id' => $item['parent-uri-id'], 'uid' => $item['uid']]);
1032 // Update the contact relations
1033 Contact\Relation::store($toplevel_parent['author-id'], $item['author-id'], $item['created']);
1036 $parent_origin = $item['origin'];
1038 if ($item['wall'] && empty($item['conversation'])) {
1039 $item['conversation'] = $item['parent-uri'] . '#context';
1043 if ($item['origin']) {
1044 if (Photo::setPermissionFromBody($item['body'], $item['uid'], $item['contact-id'], $item['allow_cid'], $item['allow_gid'], $item['deny_cid'], $item['deny_gid'])) {
1045 $item['object-type'] = Activity\ObjectType::IMAGE;
1048 $item = DI::contentItem()->moveAttachmentsFromBodyToAttach($item);
1051 $item['parent-uri-id'] = ItemURI::getIdByURI($item['parent-uri']);
1052 $item['thr-parent-id'] = ItemURI::getIdByURI($item['thr-parent']);
1054 if (!empty($item['conversation']) && empty($item['conversation-id'])) {
1055 $item['conversation-id'] = ItemURI::getIdByURI($item['conversation']);
1058 // Is this item available in the global items (with uid=0)?
1059 if ($item['uid'] == 0) {
1060 $item['global'] = true;
1062 // Set the global flag on all items if this was a global item entry
1063 Post::update(['global' => true], ['uri-id' => $item['uri-id']]);
1065 $item['global'] = Post::exists(['uid' => 0, 'uri-id' => $item['uri-id']]);
1069 if (!$defined_permissions && !empty($item['allow_cid'] . $item['allow_gid'] . $item['deny_cid'] . $item['deny_gid'])) {
1070 $item['private'] = self::PRIVATE;
1073 if ($notify && $post_local) {
1074 $item['edit'] = false;
1075 $item['parent'] = $parent_id;
1077 // Trigger automatic reactions for addons
1078 if (!isset($item['api_source'])) {
1079 $item['api_source'] = true;
1082 // We have to tell the hooks who we are - this really should be improved
1083 if (!DI::userSession()->getLocalUserId()) {
1084 $_SESSION['authenticated'] = true;
1085 $_SESSION['uid'] = $uid;
1086 $dummy_session = true;
1088 $dummy_session = false;
1091 Hook::callAll('post_local', $item);
1093 if ($dummy_session) {
1094 unset($_SESSION['authenticated']);
1095 unset($_SESSION['uid']);
1097 } elseif (!$notify) {
1098 Hook::callAll('post_remote', $item);
1101 if (!empty($item['cancel'])) {
1102 Logger::notice('post cancelled by addon.');
1106 if (empty($item['vid']) && !empty($item['verb'])) {
1107 $item['vid'] = Verb::getID($item['verb']);
1110 // Creates or assigns the permission set
1111 $item['psid'] = DI::permissionSet()->selectOrCreate(
1112 DI::permissionSetFactory()->createFromString(
1120 if (!empty($item['extid'])) {
1121 $item['external-id'] = ItemURI::getIdByURI($item['extid']);
1124 if ($item['verb'] == Activity::ANNOUNCE) {
1125 self::setOwnerforResharedItem($item);
1128 if (isset($item['attachments'])) {
1129 foreach ($item['attachments'] as $attachment) {
1130 $attachment['uri-id'] = $item['uri-id'];
1131 Post\Media::insert($attachment);
1133 unset($item['attachments']);
1136 if (empty($item['quote-uri-id'])) {
1137 $quote_id = self::getQuoteUriId($item['body']);
1138 if (!empty($quote_id)) {
1139 // This is one of these "should not happen" situations.
1140 // The protocol implementations should already have done this job.
1141 Logger::notice('Quote-uri-id detected in post', ['id' => $quote_id, 'guid' => $item['guid'], 'uri-id' => $item['uri-id'], 'callstack' => System::callstack(20)]);
1142 $item['quote-uri-id'] = $quote_id;
1146 if (!empty($item['quote-uri-id'])) {
1147 $item['raw-body'] = BBCode::removeSharedData($item['raw-body']);
1148 $item['body'] = BBCode::removeSharedData($item['body']);
1151 // Remove all media attachments from the body and store them in the post-media table
1152 $item['raw-body'] = Post\Media::insertFromBody($item['uri-id'], $item['raw-body']);
1153 $item['raw-body'] = self::setHashtags($item['raw-body']);
1155 $author = Contact::getById($item['author-id'], ['network']);
1156 Post\Media::insertFromRelevantUrl($item['uri-id'], $item['raw-body'], $item['body'], $author['network'] ?? '');
1158 Post\Media::insertFromAttachmentData($item['uri-id'], $item['body']);
1159 $item['body'] = BBCode::removeAttachment($item['body']);
1160 $item['raw-body'] = BBCode::removeAttachment($item['raw-body']);
1162 // Check for hashtags in the body and repair or add hashtag links
1163 $item['body'] = self::setHashtags($item['body']);
1165 $item['language'] = self::getLanguage($item);
1167 $notify_type = Delivery::POST;
1169 // Filling item related side tables
1170 if (!empty($item['attach'])) {
1171 Post\Media::insertFromAttachment($item['uri-id'], $item['attach']);
1174 if (empty($item['event-id'])) {
1175 unset($item['event-id']);
1177 $ev = Event::fromBBCode($item['body']);
1178 if ((!empty($ev['desc']) || !empty($ev['summary'])) && !empty($ev['start'])) {
1179 Logger::info('Event found.');
1180 $ev['cid'] = $item['contact-id'];
1181 $ev['uid'] = $item['uid'];
1182 $ev['uri'] = $item['uri'];
1183 $ev['edited'] = $item['edited'];
1184 $ev['private'] = $item['private'];
1185 $ev['guid'] = $item['guid'];
1186 $ev['plink'] = $item['plink'];
1187 $ev['network'] = $item['network'];
1188 $ev['protocol'] = $item['protocol'] ?? Conversation::PARCEL_UNKNOWN;
1189 $ev['direction'] = $item['direction'] ?? Conversation::UNKNOWN;
1190 $ev['source'] = $item['source'] ?? '';
1192 $event = DBA::selectFirst('event', ['id'], ['uri' => $item['uri'], 'uid' => $item['uid']]);
1193 if (DBA::isResult($event)) {
1194 $ev['id'] = $event['id'];
1197 $event_id = Event::store($ev);
1198 $item = Event::getItemArrayForImportedId($event_id, $item);
1200 Logger::info('Event was stored', ['id' => $event_id]);
1204 if (empty($item['causer-id'])) {
1205 unset($item['causer-id']);
1208 if (in_array($item['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN])) {
1209 $content_warning = BBCode::getAbstract($item['body'], Protocol::ACTIVITYPUB);
1210 if (!empty($content_warning) && empty($item['content-warning'])) {
1211 $item['content-warning'] = BBCode::toPlaintext($content_warning);
1215 Post::insert($item['uri-id'], $item);
1217 if ($item['gravity'] == self::GRAVITY_PARENT) {
1218 Post\Thread::insert($item['uri-id'], $item);
1221 // The content of activities normally doesn't matter - except for likes from Misskey
1222 if (!in_array($item['verb'], self::ACTIVITIES) || in_array($item['verb'], [Activity::LIKE, Activity::DISLIKE]) && !empty($item['body']) && (mb_strlen($item['body']) == 1)) {
1223 Post\Content::insert($item['uri-id'], $item);
1226 $item['parent'] = $parent_id;
1228 // Create Diaspora signature
1229 if ($item['origin'] && empty($item['diaspora_signed_text']) && ($item['gravity'] != self::GRAVITY_PARENT)) {
1230 $signed = Diaspora::createCommentSignature($item);
1231 if (!empty($signed)) {
1232 $item['diaspora_signed_text'] = json_encode($signed);
1236 if (!empty($item['diaspora_signed_text'])) {
1237 DBA::replace('diaspora-interaction', ['uri-id' => $item['uri-id'], 'interaction' => $item['diaspora_signed_text']]);
1240 // Attached file links
1241 if (!empty($item['file'])) {
1242 Post\Category::storeTextByURIId($item['uri-id'], $item['uid'], $item['file']);
1245 // Delivery relevant data
1246 $delivery_data = Post\DeliveryData::extractFields($item);
1248 if (!empty($item['origin']) || !empty($item['wall']) || !empty($delivery_data['postopts']) || !empty($delivery_data['inform'])) {
1249 Post\DeliveryData::insert($item['uri-id'], $delivery_data);
1252 // Store tags from the body if this hadn't been handled previously in the protocol classes
1253 if (!Tag::existsForPost($item['uri-id'])) {
1254 Tag::storeFromBody($item['uri-id'], $item['body']);
1257 $condition = ['uri-id' => $item['uri-id'], 'uid' => $item['uid']];
1258 if (Post::exists($condition)) {
1259 Logger::notice('Item is already inserted - aborting', $condition);
1263 $post_user_id = Post\User::insert($item['uri-id'], $item['uid'], $item);
1264 if (!$post_user_id) {
1265 Logger::notice('Post-User is already inserted - aborting', ['uid' => $item['uid'], 'uri-id' => $item['uri-id']]);
1269 if ($item['gravity'] == self::GRAVITY_PARENT) {
1270 $item['post-user-id'] = $post_user_id;
1271 Post\ThreadUser::insert($item['uri-id'], $item['uid'], $item);
1274 Logger::notice('created item', ['post-id' => $post_user_id, 'uid' => $item['uid'], 'network' => $item['network'], 'uri-id' => $item['uri-id'], 'guid' => $item['guid']]);
1276 $posted_item = Post::selectFirst(self::ITEM_FIELDLIST, ['post-user-id' => $post_user_id]);
1277 if (!DBA::isResult($posted_item)) {
1278 // On failure store the data into a spool file so that the "SpoolPost" worker can try again later.
1279 Logger::warning('Could not store item. it will be spooled', ['id' => $post_user_id]);
1280 self::spool($orig_item);
1284 // update the commented timestamp on the parent
1285 if (DI::config()->get('system', 'like_no_comment')) {
1286 // Update when it is a comment
1287 $update_commented = in_array($posted_item['gravity'], [self::GRAVITY_PARENT, self::GRAVITY_COMMENT]);
1289 // Update when it isn't a follow or tag verb
1290 $update_commented = !in_array($posted_item['verb'], [Activity::FOLLOW, Activity::TAG]);
1293 if ($update_commented) {
1294 $fields = ['commented' => DateTimeFormat::utcNow(), 'changed' => DateTimeFormat::utcNow()];
1296 $fields = ['changed' => DateTimeFormat::utcNow()];
1299 Post::update($fields, ['uri-id' => $posted_item['parent-uri-id'], 'uid' => $posted_item['uid']]);
1301 // In that function we check if this is a forum post. Additionally we delete the item under certain circumstances
1302 if (self::tagDeliver($posted_item['uid'], $post_user_id)) {
1303 // Get the user information for the logging
1304 $user = User::getById($uid);
1306 Logger::notice('Item had been deleted', ['id' => $post_user_id, 'user' => $uid, 'account-type' => $user['account-type']]);
1311 DI::contentItem()->postProcessPost($posted_item);
1313 Hook::callAll('post_remote_end', $posted_item);
1316 if ($posted_item['gravity'] === self::GRAVITY_PARENT) {
1317 self::addShadow($post_user_id);
1319 self::addShadowPost($post_user_id);
1322 self::updateContact($posted_item);
1324 Post\UserNotification::setNotification($posted_item['uri-id'], $posted_item['uid']);
1326 // Distribute items to users who subscribed to their tags
1327 self::distributeByTags($posted_item);
1329 // Automatically reshare the item if the "remote_self" option is selected
1330 self::autoReshare($posted_item);
1332 $transmit = $notify || ($posted_item['visible'] && ($parent_origin || $posted_item['origin']));
1335 if ($posted_item['uid'] && Contact\User::isBlocked($posted_item['author-id'], $posted_item['uid'])) {
1336 Logger::info('Message from blocked author will not be relayed', ['item' => $posted_item['id'], 'uri' => $posted_item['uri'], 'cid' => $posted_item['author-id']]);
1339 if ($transmit && $posted_item['uid'] && Contact\User::isBlocked($posted_item['owner-id'], $posted_item['uid'])) {
1340 Logger::info('Message from blocked owner will not be relayed', ['item' => $posted_item['id'], 'uri' => $posted_item['uri'], 'cid' => $posted_item['owner-id']]);
1343 if ($transmit && !empty($posted_item['causer-id']) && $posted_item['uid'] && Contact\User::isBlocked($posted_item['causer-id'], $posted_item['uid'])) {
1344 Logger::info('Message from blocked causer will not be relayed', ['item' => $posted_item['id'], 'uri' => $posted_item['uri'], 'cid' => $posted_item['causer-id']]);
1348 // Don't relay participation messages
1349 if (($posted_item['verb'] == Activity::FOLLOW) &&
1350 (!$posted_item['origin'] || ($posted_item['author-id'] != Contact::getPublicIdByUserId($uid)))) {
1351 Logger::info('Participation messages will not be relayed', ['item' => $posted_item['id'], 'uri' => $posted_item['uri'], 'verb' => $posted_item['verb']]);
1356 if (!empty($source) && ($transmit || DI::config()->get('debug', 'store_source'))) {
1357 Post\Activity::insert($item['uri-id'], $source);
1361 Worker::add(['priority' => $priority, 'dont_fork' => true], 'Notifier', $notify_type, (int)$posted_item['uri-id'], (int)$posted_item['uid']);
1364 // Fill the cache with the rendered content.
1365 if (in_array($posted_item['gravity'], [self::GRAVITY_PARENT, self::GRAVITY_COMMENT]) && ($posted_item['uid'] == 0)) {
1366 self::updateDisplayCache($posted_item['uri-id']);
1369 return $post_user_id;
1373 * Fetch the post reason for a given item array
1375 * @param array $item
1379 public static function getPostReason(array $item): int
1381 $actor = ($item['gravity'] == self::GRAVITY_PARENT) ? $item['owner-id'] : $item['author-id'];
1382 if (empty($item['origin']) && ($item['uid'] != 0) && Contact::isSharing($actor, $item['uid'])) {
1383 return self::PR_FOLLOWER;
1386 if (!empty($item['origin']) && empty($item['post-reason'])) {
1387 return self::PR_LOCAL;
1390 return $item['post-reason'] ?? self::PR_NONE;
1394 * Update the display cache
1396 * @param integer $uri_id
1398 * @throws InternalServerErrorException
1399 * @throws \ImagickException
1401 public static function updateDisplayCache(int $uri_id)
1403 $item = Post::selectFirst(self::DISPLAY_FIELDLIST, ['uri-id' => $uri_id]);
1408 self::prepareBody($item, false, false, true);
1412 * Change the owner of a parent item if it had been shared by a forum
1414 * (public) forum posts in the new format consist of the regular post by the author
1415 * followed by an announce message sent from the forum account.
1416 * Changing the owner helps in grouping forum posts.
1418 * @param array $item
1421 private static function setOwnerforResharedItem(array $item)
1423 $parent = Post::selectFirst(['id', 'causer-id', 'owner-id', 'author-id', 'author-link', 'origin', 'post-reason'],
1424 ['uri-id' => $item['thr-parent-id'], 'uid' => $item['uid']]);
1425 if (!DBA::isResult($parent)) {
1426 Logger::error('Parent not found', ['uri-id' => $item['thr-parent-id'], 'uid' => $item['uid']]);
1430 $author = Contact::selectFirst(['url', 'contact-type', 'network'], ['id' => $item['author-id']]);
1431 if (!DBA::isResult($author)) {
1432 Logger::error('Author not found', ['id' => $item['author-id']]);
1436 $self_contact = Contact::selectFirst(['id'], ['uid' => $item['uid'], 'self' => true]);
1437 $self = !empty($self_contact) ? $self_contact['id'] : 0;
1439 $cid = Contact::getIdForURL($author['url'], $item['uid']);
1440 if (empty($cid) || (!Contact::isSharing($cid, $item['uid']) && ($cid != $self))) {
1441 Logger::info('The resharer is not a following contact: quit', ['resharer' => $author['url'], 'uid' => $item['uid'], 'cid' => $cid]);
1445 if ($author['contact-type'] != Contact::TYPE_COMMUNITY) {
1446 if ($parent['post-reason'] == self::PR_ANNOUNCEMENT) {
1447 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']]);
1451 if (Contact::isSharing($parent['owner-id'], $item['uid'])) {
1452 Logger::info('The resharer is no forum: quit', ['resharer' => $item['author-id'], 'owner' => $parent['owner-id'], 'author' => $parent['author-id'], 'uid' => $item['uid']]);
1457 self::update(['post-reason' => self::PR_ANNOUNCEMENT, 'causer-id' => $item['author-id']], ['id' => $parent['id']]);
1458 Logger::info('Set announcement post-reason', ['uri-id' => $item['uri-id'], 'thr-parent-id' => $item['thr-parent-id'], 'uid' => $item['uid']]);
1462 * Distribute the given item to users who subscribed to their tags
1464 * @param array $item Processed item
1466 private static function distributeByTags(array $item)
1468 if (($item['uid'] != 0) || ($item['gravity'] != self::GRAVITY_PARENT) || !in_array($item['network'], Protocol::FEDERATED)) {
1472 $uids = Tag::getUIDListByURIId($item['uri-id']);
1473 foreach ($uids as $uid) {
1474 $stored = self::storeForUserByUriId($item['uri-id'], $uid, ['post-reason' => self::PR_TAG]);
1475 Logger::info('Stored item for users', ['uri-id' => $item['uri-id'], 'uid' => $uid, 'stored' => $stored]);
1480 * Distributes public items to the receivers
1482 * @param integer $itemid Item ID that should be added
1483 * @param string $signed_text Original text (for Diaspora signatures), JSON encoded.
1484 * @throws \Exception
1486 public static function distribute(int $itemid, string $signed_text = '')
1488 $condition = ["`id` IN (SELECT `parent` FROM `post-user-view` WHERE `id` = ?)", $itemid];
1489 $parent = Post::selectFirst(['owner-id'], $condition);
1490 if (!DBA::isResult($parent)) {
1491 Logger::warning('Item not found', ['condition' => $condition]);
1495 // Only distribute public items from native networks
1496 $condition = ['id' => $itemid, 'uid' => 0,
1497 'network' => array_merge(Protocol::FEDERATED ,['']),
1498 'visible' => true, 'deleted' => false, 'private' => [self::PUBLIC, self::UNLISTED]];
1499 $item = Post::selectFirst(array_merge(self::ITEM_FIELDLIST, ['protocol']), $condition);
1500 if (!DBA::isResult($item)) {
1501 Logger::warning('Item not found', ['condition' => $condition]);
1505 $origin = $item['origin'];
1509 /// @todo add a field "pcid" in the contact table that refers to the public contact id.
1510 $owner = DBA::selectFirst('contact', ['url', 'nurl', 'alias'], ['id' => $parent['owner-id']]);
1511 if (!DBA::isResult($owner)) {
1515 $condition = ['nurl' => $owner['nurl'], 'rel' => [Contact::SHARING, Contact::FRIEND]];
1516 $contacts = DBA::select('contact', ['uid'], $condition);
1517 while ($contact = DBA::fetch($contacts)) {
1518 if ($contact['uid'] == 0) {
1522 $users[$contact['uid']] = $contact['uid'];
1524 DBA::close($contacts);
1526 $condition = ['alias' => $owner['url'], 'rel' => [Contact::SHARING, Contact::FRIEND]];
1527 $contacts = DBA::select('contact', ['uid'], $condition);
1528 while ($contact = DBA::fetch($contacts)) {
1529 if ($contact['uid'] == 0) {
1533 $users[$contact['uid']] = $contact['uid'];
1535 DBA::close($contacts);
1537 if (!empty($owner['alias'])) {
1538 $condition = ['nurl' => Strings::normaliseLink($owner['alias']), 'rel' => [Contact::SHARING, Contact::FRIEND]];
1539 $contacts = DBA::select('contact', ['uid'], $condition);
1540 while ($contact = DBA::fetch($contacts)) {
1541 if ($contact['uid'] == 0) {
1545 $users[$contact['uid']] = $contact['uid'];
1547 DBA::close($contacts);
1552 if ($item['uri-id'] != $item['parent-uri-id']) {
1553 $parents = Post::select(['uid', 'origin'], ["`uri-id` = ? AND `uid` != 0", $item['parent-uri-id']]);
1554 while ($parent = Post::fetch($parents)) {
1555 $users[$parent['uid']] = $parent['uid'];
1556 if ($parent['origin'] && !$origin) {
1557 $origin_uid = $parent['uid'];
1560 DBA::close($parents);
1563 foreach ($users as $uid) {
1564 if ($origin_uid == $uid) {
1565 $item['diaspora_signed_text'] = $signed_text;
1567 $item['post-reason'] = self::PR_DISTRIBUTE;
1568 self::storeForUser($item, $uid);
1573 * Store a public item defined by their URI-ID for the given users
1575 * @param integer $uri_id URI-ID of the given item
1576 * @param integer $uid The user that will receive the item entry
1577 * @param array $fields Additional fields to be stored
1578 * @param integer $source_uid User id of the source post
1579 * @return integer stored item id
1581 public static function storeForUserByUriId(int $uri_id, int $uid, array $fields = [], int $source_uid = 0): int
1583 if ($uid == $source_uid) {
1584 Logger::warning('target UID must not be be equal to the source UID', ['uri-id' => $uri_id, 'uid' => $uid]);
1588 $item = Post::selectFirst(array_merge(self::ITEM_FIELDLIST, ['protocol']), ['uri-id' => $uri_id, 'uid' => $source_uid]);
1589 if (!DBA::isResult($item)) {
1590 Logger::warning('Item could not be fetched', ['uri-id' => $uri_id, 'uid' => $source_uid]);
1594 if (($uid != 0) && ($item['gravity'] == self::GRAVITY_PARENT)) {
1595 $owner = User::getOwnerDataById($uid);
1596 if (($owner['contact-type'] == User::ACCOUNT_TYPE_COMMUNITY) && !Tag::isMentioned($uri_id, $owner['url'])) {
1597 Logger::info('Target user is a forum but is not mentioned here, thread will not be stored', ['uid' => $uid, 'uri-id' => $uri_id]);
1602 if (($source_uid == 0) && (($item['private'] == self::PRIVATE) || !in_array($item['network'], Protocol::FEDERATED))) {
1603 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']]);
1607 $item['post-reason'] = self::PR_STORED;
1609 $item = array_merge($item, $fields);
1611 if (($uid != 0) && Contact::isSharing(($item['gravity'] == Item::GRAVITY_PARENT) ? $item['owner-id'] : $item['author-id'], $uid)) {
1612 $item['post-reason'] = self::PR_FOLLOWER;
1615 $is_reshare = ($item['gravity'] == self::GRAVITY_ACTIVITY) && ($item['verb'] == Activity::ANNOUNCE);
1617 if (($uid != 0) && (($item['gravity'] == self::GRAVITY_PARENT) || $is_reshare) &&
1618 DI::pConfig()->get($uid, 'system', 'accept_only_sharer') == self::COMPLETION_NONE &&
1619 !in_array($item['post-reason'], [self::PR_FOLLOWER, self::PR_TAG, self::PR_TO, self::PR_CC, self::PR_ACTIVITY])) {
1620 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']]);
1624 $causer = $item['causer-id'] ?: $item['author-id'];
1626 if (($uri_id != $item['parent-uri-id']) && ($item['gravity'] == self::GRAVITY_COMMENT) && !Post::exists(['uri-id' => $item['parent-uri-id'], 'uid' => $uid])) {
1627 if (!self::fetchParent($item['parent-uri-id'], $uid, $causer)) {
1628 Logger::info('Parent post had not been added', ['uri-id' => $item['parent-uri-id'], 'uid' => $uid, 'causer' => $causer]);
1631 Logger::info('Fetched parent post', ['uri-id' => $item['parent-uri-id'], 'uid' => $uid, 'causer' => $causer]);
1632 } elseif (($uri_id != $item['thr-parent-id']) && $is_reshare && !Post::exists(['uri-id' => $item['thr-parent-id'], 'uid' => $uid])) {
1633 if (!self::fetchParent($item['thr-parent-id'], $uid, $causer)) {
1634 Logger::info('Thread parent had not been added', ['uri-id' => $item['thr-parent-id'], 'uid' => $uid, 'causer' => $causer]);
1637 Logger::info('Fetched thread parent', ['uri-id' => $item['thr-parent-id'], 'uid' => $uid, 'causer' => $causer]);
1640 $stored = self::storeForUser($item, $uid);
1641 Logger::info('Item stored for user', ['uri-id' => $item['uri-id'], 'uid' => $uid, 'causer' => $causer, 'source-uid' => $source_uid, 'stored' => $stored]);
1646 * Fetch the parent with the given uri-id
1648 * @param integer $uri_id
1649 * @param integer $uid
1650 * @param integer $causer
1654 private static function fetchParent(int $uri_id, int $uid, int $causer): int
1656 // Fetch the origin user for the post
1657 $origin_uid = self::GetOriginUidForUriId($uri_id, $uid);
1658 if (is_null($origin_uid)) {
1659 Logger::info('Origin item was not found', ['uid' => $uid, 'uri-id' => $uri_id]);
1663 return self::storeForUserByUriId($uri_id, $uid, ['causer-id' => $causer, 'post-reason' => self::PR_FETCHED], $origin_uid);
1667 * Returns the origin uid of a post if the given user is allowed to see it.
1673 private static function GetOriginUidForUriId(int $uriid, int $uid)
1675 if (Post::exists(['uri-id' => $uriid, 'uid' => $uid])) {
1679 $post = Post::selectFirst(['uid', 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid', 'private'], ['uri-id' => $uriid, 'origin' => true]);
1680 if (!empty($post)) {
1681 if (in_array($post['private'], [Item::PUBLIC, Item::UNLISTED])) {
1682 return $post['uid'];
1685 $pcid = Contact::getPublicIdByUserId($uid);
1690 foreach (Item::enumeratePermissions($post, true) as $receiver) {
1691 if ($receiver == $pcid) {
1692 return $post['uid'];
1699 if (Post::exists(['uri-id' => $uriid, 'uid' => 0])) {
1703 // When the post belongs to a a forum then all forum users are allowed to access it
1704 foreach (Tag::getByURIId($uriid, [Tag::MENTION, Tag::EXCLUSIVE_MENTION]) as $tag) {
1705 if (DBA::exists('contact', ['uid' => $uid, 'nurl' => Strings::normaliseLink($tag['url']), 'contact-type' => Contact::TYPE_COMMUNITY])) {
1706 $target_uid = User::getIdForURL($tag['url']);
1707 if (!empty($target_uid)) {
1717 * Store a public item array for the given users
1719 * @param array $item The item entry that will be stored
1720 * @param integer $uid The user that will receive the item entry
1721 * @return integer stored item id
1722 * @throws \Exception
1724 private static function storeForUser(array $item, int $uid): int
1726 $post = Post::selectFirst(['id'], ['uri-id' => $item['uri-id'], 'uid' => $uid]);
1727 if (!empty($post['id'])) {
1728 if (!empty($item['event-id'])) {
1729 $event_post = Post::selectFirst(['event-id'], ['uri-id' => $item['uri-id'], 'uid' => $uid]);
1730 if (!empty($event_post['event-id'])) {
1731 $event = DBA::selectFirst('event', ['edited', 'start', 'finish', 'summary', 'desc', 'location', 'nofinish'], ['id' => $item['event-id']]);
1732 if (!empty($event)) {
1733 // We aren't using "Event::store" here, since we don't want to trigger any further action
1734 $ret = DBA::update('event', $event, ['id' => $event_post['event-id']]);
1735 Logger::info('Event updated', ['uid' => $uid, 'source-event' => $item['event-id'], 'target-event' => $event_post['event-id'], 'ret' => $ret]);
1739 Logger::info('Item already exists', ['uri-id' => $item['uri-id'], 'uid' => $uid, 'id' => $post['id']]);
1743 // Data from the "post-user" table
1745 unset($item['mention']);
1746 unset($item['starred']);
1747 unset($item['unseen']);
1748 unset($item['psid']);
1749 unset($item['pinned']);
1750 unset($item['ignored']);
1751 unset($item['pubmail']);
1752 unset($item['event-id']);
1753 unset($item['hidden']);
1754 unset($item['notification-type']);
1756 // Data from the "post-delivery-data" table
1757 unset($item['postopts']);
1758 unset($item['inform']);
1760 $item['uid'] = $uid;
1761 $item['origin'] = 0;
1765 if ($item['gravity'] == self::GRAVITY_PARENT) {
1766 $contact = DBA::selectFirst('contact', [], ['id' => $item['contact-id'], 'self' => false]);
1767 if (DBA::isResult($contact)) {
1768 $notify = self::isRemoteSelf($contact, $item);
1769 $item['wall'] = (bool)$notify;
1773 $item['contact-id'] = self::contactId($item);
1774 $distributed = self::insert($item, $notify);
1776 if (!$distributed) {
1777 Logger::info("Distributed item wasn't stored", ['uri-id' => $item['uri-id'], 'user' => $uid]);
1779 Logger::info('Distributed item was stored', ['uri-id' => $item['uri-id'], 'user' => $uid, 'stored' => $distributed]);
1781 return $distributed;
1785 * Add a shadow entry for a given item id that is a thread starter
1787 * We store every public item entry additionally with the user id "0".
1788 * This is used for the community page and for the search.
1789 * It is planned that in the future we will store public item entries only once.
1791 * @param integer $itemid Item ID that should be added
1792 * @throws \Exception
1794 private static function addShadow(int $itemid)
1796 $fields = ['uid', 'private', 'visible', 'deleted', 'network', 'uri-id'];
1797 $condition = ['id' => $itemid, 'gravity' => self::GRAVITY_PARENT];
1798 $item = Post::selectFirst($fields, $condition);
1800 if (!DBA::isResult($item)) {
1804 // is it already a copy?
1805 if (($itemid == 0) || ($item['uid'] == 0)) {
1809 // Is it a visible public post?
1810 if (!$item["visible"] || $item["deleted"] || ($item["private"] == self::PRIVATE)) {
1814 // is it an entry from a connector? Only add an entry for natively connected networks
1815 if (!in_array($item["network"], array_merge(Protocol::FEDERATED ,['']))) {
1819 if (Post::exists(['uri-id' => $item['uri-id'], 'uid' => 0])) {
1823 $item = Post::selectFirst(array_merge(self::ITEM_FIELDLIST, ['protocol']), ['id' => $itemid]);
1825 if (DBA::isResult($item)) {
1826 // Preparing public shadow (removing user specific data)
1829 unset($item['parent']);
1830 unset($item['wall']);
1831 unset($item['mention']);
1832 unset($item['origin']);
1833 unset($item['starred']);
1834 unset($item['postopts']);
1835 unset($item['inform']);
1836 unset($item['post-reason']);
1837 if ($item['uri-id'] == $item['parent-uri-id']) {
1838 $item['contact-id'] = $item['owner-id'];
1840 $item['contact-id'] = $item['author-id'];
1843 $public_shadow = self::insert($item);
1845 Logger::info('Stored public shadow', ['thread' => $itemid, 'id' => $public_shadow]);
1850 * Add a shadow entry for a given item id that is a comment
1852 * This function does the same like the function above - but for comments
1854 * @param integer $itemid Item ID that should be added
1855 * @throws \Exception
1857 private static function addShadowPost(int $itemid)
1859 $item = Post::selectFirst(array_merge(self::ITEM_FIELDLIST, ['protocol']), ['id' => $itemid]);
1860 if (!DBA::isResult($item)) {
1864 // Is it a toplevel post?
1865 if ($item['gravity'] == self::GRAVITY_PARENT) {
1866 self::addShadow($itemid);
1870 // Is this a shadow entry?
1871 if ($item['uid'] == 0) {
1875 // Is there a shadow parent?
1876 if (!Post::exists(['uri-id' => $item['parent-uri-id'], 'uid' => 0])) {
1880 // Is there already a shadow entry?
1881 if (Post::exists(['uri-id' => $item['uri-id'], 'uid' => 0])) {
1885 // Save "origin" and "parent" state
1886 $origin = $item['origin'];
1887 $parent = $item['parent'];
1889 // Preparing public shadow (removing user specific data)
1892 unset($item['parent']);
1893 unset($item['wall']);
1894 unset($item['mention']);
1895 unset($item['origin']);
1896 unset($item['starred']);
1897 unset($item['postopts']);
1898 unset($item['inform']);
1899 unset($item['post-reason']);
1900 $item['contact-id'] = Contact::getIdForURL($item['author-link']);
1902 $public_shadow = self::insert($item);
1904 Logger::info('Stored public shadow', ['uri-id' => $item['uri-id'], 'id' => $public_shadow]);
1906 // If this was a comment to a Diaspora post we don't get our comment back.
1907 // This means that we have to distribute the comment by ourselves.
1908 if ($origin && Post::exists(['id' => $parent, 'network' => Protocol::DIASPORA])) {
1909 self::distribute($public_shadow);
1914 * Adds a language specification in a "language" element of given $arr.
1915 * Expects "body" element to exist in $arr.
1917 * @param array $item
1918 * @return string detected language
1919 * @throws \Text_LanguageDetect_Exception
1921 private static function getLanguage(array $item): string
1923 if (!empty($item['language'])) {
1924 return $item['language'];
1927 if (!in_array($item['gravity'], [self::GRAVITY_PARENT, self::GRAVITY_COMMENT]) || empty($item['body'])) {
1931 $languages = self::getLanguageArray(trim($item['title'] . "\n" . $item['body']), 3);
1932 if (empty($languages)) {
1936 return json_encode($languages);
1940 * Get a language array from a given text
1942 * @param string $body
1943 * @param integer $count
1946 public static function getLanguageArray(string $body, int $count): array
1948 // Convert attachments to links
1949 $naked_body = BBCode::removeAttachment($body);
1950 if (empty($naked_body)) {
1954 // Remove links and pictures
1955 $naked_body = BBCode::removeLinks($naked_body);
1957 // Convert the title and the body to plain text
1958 $naked_body = BBCode::toPlaintext($naked_body);
1960 // Remove possibly remaining links
1961 $naked_body = preg_replace(Strings::autoLinkRegEx(), '', $naked_body);
1963 if (empty($naked_body)) {
1967 $naked_body = self::getDominantLanguage($naked_body);
1969 $availableLanguages = DI::l10n()->getAvailableLanguages();
1970 // See https://github.com/friendica/friendica/issues/10511
1971 // Persian is manually added to language detection until a persian translation is provided for the interface, at
1972 // which point it will be automatically available through `getAvailableLanguages()` and this should be removed.
1973 $availableLanguages['fa'] = 'fa';
1975 $ld = new Language(array_keys($availableLanguages));
1976 return $ld->detect($naked_body)->limit(0, $count)->close() ?: [];
1980 * Check if latin or non latin are dominant in the body and only return the dominant one
1982 * @param string $body
1985 private static function getDominantLanguage(string $body): string
1989 for ($i = 0; $i < mb_strlen($body); $i++) {
1990 $character = mb_substr($body, $i, 1);
1991 $ord = mb_ord($character);
1993 // We add the most common characters to both strings.
1994 if (($ord <= 64) || ($ord >= 91 && $ord <= 96) || ($ord >= 123 && $ord <= 191) || in_array($ord, [215, 247]) || ($ord >= 697 && $ord <= 735) || ($ord > 65535)) {
1995 $latin .= $character;
1996 $non_latin .= $character;
1997 } elseif ($ord < 768) {
1998 $latin .= $character;
2000 $non_latin .= $character;
2003 return (mb_strlen($latin) > mb_strlen($non_latin)) ? $latin : $non_latin;
2006 public static function getLanguageMessage(array $item): string
2008 $iso639 = new \Matriphe\ISO639\ISO639;
2010 $used_languages = '';
2011 foreach (json_decode($item['language'], true) as $language => $reliability) {
2012 $used_languages .= $iso639->languageByCode1($language) . ' (' . $language . "): " . number_format($reliability, 5) . '\n';
2014 $used_languages = DI::l10n()->t('Detected languages in this post:\n%s', $used_languages);
2015 return $used_languages;
2019 * Creates an unique guid out of a given uri.
2020 * This function is used for messages outside the fediverse (Connector posts, feeds, Mails, ...)
2021 * Posts that are created on this system are using System::createUUID.
2022 * Received ActivityPub posts are using Processor::getGUIDByURL.
2024 * @param string $uri uri of an item entry
2025 * @param string|null $host hostname for the GUID prefix
2026 * @return string Unique guid
2027 * @throws \Exception
2029 public static function guidFromUri(string $uri, string $host = null): string
2031 // Our regular guid routine is using this kind of prefix as well
2032 // We have to avoid that different routines could accidentally create the same value
2033 $parsed = parse_url($uri);
2035 // Remove the scheme to make sure that "https" and "http" doesn't make a difference
2036 unset($parsed['scheme']);
2038 $hostPart = $host ?? $parsed['host'] ?? '';
2040 Logger::warning('Empty host GUID part', ['uri' => $uri, 'host' => $host, 'parsed' => $parsed, 'callstack' => System::callstack(10)]);
2043 // Glue it together to be able to make a hash from it
2044 $host_id = implode('/', $parsed);
2046 // Use a mixture of several hashes to provide some GUID like experience
2047 return hash('crc32', $hostPart) . '-' . hash('joaat', $host_id) . '-' . hash('fnv164', $host_id);
2051 * generate an unique URI
2053 * @param string $guid An existing GUID (Otherwise it will be generated)
2056 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2058 public static function newURI(string $guid = ''): string
2061 $guid = System::createUUID();
2064 return DI::baseUrl() . '/objects/' . $guid;
2068 * Set "success_update" and "last-item" to the date of the last time we heard from this contact
2070 * This can be used to filter for inactive contacts.
2071 * Only do this for public postings to avoid privacy problems, since poco data is public.
2072 * Don't set this value if it isn't from the owner (could be an author that we don't know)
2074 * @param array $arr Contains the just posted item record
2075 * @throws \Exception
2077 private static function updateContact(array $arr)
2079 // Unarchive the author
2080 $contact = DBA::selectFirst('contact', [], ['id' => $arr["author-id"]]);
2081 if (DBA::isResult($contact)) {
2082 Contact::unmarkForArchival($contact);
2085 // Unarchive the contact if it's not our own contact
2086 $contact = DBA::selectFirst('contact', [], ['id' => $arr["contact-id"], 'self' => false]);
2087 if (DBA::isResult($contact)) {
2088 Contact::unmarkForArchival($contact);
2091 /// @todo On private posts we could obfuscate the date
2092 $update = ($arr['private'] != self::PRIVATE) || in_array($arr['network'], Protocol::FEDERATED);
2094 // Is it a forum? Then we don't care about the rules from above
2095 if (!$update && in_array($arr["network"], [Protocol::ACTIVITYPUB, Protocol::DFRN]) && ($arr["parent-uri-id"] === $arr["uri-id"])) {
2096 if (DBA::exists('contact', ['id' => $arr['contact-id'], 'forum' => true])) {
2102 // The "self" contact id is used (for example in the connectors) when the contact is unknown
2103 // So we have to ensure to only update the last item when it had been our own post,
2104 // or it had been done by a "regular" contact.
2105 if (!empty($arr['wall'])) {
2106 $condition = ['id' => $arr['contact-id']];
2108 $condition = ['id' => $arr['contact-id'], 'self' => false];
2110 Contact::update(['failed' => false, 'local-data' => true, 'success_update' => $arr['received'], 'last-item' => $arr['received']], $condition);
2112 // Now do the same for the system wide contacts with uid=0
2113 if ($arr['private'] != self::PRIVATE) {
2114 Contact::update(['failed' => false, 'local-data' => true, 'success_update' => $arr['received'], 'last-item' => $arr['received']],
2115 ['id' => $arr['owner-id']]);
2117 if ($arr['owner-id'] != $arr['author-id']) {
2118 Contact::update(['failed' => false, 'local-data' => true, 'success_update' => $arr['received'], 'last-item' => $arr['received']],
2119 ['id' => $arr['author-id']]);
2124 public static function setHashtags(string $body): string
2126 $body = BBCode::performWithEscapedTags($body, ['noparse', 'pre', 'code', 'img'], function ($body) {
2127 $tags = BBCode::getTags($body);
2130 if (!count($tags)) {
2134 // This sorting is important when there are hashtags that are part of other hashtags
2135 // Otherwise there could be problems with hashtags like #test and #test2
2136 // Because of this we are sorting from the longest to the shortest tag.
2137 usort($tags, function ($a, $b) {
2138 return strlen($b) <=> strlen($a);
2141 $URLSearchString = "^\[\]";
2143 // All hashtags should point to the home server if "local_tags" is activated
2144 if (DI::config()->get('system', 'local_tags')) {
2145 $body = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
2146 "#[url=" . DI::baseUrl() . "/search?tag=$2]$2[/url]", $body);
2149 // mask hashtags inside of url, bookmarks and attachments to avoid urls in urls
2150 $body = preg_replace_callback("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
2152 return ("[url=" . str_replace("#", "#", $match[1]) . "]" . str_replace("#", "#", $match[2]) . "[/url]");
2155 $body = preg_replace_callback("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism",
2157 return ("[bookmark=" . str_replace("#", "#", $match[1]) . "]" . str_replace("#", "#", $match[2]) . "[/bookmark]");
2160 $body = preg_replace_callback("/\[attachment (.*?)\](.*?)\[\/attachment\]/ism",
2162 return ("[attachment " . str_replace("#", "#", $match[1]) . "]" . $match[2] . "[/attachment]");
2165 // Repair recursive urls
2166 $body = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
2169 foreach ($tags as $tag) {
2170 if ((strpos($tag, '#') !== 0) || strpos($tag, '[url=') || strlen($tag) < 2 || $tag[1] == '#') {
2174 $basetag = str_replace('_', ' ', substr($tag, 1));
2175 $newtag = '#[url=' . DI::baseUrl() . '/search?tag=' . $basetag . ']' . $basetag . '[/url]';
2177 $body = str_replace($tag, $newtag, $body);
2180 // Convert back the masked hashtags
2181 $body = str_replace("#", "#", $body);
2190 * look for mention tags and setup a second delivery chain for forum/community posts if appropriate
2193 * @param int $item_id
2194 * @return boolean true if item was deleted, else false
2195 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2196 * @throws \ImagickException
2198 private static function tagDeliver(int $uid, int $item_id): bool
2202 $owner = User::getOwnerDataById($uid);
2203 if (!DBA::isResult($owner)) {
2204 Logger::warning('User not found, quitting here.', ['uid' => $uid]);
2208 if ($owner['contact-type'] != User::ACCOUNT_TYPE_COMMUNITY) {
2209 Logger::debug('Owner is no community, quitting here.', ['uid' => $uid, 'id' => $item_id]);
2213 $item = Post::selectFirst(self::ITEM_FIELDLIST, ['id' => $item_id, 'gravity' => [self::GRAVITY_PARENT, self::GRAVITY_COMMENT], 'origin' => false]);
2214 if (!DBA::isResult($item)) {
2215 Logger::debug('Post is an activity or origin or not found at all, quitting here.', ['id' => $item_id]);
2219 if ($item['gravity'] == self::GRAVITY_PARENT) {
2220 if (Tag::isMentioned($item['uri-id'], $owner['url'])) {
2221 Logger::info('Mention found in tag.', ['uri' => $item['uri'], 'uid' => $uid, 'id' => $item_id, 'uri-id' => $item['uri-id'], 'guid' => $item['guid']]);
2223 Logger::info('Top-level post without mention is deleted.', ['uri' => $item['uri'], $uid, 'id' => $item_id, 'uri-id' => $item['uri-id'], 'guid' => $item['guid']]);
2224 Post\User::delete(['uri-id' => $item['uri-id'], 'uid' => $item['uid']]);
2228 $arr = ['item' => $item, 'user' => $owner];
2230 Hook::callAll('tagged', $arr);
2232 if (Tag::isMentioned($item['parent-uri-id'], $owner['url'])) {
2233 Logger::info('Mention found in parent tag.', ['uri' => $item['uri'], 'uid' => $uid, 'id' => $item_id, 'uri-id' => $item['uri-id'], 'guid' => $item['guid']]);
2235 Logger::debug('No mentions found in parent, quitting here.', ['id' => $item_id, 'uri-id' => $item['uri-id'], 'guid' => $item['guid']]);
2240 Logger::info('Community post will be distributed', ['uri' => $item['uri'], 'uid' => $uid, 'id' => $item_id, 'uri-id' => $item['uri-id'], 'guid' => $item['guid']]);
2242 if ($owner['page-flags'] == User::PAGE_FLAGS_PRVGROUP) {
2244 $allow_gid = '<' . Group::FOLLOWERS . '>';
2247 self::performActivity($item['id'], 'announce', $uid, $allow_cid, $allow_gid, $deny_cid, $deny_gid);
2249 self::performActivity($item['id'], 'announce', $uid);
2252 Logger::info('Community post had been distributed', ['uri' => $item['uri'], 'uid' => $uid, 'id' => $item_id, 'uri-id' => $item['uri-id'], 'guid' => $item['guid']]);
2257 * Automatically reshare the item if the "remote_self" option is selected
2259 * @param array $item
2262 private static function autoReshare(array $item)
2264 if ($item['gravity'] != self::GRAVITY_PARENT) {
2268 $cdata = Contact::getPublicAndUserContactID($item['author-id'], $item['uid']);
2269 if (empty($cdata['user']) || ($cdata['user'] != $item['contact-id'])) {
2273 $cdata = Contact::getPublicAndUserContactID($item['author-id'], $item['uid']);
2274 if (empty($cdata['user']) || ($cdata['user'] != $item['contact-id'])) {
2278 if (!DBA::exists('contact', ['id' => $cdata['user'], 'remote_self' => Contact::MIRROR_NATIVE_RESHARE])) {
2282 if (!in_array($item['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN])) {
2286 Logger::info('Automatically reshare item', ['uid' => $item['uid'], 'id' => $item['id'], 'guid' => $item['guid'], 'uri-id' => $item['uri-id']]);
2288 self::performActivity($item['id'], 'announce', $item['uid']);
2291 public static function isRemoteSelf(array $contact, array &$datarray): bool
2293 if ($contact['remote_self'] != Contact::MIRROR_OWN_POST) {
2297 // Prevent the forwarding of posts that are forwarded
2298 if (!empty($datarray['extid']) && ($datarray['extid'] == Protocol::DFRN)) {
2299 Logger::info('Already forwarded');
2303 // Prevent to forward already forwarded posts
2304 if ($datarray['app'] == DI::baseUrl()->getHost()) {
2305 Logger::info('Already forwarded (second test)');
2309 // Only forward posts
2310 if ($datarray['verb'] != Activity::POST) {
2311 Logger::info('No post');
2315 if (($contact['network'] != Protocol::FEED) && ($datarray['private'] == self::PRIVATE)) {
2316 Logger::info('Not public');
2320 $datarray2 = $datarray;
2321 Logger::info('remote-self start', ['contact' => $contact['url'], 'remote_self'=> $contact['remote_self'], 'item' => $datarray]);
2323 $self = DBA::selectFirst('contact', ['id', 'name', 'url', 'thumb'],
2324 ['uid' => $contact['uid'], 'self' => true]);
2325 if (!DBA::isResult($self)) {
2326 Logger::error('Self contact not found', ['uid' => $contact['uid']]);
2330 $datarray['contact-id'] = $self['id'];
2332 $datarray['author-name'] = $datarray['owner-name'] = $self['name'];
2333 $datarray['author-link'] = $datarray['owner-link'] = $self['url'];
2334 $datarray['author-avatar'] = $datarray['owner-avatar'] = $self['thumb'];
2336 unset($datarray['edited']);
2338 unset($datarray['network']);
2339 unset($datarray['owner-id']);
2340 unset($datarray['author-id']);
2342 if ($contact['network'] != Protocol::FEED) {
2343 $old_uri_id = $datarray['uri-id'] ?? 0;
2344 $datarray['guid'] = System::createUUID();
2345 unset($datarray['plink']);
2346 $datarray['uri'] = self::newURI($datarray['guid']);
2347 $datarray['uri-id'] = ItemURI::getIdByURI($datarray['uri']);
2348 $datarray['extid'] = Protocol::DFRN;
2349 $urlpart = parse_url($datarray2['author-link']);
2350 $datarray['app'] = $urlpart['host'];
2351 if (!empty($old_uri_id)) {
2352 Post\Media::copy($old_uri_id, $datarray['uri-id']);
2355 unset($datarray['parent-uri']);
2356 unset($datarray['thr-parent']);
2358 // Store the original post
2359 $result = self::insert($datarray2);
2360 Logger::info('remote-self post original item', ['contact' => $contact['url'], 'result'=> $result, 'item' => $datarray2]);
2362 $datarray['private'] = self::PUBLIC;
2363 $datarray['app'] = 'Feed';
2367 return (bool)$result;
2374 * @param array $item
2377 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2378 * @throws \ImagickException
2380 public static function fixPrivatePhotos(string $s, int $uid, array $item = null, int $cid = 0): string
2382 if (DI::config()->get('system', 'disable_embedded')) {
2386 Logger::info('check for photos');
2387 $site = substr(DI::baseUrl(), strpos(DI::baseUrl(), '://'));
2392 $img_start = strpos($orig_body, '[img');
2393 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
2394 $img_len = ($img_start !== false ? strpos(substr($orig_body, $img_start + $img_st_close + 1), '[/img]') : false);
2396 while (($img_st_close !== false) && ($img_len !== false)) {
2397 $img_st_close++; // make it point to AFTER the closing bracket
2398 $image = substr($orig_body, $img_start + $img_st_close, $img_len);
2400 Logger::info('found photo', ['image' => $image]);
2402 if (stristr($image, $site . '/photo/')) {
2403 // Only embed locally hosted photos
2405 $i = basename($image);
2406 $i = str_replace(['.jpg', '.png', '.gif'], ['', '', ''], $i);
2407 $x = strpos($i, '-');
2410 $res = substr($i, $x + 1);
2411 $i = substr($i, 0, $x);
2412 $photo = Photo::getPhotoForUser($uid, $i, $res);
2413 if (DBA::isResult($photo)) {
2415 * Check to see if we should replace this photo link with an embedded image
2416 * 1. No need to do so if the photo is public
2417 * 2. If there's a contact-id provided, see if they're in the access list
2418 * for the photo. If so, embed it.
2419 * 3. Otherwise, if we have an item, see if the item permissions match the photo
2420 * permissions, regardless of order but first check to see if they're an exact
2421 * match to save some processing overhead.
2423 if (self::hasPermissions($photo)) {
2425 $recips = self::enumeratePermissions($photo);
2426 if (in_array($cid, $recips)) {
2430 if (self::samePermissions($uid, $item, $photo)) {
2436 $photo_img = Photo::getImageForPhoto($photo);
2437 // If a custom width and height were specified, apply before embedding
2438 if (preg_match("/\[img\=([0-9]*)x([0-9]*)\]/is", substr($orig_body, $img_start, $img_st_close), $match)) {
2439 Logger::info('scaling photo');
2441 $width = intval($match[1]);
2442 $height = intval($match[2]);
2444 $photo_img->scaleDown(max($width, $height));
2447 $data = $photo_img->asString();
2448 $type = $photo_img->getType();
2450 Logger::info('replacing photo');
2451 $image = 'data:' . $type . ';base64,' . base64_encode($data);
2452 Logger::debug('replaced', ['image' => $image]);
2458 $new_body = $new_body . substr($orig_body, 0, $img_start + $img_st_close) . $image . '[/img]';
2459 $orig_body = substr($orig_body, $img_start + $img_st_close + $img_len + strlen('[/img]'));
2460 if ($orig_body === false) {
2464 $img_start = strpos($orig_body, '[img');
2465 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
2466 $img_len = ($img_start !== false ? strpos(substr($orig_body, $img_start + $img_st_close + 1), '[/img]') : false);
2469 $new_body = $new_body . $orig_body;
2474 private static function hasPermissions(array $obj)
2476 return !empty($obj['allow_cid']) || !empty($obj['allow_gid']) ||
2477 !empty($obj['deny_cid']) || !empty($obj['deny_gid']);
2480 // @TODO $uid is unused parameter
2481 private static function samePermissions($uid, array $obj1, array $obj2): bool
2483 // first part is easy. Check that these are exactly the same.
2484 if (($obj1['allow_cid'] == $obj2['allow_cid'])
2485 && ($obj1['allow_gid'] == $obj2['allow_gid'])
2486 && ($obj1['deny_cid'] == $obj2['deny_cid'])
2487 && ($obj1['deny_gid'] == $obj2['deny_gid'])) {
2491 // This is harder. Parse all the permissions and compare the resulting set.
2492 $recipients1 = self::enumeratePermissions($obj1);
2493 $recipients2 = self::enumeratePermissions($obj2);
2497 /// @TODO Comparison of arrays, maybe use array_diff_assoc() here?
2498 return ($recipients1 == $recipients2);
2502 * Returns an array of contact-ids that are allowed to see this object
2504 * @param array $obj Item array with at least uid, allow_cid, allow_gid, deny_cid and deny_gid
2505 * @param bool $check_dead Prunes unavailable contacts from the result
2507 * @throws \Exception
2509 public static function enumeratePermissions(array $obj, bool $check_dead = false): array
2511 $aclFormatter = DI::aclFormatter();
2513 $allow_people = $aclFormatter->expand($obj['allow_cid']);
2514 $allow_groups = Group::expand($obj['uid'], $aclFormatter->expand($obj['allow_gid']), $check_dead);
2515 $deny_people = $aclFormatter->expand($obj['deny_cid']);
2516 $deny_groups = Group::expand($obj['uid'], $aclFormatter->expand($obj['deny_gid']), $check_dead);
2517 $recipients = array_unique(array_merge($allow_people, $allow_groups));
2518 $deny = array_unique(array_merge($deny_people, $deny_groups));
2519 $recipients = array_diff($recipients, $deny);
2523 public static function expire(int $uid, int $days, string $network = "", bool $force = false)
2525 if (!$uid || ($days < 1)) {
2529 $condition = ["`uid` = ? AND NOT `deleted` AND `gravity` = ?",
2530 $uid, self::GRAVITY_PARENT];
2533 * $expire_network_only = save your own wall posts
2534 * and just expire conversations started by others
2536 $expire_network_only = DI::pConfig()->get($uid, 'expire', 'network_only', false);
2538 if ($expire_network_only) {
2539 $condition[0] .= " AND NOT `wall`";
2542 if ($network != "") {
2543 $condition[0] .= " AND `network` = ?";
2544 $condition[] = $network;
2547 $condition[0] .= " AND `received` < ?";
2548 $condition[] = DateTimeFormat::utc('now - ' . $days . ' day');
2550 $items = Post::select(['resource-id', 'starred', 'id', 'post-type', 'uid', 'uri-id'], $condition);
2552 if (!DBA::isResult($items)) {
2556 $expire_items = (bool)DI::pConfig()->get($uid, 'expire', 'items', true);
2558 // Forcing expiring of items - but not notes and marked items
2560 $expire_items = true;
2563 $expire_notes = (bool)DI::pConfig()->get($uid, 'expire', 'notes', true);
2564 $expire_starred = (bool)DI::pConfig()->get($uid, 'expire', 'starred', true);
2565 $expire_photos = (bool)DI::pConfig()->get($uid, 'expire', 'photos', false);
2569 $priority = DI::config()->get('system', 'expire-notify-priority');
2571 while ($item = Post::fetch($items)) {
2572 // don't expire filed items
2573 if (DBA::exists('post-category', ['uri-id' => $item['uri-id'], 'uid' => $item['uid'], 'type' => Post\Category::FILE])) {
2577 // Only expire posts, not photos and photo comments
2579 if (!$expire_photos && !empty($item['resource-id'])) {
2581 } elseif (!$expire_starred && intval($item['starred'])) {
2583 } elseif (!$expire_notes && ($item['post-type'] == self::PT_PERSONAL_NOTE)) {
2585 } elseif (!$expire_items && ($item['post-type'] != self::PT_PERSONAL_NOTE)) {
2589 self::markForDeletionById($item['id'], $priority);
2594 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]);
2597 public static function firstPostDate(int $uid, bool $wall = false)
2599 $user = User::getById($uid, ['register_date']);
2604 $condition = ["`uid` = ? AND `wall` = ? AND NOT `deleted` AND `visible` AND `received` >= ?",
2605 $uid, $wall, $user['register_date']];
2606 $params = ['order' => ['received' => false]];
2607 $thread = Post::selectFirstThread(['received'], $condition, $params);
2608 if (DBA::isResult($thread)) {
2609 $postdate = substr(DateTimeFormat::local($thread['received']), 0, 10);
2616 * add/remove activity to an item
2618 * Toggle activities as like,dislike,attend of an item
2620 * @param int $item_id
2621 * @param string $verb
2622 * Activity verb. One of
2623 * like, unlike, dislike, undislike, attendyes, unattendyes,
2624 * attendno, unattendno, attendmaybe, unattendmaybe,
2625 * announce, unannounce
2627 * @param string $allow_cid
2628 * @param string $allow_gid
2629 * @param string $deny_cid
2630 * @param string $deny_gid
2632 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2633 * @throws \ImagickException
2634 * @hook 'post_local_end'
2636 * 'post_id' => ID of posted item
2638 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
2644 Logger::notice('Start create activity', ['verb' => $verb, 'item' => $item_id, 'user' => $uid]);
2646 $item = Post::selectFirst(self::ITEM_FIELDLIST, ['id' => $item_id]);
2647 if (!DBA::isResult($item)) {
2648 Logger::warning('Post had not been fetched', ['id' => $item_id]);
2652 $uri_id = $item['uri-id'];
2654 if (!in_array($item['uid'], [0, $uid])) {
2658 if (!Post::exists(['uri-id' => $item['parent-uri-id'], 'uid' => $uid])) {
2659 $stored = self::storeForUserByUriId($item['parent-uri-id'], $uid, ['post-reason' => Item::PR_ACTIVITY]);
2660 if (($item['parent-uri-id'] == $item['uri-id']) && !empty($stored)) {
2661 $item = Post::selectFirst(self::ITEM_FIELDLIST, ['id' => $stored]);
2662 if (!DBA::isResult($item)) {
2663 Logger::info('Could not fetch just created item - should not happen', ['stored' => $stored, 'uid' => $uid, 'uri-id' => $uri_id]);
2669 // Retrieves the local post owner
2670 $owner = User::getOwnerDataById($uid);
2671 if (empty($owner)) {
2672 Logger::info('Empty owner for user', ['uid' => $uid]);
2676 // Retrieve the current logged in user's public contact
2677 $author_id = Contact::getPublicIdByUserId($uid);
2678 if (empty($author_id)) {
2679 Logger::info('Empty public contact');
2687 $activity = Activity::LIKE;
2691 $activity = Activity::DISLIKE;
2695 $activity = Activity::ATTEND;
2699 $activity = Activity::ATTENDNO;
2702 case 'unattendmaybe':
2703 $activity = Activity::ATTENDMAYBE;
2707 $activity = Activity::FOLLOW;
2711 $activity = Activity::ANNOUNCE;
2714 Logger::warning('unknown verb', ['verb' => $verb, 'item' => $item_id]);
2718 $mode = Strings::startsWith($verb, 'un') ? 'delete' : 'create';
2720 // Enable activity toggling instead of on/off
2721 $event_verb_flag = $activity === Activity::ATTEND || $activity === Activity::ATTENDNO || $activity === Activity::ATTENDMAYBE;
2723 // Look for an existing verb row
2724 // Event participation activities are mutually exclusive, only one of them can exist at all times.
2725 if ($event_verb_flag) {
2726 $verbs = [Activity::ATTEND, Activity::ATTENDNO, Activity::ATTENDMAYBE];
2728 // Translate to the index based activity index
2730 foreach ($verbs as $verb) {
2731 $vids[] = Verb::getID($verb);
2734 $vids = Verb::getID($activity);
2737 $condition = ['vid' => $vids, 'deleted' => false, 'gravity' => self::GRAVITY_ACTIVITY,
2738 'author-id' => $author_id, 'uid' => $uid, 'thr-parent-id' => $uri_id];
2739 $like_item = Post::selectFirst(['id', 'guid', 'verb'], $condition);
2741 if (DBA::isResult($like_item)) {
2743 * Truth table for existing activities
2745 * | Inputs || Outputs |
2746 * |----------------------------||-------------------|
2747 * | Mode | Event | Same verb || Delete? | Return? |
2748 * |--------|-------|-----------||---------|---------|
2749 * | create | Yes | Yes || No | Yes |
2750 * | create | Yes | No || Yes | No |
2751 * | create | No | Yes || No | Yes |
2752 * | create | No | No || N/A†|
2753 * | delete | Yes | Yes || Yes | N/A‡ |
2754 * | delete | Yes | No || No | N/A‡ |
2755 * | delete | No | Yes || Yes | N/A‡ |
2756 * | delete | No | No || N/A†|
2757 * |--------|-------|-----------||---------|---------|
2758 * | A | B | C || A xor C | !B or C |
2760 * †Can't happen: It's impossible to find an existing non-event activity without
2761 * the same verb because we are only looking for this single verb.
2763 * ‡ The "mode = delete" is returning early whether an existing activity was found or not.
2765 if ($mode == 'create' xor $like_item['verb'] == $activity) {
2766 self::markForDeletionById($like_item['id']);
2769 if (!$event_verb_flag || $like_item['verb'] == $activity) {
2774 // No need to go further if we aren't creating anything
2775 if ($mode == 'delete') {
2779 $objtype = $item['resource-id'] ? Activity\ObjectType::IMAGE : Activity\ObjectType::NOTE;
2782 'guid' => System::createUUID(),
2783 'uri' => self::newURI(),
2785 'contact-id' => $owner['id'],
2786 'wall' => $item['wall'],
2788 'network' => Protocol::DFRN,
2789 'protocol' => Conversation::PARCEL_DIRECT,
2790 'direction' => Conversation::PUSH,
2791 'gravity' => self::GRAVITY_ACTIVITY,
2792 'parent' => $item['id'],
2793 'thr-parent' => $item['uri'],
2794 'owner-id' => $author_id,
2795 'author-id' => $author_id,
2796 'body' => $activity,
2797 'verb' => $activity,
2798 'object-type' => $objtype,
2799 'allow_cid' => $allow_cid ?? $item['allow_cid'],
2800 'allow_gid' => $allow_gid ?? $item['allow_gid'],
2801 'deny_cid' => $deny_cid ?? $item['deny_cid'],
2802 'deny_gid' => $deny_gid ?? $item['deny_gid'],
2807 if (in_array($activity, [Activity::LIKE, Activity::DISLIKE])) {
2808 $signed = Diaspora::createLikeSignature($uid, $new_item);
2809 if (!empty($signed)) {
2810 $new_item['diaspora_signed_text'] = json_encode($signed);
2814 self::insert($new_item, true);
2816 // If the parent item isn't visible then set it to visible
2817 // @todo Check if this is still needed
2818 if (!$item['visible']) {
2819 self::update(['visible' => true], ['id' => $item['id']]);
2825 * Fetch the SQL condition for the given user id
2827 * @param integer $owner_id User ID for which the permissions should be fetched
2828 * @return array condition
2830 public static function getPermissionsConditionArrayByUserId(int $owner_id): array
2832 $local_user = DI::userSession()->getLocalUserId();
2833 $remote_user = DI::userSession()->getRemoteContactID($owner_id);
2835 // default permissions - anonymous user
2836 $condition = ["`private` != ?", self::PRIVATE];
2838 if ($local_user && ($local_user == $owner_id)) {
2839 // Profile owner - everything is visible
2841 } elseif ($remote_user) {
2842 // Authenticated visitor - fetch the matching permissionsets
2843 $permissionSets = DI::permissionSet()->selectByContactId($remote_user, $owner_id);
2845 $condition = ["(`private` != ? OR (`private` = ? AND `wall`
2846 AND `psid` IN (" . implode(', ', array_fill(0, count($set), '?')) . ")))",
2847 self::PRIVATE, self::PRIVATE];
2848 $condition = array_merge($condition, $permissionSets->column('id'));
2856 * Get a permission SQL string for the given user
2858 * @param int $owner_id
2859 * @param string $table
2862 public static function getPermissionsSQLByUserId(int $owner_id, string $table = ''): string
2864 $local_user = DI::userSession()->getLocalUserId();
2865 $remote_user = DI::userSession()->getRemoteContactID($owner_id);
2867 if (!empty($table)) {
2868 $table = DBA::quoteIdentifier($table) . '.';
2872 * Construct permissions
2874 * default permissions - anonymous user
2876 $sql = sprintf(" AND " . $table . "`private` != %d", self::PRIVATE);
2878 // Profile owner - everything is visible
2879 if ($local_user && ($local_user == $owner_id)) {
2881 } elseif ($remote_user) {
2883 * Authenticated visitor. Unless pre-verified,
2884 * check that the contact belongs to this $owner_id
2885 * and load the groups the visitor belongs to.
2886 * If pre-verified, the caller is expected to have already
2887 * done this and passed the groups into this function.
2889 $permissionSets = DI::permissionSet()->selectByContactId($remote_user, $owner_id);
2892 $sql_set = sprintf(" OR (" . $table . "`private` = %d AND " . $table . "`wall` AND " . $table . "`psid` IN (", self::PRIVATE) . implode(',', $permissionSets->column('id')) . "))";
2897 $sql = sprintf(" AND (" . $table . "`private` != %d", self::PRIVATE) . $sql_set . ")";
2904 * get translated item type
2906 * @param array $item
2907 * @param \Friendica\Core\L10n $l10n
2910 public static function postType(array $item, \Friendica\Core\L10n $l10n): string
2912 if (!empty($item['event-id'])) {
2913 return $l10n->t('event');
2914 } elseif (!empty($item['resource-id'])) {
2915 return $l10n->t('photo');
2916 } elseif ($item['gravity'] == self::GRAVITY_ACTIVITY) {
2917 return $l10n->t('activity');
2918 } elseif ($item['gravity'] == self::GRAVITY_COMMENT) {
2919 return $l10n->t('comment');
2922 return $l10n->t('post');
2926 * Sets the "rendered-html" field of the provided item
2928 * Body is preserved to avoid side-effects as we modify it just-in-time for spoilers and private image links
2930 * @param array $item
2932 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2933 * @todo Remove reference, simply return "rendered-html" and "rendered-hash"
2935 private static function putInCache(&$item)
2937 // Save original body to prevent addons to modify it
2938 $body = $item['body'];
2940 $rendered_hash = $item['rendered-hash'] ?? '';
2941 $rendered_html = $item['rendered-html'] ?? '';
2943 if ($rendered_hash == ''
2944 || $rendered_html == ''
2945 || $rendered_hash != hash('md5', BBCode::VERSION . '::' . $body)
2946 || DI::config()->get('system', 'ignore_cache')
2948 $item['rendered-html'] = BBCode::convertForUriId($item['uri-id'], $item['body']);
2949 $item['rendered-hash'] = hash('md5', BBCode::VERSION . '::' . $body);
2951 $hook_data = ['item' => $item, 'rendered-html' => $item['rendered-html'], 'rendered-hash' => $item['rendered-hash']];
2952 Hook::callAll('put_item_in_cache', $hook_data);
2953 $item['rendered-html'] = $hook_data['rendered-html'];
2954 $item['rendered-hash'] = $hook_data['rendered-hash'];
2957 // Update if the generated values differ from the existing ones
2958 if ((($rendered_hash != $item['rendered-hash']) || ($rendered_html != $item['rendered-html'])) && !empty($item['id'])) {
2961 'rendered-html' => $item['rendered-html'],
2962 'rendered-hash' => $item['rendered-hash']
2964 ['id' => $item['id']]
2969 $item['body'] = $body;
2973 * Given an item array, convert the body element from bbcode to html and add smilie icons.
2974 * If attach is true, also add icons for item attachments.
2976 * @param array $item Record from item table
2977 * @param boolean $attach If true, add icons for item attachments as well
2978 * @param boolean $is_preview Whether this is a preview
2979 * @param boolean $only_cache Whether only cached HTML should be updated
2980 * @return string item body html
2981 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2982 * @throws \ImagickException
2983 * @hook prepare_body_init item array before any work
2984 * @hook prepare_body_content_filter ('item'=>item array, 'filter_reasons'=>string array) before first bbcode to html
2985 * @hook prepare_body ('item'=>item array, 'html'=>body string, 'is_preview'=>boolean, 'filter_reasons'=>string array) after first bbcode to html
2986 * @hook prepare_body_final ('item'=>item array, 'html'=>body string) after attach icons and blockquote special case handling (spoiler, author)
2988 public static function prepareBody(array &$item, bool $attach = false, bool $is_preview = false, bool $only_cache = false): string
2991 Hook::callAll('prepare_body_init', $item);
2994 // In order to provide theme developers more possibilities, event items
2995 // are treated differently.
2996 if ($item['object-type'] === Activity\ObjectType::EVENT && isset($item['event-id'])) {
2997 $ev = Event::getItemHTML($item);
3001 $tags = Tag::populateFromItem($item);
3003 $item['tags'] = $tags['tags'];
3004 $item['hashtags'] = $tags['hashtags'];
3005 $item['mentions'] = $tags['mentions'];
3008 $item['body'] = preg_replace("#\s*\[attachment .*?].*?\[/attachment]\s*#ism", "\n", $item['body']);
3009 $item['body'] = Post\Media::removeFromEndOfBody($item['body'] ?? '');
3012 $body = $item['body'];
3014 $item['body'] = preg_replace("#\s*\[attachment .*?].*?\[/attachment]\s*#ism", "\n", $item['body']);
3017 $fields = ['uri-id', 'uri', 'body', 'title', 'author-name', 'author-link', 'author-avatar', 'guid', 'created', 'plink', 'network', 'has-media', 'quote-uri-id', 'post-type'];
3021 $quote_shared_links = [];
3023 $shared = DI::contentItem()->getSharedPost($item, $fields);
3024 if (!empty($shared['post'])) {
3025 $shared_item = $shared['post'];
3026 $shared_item['body'] = Post\Media::removeFromEndOfBody($shared_item['body']);
3027 $quote_uri_id = $shared['post']['uri-id'];
3028 $shared_links[] = strtolower($shared['post']['uri']);
3029 $item['body'] = BBCode::removeSharedData($item['body']);
3030 } elseif (empty($shared_item['uri-id']) && empty($item['quote-uri-id']) && ($item['network'] != Protocol::DIASPORA)) {
3031 $media = Post\Media::getByURIId($item['uri-id'], [Post\Media::ACTIVITY]);
3032 if (!empty($media)) {
3033 $shared_item = Post::selectFirst($fields, ['plink' => $media[0]['url'], 'uid' => [$item['uid'], 0]]);
3035 if (empty($shared_item['uri-id'])) {
3036 $shared_item = Post::selectFirst($fields, ['uri' => $media[0]['url'], 'uid' => [$item['uid'], 0]]);
3037 $shared_links[] = strtolower($media[0]['url']);
3040 if (!empty($shared_item['uri-id'])) {
3041 $data = BBCode::getAttachmentData($shared_item['body']);
3042 if (!empty($data['url'])) {
3043 $quote_shared_links[] = $data['url'];
3046 $quote_uri_id = $shared_item['uri-id'];
3051 if (!empty($quote_uri_id)) {
3052 if (isset($shared_item['plink'])) {
3053 $item['body'] .= "\n" . DI::contentItem()->createSharedBlockByArray($shared_item);
3055 DI::logger()->warning('Missing plink in shared item', ['item' => $item, 'shared' => $shared, 'quote_uri_id' => $quote_uri_id, 'shared_item' => $shared_item]);
3059 if (!empty($shared_item['uri-id'])) {
3060 $shared_uri_id = $shared_item['uri-id'];
3061 $shared_links[] = strtolower($shared_item['plink']);
3062 $shared_attachments = Post\Media::splitAttachments($shared_uri_id, [], $shared_item['has-media']);
3063 $shared_links = array_merge($shared_links, array_column($shared_attachments['visual'], 'url'));
3064 $shared_links = array_merge($shared_links, array_column($shared_attachments['link'], 'url'));
3065 $shared_links = array_merge($shared_links, array_column($shared_attachments['additional'], 'url'));
3066 $item['body'] = self::replaceVisualAttachments($shared_attachments, $item['body']);
3069 $attachments = Post\Media::splitAttachments($item['uri-id'], $shared_links, $item['has-media'] ?? false);
3070 $item['body'] = self::replaceVisualAttachments($attachments, $item['body'] ?? '');
3072 self::putInCache($item);
3073 $item['body'] = $body;
3074 $s = $item["rendered-html"];
3080 // Compile eventual content filter reasons
3081 $filter_reasons = [];
3082 if (!$is_preview && DI::userSession()->getPublicContactId() != $item['author-id']) {
3083 if (!empty($item['user-blocked-author']) || !empty($item['user-blocked-owner'])) {
3084 $filter_reasons[] = DI::l10n()->t('%s is blocked', $item['author-name']);
3085 } elseif (!empty($item['user-ignored-author']) || !empty($item['user-ignored-owner'])) {
3086 $filter_reasons[] = DI::l10n()->t('%s is ignored', $item['author-name']);
3087 } elseif (!empty($item['user-collapsed-author']) || !empty($item['user-collapsed-owner'])) {
3088 $filter_reasons[] = DI::l10n()->t('Content from %s is collapsed', $item['author-name']);
3091 if (!empty($item['content-warning']) && (!DI::userSession()->getLocalUserId() || !DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'system', 'disable_cw', false))) {
3092 $filter_reasons[] = DI::l10n()->t('Content warning: %s', $item['content-warning']);
3095 $item['attachments'] = $attachments;
3099 'filter_reasons' => $filter_reasons
3101 Hook::callAll('prepare_body_content_filter', $hook_data);
3102 $filter_reasons = $hook_data['filter_reasons'];
3109 'preview' => $is_preview,
3110 'filter_reasons' => $filter_reasons
3112 Hook::callAll('prepare_body', $hook_data);
3113 $s = $hook_data['html'];
3118 // Replace the blockquotes with quotes that are used in mails.
3119 $mailquote = '<blockquote type="cite" class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex;">';
3120 $s = str_replace(['<blockquote>', '<blockquote class="spoiler">', '<blockquote class="author">'], [$mailquote, $mailquote, $mailquote], $s);
3124 if (!empty($shared_attachments)) {
3125 $s = self::addVisualAttachments($shared_attachments, $shared_item, $s, true);
3126 $s = self::addLinkAttachment($shared_uri_id ?: $item['uri-id'], $shared_attachments, $body, $s, true, $quote_shared_links);
3127 $s = self::addNonVisualAttachments($shared_attachments, $item, $s, true);
3128 $body = BBCode::removeSharedData($body);
3131 $s = self::addVisualAttachments($attachments, $item, $s, false);
3132 $s = self::addLinkAttachment($item['uri-id'], $attachments, $body, $s, false, $shared_links);
3133 $s = self::addNonVisualAttachments($attachments, $item, $s, false);
3134 $s = self::addQuestions($item, $s);
3137 if (strpos($s, '<div class="map">') !== false && !empty($item['coord'])) {
3138 $x = Map::byCoordinates(trim($item['coord']));
3140 $s = preg_replace('/\<div class\=\"map\"\>/', '$0' . $x, $s);
3144 // Replace friendica image url size with theme preference.
3145 if (!empty($a->getThemeInfoValue('item_image_size'))) {
3146 $ps = $a->getThemeInfoValue('item_image_size');
3147 $s = preg_replace('|(<img[^>]+src="[^"]+/photo/[0-9a-f]+)-[0-9]|', "$1-" . $ps, $s);
3150 $s = HTML::applyContentFilter($s, $filter_reasons);
3152 $hook_data = ['item' => $item, 'html' => $s];
3153 Hook::callAll('prepare_body_final', $hook_data);
3154 return $hook_data['html'];
3158 * @param array $images
3160 * @throws \Friendica\Network\HTTPException\ServiceUnavailableException
3162 private static function makeImageGrid(array $images): string
3164 // Image for first column (fc) and second column (sc)
3168 for ($i = 0; $i < count($images); $i++) {
3169 ($i % 2 == 0) ? ($images_fc[] = $images[$i]) : ($images_sc[] = $images[$i]);
3172 return Renderer::replaceMacros(Renderer::getMarkupTemplate('content/image_grid.tpl'), [
3182 * Check if the body contains a link
3184 * @param string $body
3185 * @param string $url
3189 public static function containsLink(string $body, string $url, int $type = 0): bool
3191 // Make sure that for example site parameters aren't used when testing if the link is contained in the body
3192 $urlparts = parse_url($url);
3193 if (empty($urlparts)) {
3197 unset($urlparts['query']);
3198 unset($urlparts['fragment']);
3201 $url = (string)Uri::fromParts($urlparts);
3202 } catch (\InvalidArgumentException $e) {
3203 DI::logger()->notice('Invalid URL', ['$url' => $url, '$urlparts' => $urlparts]);
3204 /* See https://github.com/friendica/friendica/issues/12113
3205 * Malformed URLs will result in a Fatal Error
3210 // Remove media links to only search in embedded content
3211 // @todo Check images for image link, audio for audio links, ...
3212 if (in_array($type, [Post\Media::AUDIO, Post\Media::VIDEO, Post\Media::IMAGE])) {
3213 $body = preg_replace("/\[url=[^\[\]]*\](.*)\[\/url\]/Usi", ' $1 ', $body);
3216 if (strpos($body, $url)) {
3220 foreach ([0, 1, 2] as $size) {
3221 if (preg_match('#/photo/.*-' . $size . '\.#ism', $url) &&
3222 strpos(preg_replace('#(/photo/.*)-[012]\.#ism', '$1-' . $size . '.', $body), $url)) {
3231 * Replace visual attachments in the body
3233 * @param array $attachments
3234 * @param string $body
3235 * @return string modified body
3237 private static function replaceVisualAttachments(array $attachments, string $body): string
3239 DI::profiler()->startRecording('rendering');
3241 foreach ($attachments['visual'] as $attachment) {
3242 if (!empty($attachment['preview'])) {
3243 $proxy = Post\Media::getPreviewUrlForId($attachment['id'], Proxy::SIZE_LARGE);
3244 $search = ['[img=' . $attachment['preview'] . ']', ']' . $attachment['preview'] . '[/img]'];
3245 $replace = ['[img=' . $proxy . ']', ']' . $proxy . '[/img]'];
3247 $body = str_replace($search, $replace, $body);
3248 } elseif ($attachment['filetype'] == 'image') {
3249 $proxy = Post\Media::getUrlForId($attachment['id']);
3250 $search = ['[img=' . $attachment['url'] . ']', ']' . $attachment['url'] . '[/img]'];
3251 $replace = ['[img=' . $proxy . ']', ']' . $proxy . '[/img]'];
3253 $body = str_replace($search, $replace, $body);
3256 DI::profiler()->stopRecording();
3261 * Add visual attachments to the content
3263 * @param array $attachments
3264 * @param array $item
3265 * @param string $content
3266 * @return string modified content
3268 private static function addVisualAttachments(array $attachments, array $item, string $content, bool $shared): string
3270 DI::profiler()->startRecording('rendering');
3275 // @todo In the future we should make a single for the template engine with all media in it. This allows more flexibilty.
3276 foreach ($attachments['visual'] as $attachment) {
3277 if (self::containsLink($item['body'], $attachment['preview'] ?? $attachment['url'], $attachment['type'])) {
3281 if ($attachment['filetype'] == 'image') {
3282 $preview_url = Post\Media::getPreviewUrlForId($attachment['id'], ($attachment['width'] > $attachment['height']) ? Proxy::SIZE_MEDIUM : Proxy::SIZE_LARGE);
3283 } elseif (!empty($attachment['preview'])) {
3284 $preview_url = Post\Media::getPreviewUrlForId($attachment['id'], Proxy::SIZE_LARGE);
3289 if ($preview_url && self::containsLink($item['body'], $preview_url)) {
3293 if (($attachment['filetype'] == 'video')) {
3294 /// @todo Move the template to /content as well
3295 $media = Renderer::replaceMacros(Renderer::getMarkupTemplate('video_top.tpl'), [
3297 'id' => $attachment['id'],
3298 'src' => $attachment['url'],
3299 'name' => $attachment['name'] ?: $attachment['url'],
3300 'preview' => $preview_url,
3301 'mime' => $attachment['mimetype'],
3304 if (($item['post-type'] ?? null) == Item::PT_VIDEO) {
3307 $trailing .= $media;
3309 } elseif ($attachment['filetype'] == 'audio') {
3310 $media = Renderer::replaceMacros(Renderer::getMarkupTemplate('content/audio.tpl'), [
3312 'id' => $attachment['id'],
3313 'src' => $attachment['url'],
3314 'name' => $attachment['name'] ?: $attachment['url'],
3315 'mime' => $attachment['mimetype'],
3318 if (($item['post-type'] ?? null) == Item::PT_AUDIO) {
3321 $trailing .= $media;
3323 } elseif ($attachment['filetype'] == 'image') {
3324 $src_url = Post\Media::getUrlForId($attachment['id']);
3325 if (self::containsLink($item['body'], $src_url)) {
3328 $images[] = ['src' => $src_url, 'preview' => $preview_url, 'attachment' => $attachment];
3333 if (count($images) > 1) {
3334 $media = self::makeImageGrid($images);
3335 } elseif (count($images) == 1) {
3336 $media = Renderer::replaceMacros(Renderer::getMarkupTemplate('content/image.tpl'), [
3337 '$image' => $images[0],
3341 // On Diaspora posts the attached pictures are leading
3342 if ($item['network'] == Protocol::DIASPORA) {
3345 $trailing .= $media;
3349 $content = str_replace(BBCode::TOP_ANCHOR, '<div class="body-attach">' . $leading . '</div>' . BBCode::TOP_ANCHOR, $content);
3350 $content = str_replace(BBCode::BOTTOM_ANCHOR, '<div class="body-attach">' . $trailing . '</div>' . BBCode::BOTTOM_ANCHOR, $content);
3352 if ($leading != '') {
3353 $content = '<div class="body-attach">' . $leading . '</div>' . $content;
3356 if ($trailing != '') {
3357 $content .= '<div class="body-attach">' . $trailing . '</div>';
3361 DI::profiler()->stopRecording();
3366 * Add link attachment to the content
3368 * @param array $attachments
3369 * @param string $body
3370 * @param string $content
3371 * @param bool $shared
3372 * @param array $ignore_links A list of URLs to ignore
3373 * @return string modified content
3375 private static function addLinkAttachment(int $uriid, array $attachments, string $body, string $content, bool $shared, array $ignore_links): string
3377 DI::profiler()->startRecording('rendering');
3378 // Don't show a preview when there is a visual attachment (audio or video)
3379 $types = array_column($attachments['visual'], 'type');
3380 $preview = !in_array(Post\Media::IMAGE, $types) && !in_array(Post\Media::VIDEO, $types);
3382 if (!empty($attachments['link'])) {
3383 foreach ($attachments['link'] as $link) {
3385 foreach ($ignore_links as $ignore_link) {
3386 if (Strings::compareLink($link['url'], $ignore_link)) {
3390 // @todo Judge between the links to use the one with most information
3391 if (!$found && (empty($attachment) || !empty($link['author-name']) ||
3392 (empty($attachment['name']) && !empty($link['name'])) ||
3393 (empty($attachment['description']) && !empty($link['description'])) ||
3394 (empty($attachment['preview']) && !empty($link['preview'])))) {
3395 $attachment = $link;
3400 if (!empty($attachment)) {
3403 'author_name' => $attachment['author-name'] ?? '',
3404 'author_url' => $attachment['author-url'] ?? '',
3405 'description' => $attachment['description'] ?? '',
3408 'provider_name' => $attachment['publisher-name'] ?? '',
3409 'provider_url' => $attachment['publisher-url'] ?? '',
3411 'title' => $attachment['name'] ?? '',
3413 'url' => $attachment['url']];
3415 if ($preview && !empty($attachment['preview'])) {
3416 if ($attachment['preview-width'] >= 500) {
3417 $data['image'] = Post\Media::getPreviewUrlForId($attachment['id'], Proxy::SIZE_MEDIUM);
3419 $data['preview'] = Post\Media::getPreviewUrlForId($attachment['id'], Proxy::SIZE_MEDIUM);
3423 if (!empty($data['description']) && !empty($content)) {
3424 similar_text($data['description'], $content, $percent);
3429 if (!empty($data['description']) && (($data['title'] == $data['description']) || ($percent > 95) || (strpos($content, $data['description']) !== false))) {
3430 $data['description'] = '';
3433 if (($data['author_name'] ?? '') == ($data['provider_name'] ?? '')) {
3434 $data['author_name'] = '';
3437 if (($data['author_url'] ?? '') == ($data['provider_url'] ?? '')) {
3438 $data['author_url'] = '';
3440 } elseif (preg_match("/.*(\[attachment.*?\].*?\[\/attachment\]).*/ism", $body, $match)) {
3441 $data = BBCode::getAttachmentData($match[1]);
3443 DI::profiler()->stopRecording();
3445 if (isset($data['url']) && !in_array(strtolower($data['url']), $ignore_links)) {
3446 if (!empty($data['description']) || !empty($data['image']) || !empty($data['preview']) || (!empty($data['title']) && !Strings::compareLink($data['title'], $data['url']))) {
3447 $parts = parse_url($data['url']);
3448 if (!empty($parts['scheme']) && !empty($parts['host'])) {
3449 if (empty($data['provider_name'])) {
3450 $data['provider_name'] = $parts['host'];
3452 if (empty($data['provider_url']) || empty(parse_url($data['provider_url'], PHP_URL_SCHEME))) {
3453 $data['provider_url'] = $parts['scheme'] . '://' . $parts['host'];
3455 if (!empty($parts['port'])) {
3456 $data['provider_url'] .= ':' . $parts['port'];
3461 // @todo Use a template
3462 $preview_mode = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'system', 'preview_mode', BBCode::PREVIEW_LARGE);
3463 if ($preview_mode != BBCode::PREVIEW_NONE) {
3464 $rendered = BBCode::convertAttachment('', BBCode::INTERNAL, false, $data, $uriid, $preview_mode);
3468 } elseif (!self::containsLink($content, $data['url'], Post\Media::HTML)) {
3469 $rendered = Renderer::replaceMacros(Renderer::getMarkupTemplate('content/link.tpl'), [
3470 '$url' => $data['url'],
3471 '$title' => $data['title'],
3478 return str_replace(BBCode::BOTTOM_ANCHOR, BBCode::BOTTOM_ANCHOR . $rendered, $content);
3480 return $content . $rendered;
3487 * Add non visual attachments to the content
3489 * @param array $attachments
3490 * @param array $item
3491 * @param string $content
3492 * @return string modified content
3494 private static function addNonVisualAttachments(array $attachments, array $item, string $content): string
3496 DI::profiler()->startRecording('rendering');
3498 foreach ($attachments['additional'] as $attachment) {
3499 if (strpos($item['body'], $attachment['url'])) {
3503 $author = ['uid' => 0, 'id' => $item['author-id'],
3504 'network' => $item['author-network'], 'url' => $item['author-link']];
3505 $the_url = Contact::magicLinkByContact($author, $attachment['url']);
3507 $title = Strings::escapeHtml(trim(($attachment['description'] ?? '') ?: $attachment['url']));
3509 if (!empty($attachment['size'])) {
3510 $title .= ' ' . $attachment['size'] . ' ' . DI::l10n()->t('bytes');
3513 /// @todo Use a template
3514 $icon = '<div class="attachtype icon s22 type-' . $attachment['filetype'] . ' subtype-' . $attachment['subtype'] . '"></div>';
3515 $trailing .= '<a href="' . strip_tags($the_url) . '" title="' . $title . '" class="attachlink" target="_blank" rel="noopener noreferrer" >' . $icon . '</a>';
3518 if ($trailing != '') {
3519 $content .= '<div class="body-attach">' . $trailing . '</div>';
3522 DI::profiler()->stopRecording();
3526 private static function addQuestions(array $item, string $content): string
3528 DI::profiler()->startRecording('rendering');
3529 if (!empty($item['question-id'])) {
3531 'id' => $item['question-id'],
3532 'multiple' => $item['question-multiple'],
3533 'voters' => $item['question-voters'],
3534 'endtime' => $item['question-end-time']
3537 $options = Post\QuestionOption::getByURIId($item['uri-id']);
3538 foreach ($options as $key => $option) {
3539 if ($question['voters'] > 0) {
3540 $percent = $option['replies'] / $question['voters'] * 100;
3541 $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));
3543 $options[$key]['vote'] = DI::l10n()->tt('%2$s (%1$d vote)', '%2$s (%1$d votes)', $option['replies'], $option['name']);
3547 if (!empty($question['voters']) && !empty($question['endtime'])) {
3548 $summary = DI::l10n()->tt('%d voter. Poll end: %s', '%d voters. Poll end: %s', $question['voters'], Temporal::getRelativeDate($question['endtime']));
3549 } elseif (!empty($question['voters'])) {
3550 $summary = DI::l10n()->tt('%d voter.', '%d voters.', $question['voters']);
3551 } elseif (!empty($question['endtime'])) {
3552 $summary = DI::l10n()->t('Poll end: %s', Temporal::getRelativeDate($question['endtime']));
3557 $content .= Renderer::replaceMacros(Renderer::getMarkupTemplate('content/question.tpl'), [
3558 '$question' => $question,
3559 '$options' => $options,
3560 '$summary' => $summary,
3563 DI::profiler()->stopRecording();
3568 * get private link for item
3570 * @param array $item
3571 * @return boolean|array False if item has not plink, otherwise array('href'=>plink url, 'title'=>translated title)
3572 * @throws \Exception
3574 public static function getPlink(array $item)
3576 if (!empty($item['plink']) && Network::isValidHttpUrl($item['plink'])) {
3577 $plink = $item['plink'];
3578 } elseif (!empty($item['uri']) && Network::isValidHttpUrl($item['uri']) && !Network::isLocalLink($item['uri'])) {
3579 $plink = $item['uri'];
3582 if (DI::userSession()->getLocalUserId()) {
3584 'href' => "display/" . $item['guid'],
3585 'orig' => "display/" . $item['guid'],
3586 'title' => DI::l10n()->t('View on separate page'),
3587 'orig_title' => DI::l10n()->t('View on separate page'),
3590 if (!empty($plink) && ($item['private'] == self::PRIVATE)) {
3591 $author = ['uid' => 0, 'id' => $item['author-id'],
3592 'network' => $item['author-network'], 'url' => $item['author-link']];
3593 $plink = Contact::magicLinkByContact($author, $plink);
3596 if (!empty($plink)) {
3597 $ret['href'] = DI::baseUrl()->remove($plink);
3598 $ret['title'] = DI::l10n()->t('Link to source');
3600 } elseif (!empty($plink) && ($item['private'] != self::PRIVATE)) {
3604 'title' => DI::l10n()->t('Link to source'),
3605 'orig_title' => DI::l10n()->t('Link to source'),
3615 * Does the given uri-id belongs to a post that is sent as starting post to a forum?
3617 * @param int $uri_id
3619 * @return boolean "true" when it is a forum post
3621 public static function isForumPost(int $uri_id): bool
3623 foreach (Tag::getByURIId($uri_id, [Tag::EXCLUSIVE_MENTION]) as $tag) {
3624 if (DBA::exists('contact', ['uid' => 0, 'nurl' => Strings::normaliseLink($tag['url']), 'contact-type' => Contact::TYPE_COMMUNITY])) {
3632 * Search item id for given URI or plink
3634 * @param string $uri
3635 * @param integer $uid
3637 * @return integer item id
3639 public static function searchByLink(string $uri, int $uid = 0): int
3641 $ssl_uri = str_replace('http://', 'https://', $uri);
3642 $uris = [$uri, $ssl_uri, Strings::normaliseLink($uri)];
3644 $item = Post::selectFirst(['id'], ['uri' => $uris, 'uid' => $uid]);
3645 if (DBA::isResult($item)) {
3649 $item = Post::selectFirst(['id'], ['plink' => $uris, 'uid' => $uid]);
3650 if (DBA::isResult($item)) {
3658 * Return the URI for a link to the post
3660 * @param string $uri URI or link to post
3662 * @return string URI
3664 public static function getURIByLink(string $uri): string
3666 $ssl_uri = str_replace('http://', 'https://', $uri);
3667 $uris = [$uri, $ssl_uri, Strings::normaliseLink($uri)];
3669 $item = Post::selectFirst(['uri'], ['uri' => $uris]);
3670 if (DBA::isResult($item)) {
3671 return $item['uri'];
3674 $item = Post::selectFirst(['uri'], ['plink' => $uris]);
3675 if (DBA::isResult($item)) {
3676 return $item['uri'];
3683 * Fetches item for given URI or plink
3685 * @param string $uri
3686 * @param integer $uid
3688 * @return integer item id
3690 public static function fetchByLink(string $uri, int $uid = 0): int
3692 Logger::info('Trying to fetch link', ['uid' => $uid, 'uri' => $uri]);
3693 $item_id = self::searchByLink($uri, $uid);
3694 if (!empty($item_id)) {
3695 Logger::info('Link found', ['uid' => $uid, 'uri' => $uri, 'id' => $item_id]);
3705 Hook::callAll('item_by_link', $hookData);
3707 if (isset($hookData['item_id'])) {
3708 return is_numeric($hookData['item_id']) ? $hookData['item_id'] : 0;
3711 $fetched_uri = ActivityPub\Processor::fetchMissingActivity($uri, [], '', ActivityPub\Receiver::COMPLETION_MANUAL, $uid);
3714 $item_id = self::searchByLink($fetched_uri, $uid);
3716 $item_id = Diaspora::fetchByURL($uri);
3719 if (!empty($item_id)) {
3720 Logger::info('Link fetched', ['uid' => $uid, 'uri' => $uri, 'id' => $item_id]);
3724 Logger::info('Link not found', ['uid' => $uid, 'uri' => $uri]);
3729 * Fetch the uri-id of a quote
3731 * @param string $body
3734 public static function getQuoteUriId(string $body, int $uid = 0): int
3736 $shared = BBCode::fetchShareAttributes($body);
3737 if (empty($shared['guid']) && empty($shared['message_id'])) {
3741 if (empty($shared['link']) && empty($shared['message_id'])) {
3742 Logger::notice('Invalid share block.', ['share' => $shared]);
3746 if (!empty($shared['guid'])) {
3747 $shared_item = Post::selectFirst(['uri-id'], ['guid' => $shared['guid'], 'uid' => [0, $uid]]);
3748 if (!empty($shared_item['uri-id'])) {
3749 Logger::debug('Found post by guid', ['guid' => $shared['guid'], 'uid' => $uid]);
3750 return $shared_item['uri-id'];
3754 if (!empty($shared['message_id'])) {
3755 $shared_item = Post::selectFirst(['uri-id'], ['uri' => $shared['message_id'], 'uid' => [0, $uid]]);
3756 if (!empty($shared_item['uri-id'])) {
3757 Logger::debug('Found post by message_id', ['message_id' => $shared['message_id'], 'uid' => $uid]);
3758 return $shared_item['uri-id'];
3762 if (!empty($shared['link'])) {
3763 $shared_item = Post::selectFirst(['uri-id'], ['plink' => $shared['link'], 'uid' => [0, $uid]]);
3764 if (!empty($shared_item['uri-id'])) {
3765 Logger::debug('Found post by link', ['link' => $shared['link'], 'uid' => $uid]);
3766 return $shared_item['uri-id'];
3770 $url = $shared['message_id'] ?: $shared['link'];
3771 $id = self::fetchByLink($url);
3773 Logger::notice('Post could not be fetched.', ['url' => $url, 'uid' => $uid]);
3777 $shared_item = Post::selectFirst(['uri-id'], ['id' => $id]);
3778 if (!empty($shared_item['uri-id'])) {
3779 Logger::debug('Fetched shared post', ['id' => $id, 'url' => $url, 'uid' => $uid]);
3780 return $shared_item['uri-id'];
3783 Logger::warning('Post does not exist although it was supposed to had been fetched.', ['id' => $id, 'url' => $url, 'uid' => $uid]);