3 * @copyright Copyright (C) 2010-2023, the Friendica project
5 * @license GNU AGPL version 3 or any later version
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU Affero General Public License as
9 * published by the Free Software Foundation, either version 3 of the
10 * License, or (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU Affero General Public License for more details.
17 * You should have received a copy of the GNU Affero General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
22 namespace Friendica\Model;
24 use Friendica\Contact\LocalRelationship\Entity\LocalRelationship;
25 use Friendica\Content\Text\BBCode;
26 use Friendica\Content\Text\HTML;
27 use Friendica\Core\Hook;
28 use Friendica\Core\Logger;
29 use Friendica\Core\Protocol;
30 use Friendica\Core\Renderer;
31 use Friendica\Core\System;
32 use Friendica\Core\Worker;
33 use Friendica\Database\DBA;
35 use Friendica\Model\Post\Category;
36 use Friendica\Network\HTTPException\InternalServerErrorException;
37 use Friendica\Protocol\Activity;
38 use Friendica\Protocol\ActivityPub;
39 use Friendica\Protocol\Delivery;
40 use Friendica\Protocol\Diaspora;
41 use Friendica\Util\DateTimeFormat;
42 use Friendica\Util\Map;
43 use Friendica\Util\Network;
44 use Friendica\Util\Proxy;
45 use Friendica\Util\Strings;
46 use Friendica\Util\Temporal;
47 use GuzzleHttp\Psr7\Uri;
48 use LanguageDetection\Language;
52 // Posting types, inspired by https://www.w3.org/TR/activitystreams-vocabulary/#object-types
59 const PT_DOCUMENT = 19;
62 const PT_PERSONAL_NOTE = 128;
64 // Posting reasons (Why had a post been stored for a user?)
71 const PR_FOLLOWER = 69;
72 const PR_ANNOUNCEMENT = 70;
73 const PR_COMMENT = 71;
77 const PR_FETCHED = 75;
78 const PR_COMPLETION = 76;
80 const PR_ACTIVITY = 78;
81 const PR_DISTRIBUTE = 79;
84 const PR_AUDIENCE = 82;
86 // system.accept_only_sharer setting values
87 const COMPLETION_NONE = 1;
88 const COMPLETION_COMMENT = 0;
89 const COMPLETION_LIKE = 2;
91 // Field list that is used to display the items
92 const DISPLAY_FIELDLIST = [
93 'uid', 'id', 'parent', 'guid', 'network', 'gravity',
94 'uri-id', 'uri', 'thr-parent-id', 'thr-parent', 'parent-uri-id', 'parent-uri', 'conversation',
95 'commented', 'created', 'edited', 'received', 'verb', 'object-type', 'postopts', 'plink',
96 'wall', 'private', 'starred', 'origin', 'parent-origin', 'title', 'body', 'language',
97 'content-warning', 'location', 'coord', 'app', 'rendered-hash', 'rendered-html', 'object',
98 'quote-uri', 'quote-uri-id', 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid', 'mention', 'global',
99 'author-id', 'author-link', 'author-alias', 'author-name', 'author-avatar', 'author-network', 'author-updated', 'author-gsid', 'author-baseurl', 'author-addr', 'author-uri-id',
100 'owner-id', 'owner-link', 'owner-alias', 'owner-name', 'owner-avatar', 'owner-network', 'owner-contact-type', 'owner-updated', 'owner-gsid',
101 'causer-id', 'causer-link', 'causer-alias', 'causer-name', 'causer-avatar', 'causer-contact-type', 'causer-network', 'causer-gsid',
102 'contact-id', 'contact-uid', 'contact-link', 'contact-name', 'contact-avatar',
103 'writable', 'self', 'cid', 'alias',
104 'event-created', 'event-edited', 'event-start', 'event-finish',
105 'event-summary', 'event-desc', 'event-location', 'event-type',
106 'event-nofinish', 'event-ignore', 'event-id',
107 'question-id', 'question-multiple', 'question-voters', 'question-end-time',
108 'has-categories', 'has-media',
109 'delivery_queue_count', 'delivery_queue_done', 'delivery_queue_failed'
112 // Field list that is used to deliver items via the protocols
113 const DELIVER_FIELDLIST = [
114 'uid', 'id', 'parent', 'uri-id', 'uri', 'thr-parent', 'parent-uri', 'guid',
115 'parent-guid', 'conversation', 'received', 'created', 'edited', 'verb', 'object-type', 'object', 'target',
116 'private', 'title', 'body', 'raw-body', 'location', 'coord', 'app',
117 'inform', 'deleted', 'extid', 'post-type', 'post-reason', 'gravity',
118 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid',
119 'author-id', 'author-addr', 'author-link', 'author-name', 'author-avatar', 'owner-id', 'owner-link', 'contact-uid',
120 'signed_text', 'network', 'wall', 'contact-id', 'plink', 'origin',
121 'thr-parent-id', 'parent-uri-id', 'quote-uri', 'quote-uri-id', 'postopts', 'pubmail',
122 'event-created', 'event-edited', 'event-start', 'event-finish',
123 'event-summary', 'event-desc', 'event-location', 'event-type',
124 'event-nofinish', 'event-ignore', 'event-id'
127 // All fields in the item table
128 const ITEM_FIELDLIST = [
129 'id', 'uid', 'parent', 'uri', 'parent-uri', 'thr-parent',
130 'guid', 'uri-id', 'parent-uri-id', 'thr-parent-id', 'conversation', 'vid',
131 'quote-uri', 'quote-uri-id', 'contact-id', 'wall', 'gravity', 'extid', 'psid',
132 'created', 'edited', 'commented', 'received', 'changed', 'verb',
133 'postopts', 'plink', 'resource-id', 'event-id', 'inform',
134 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid', 'post-type', 'post-reason',
135 'private', 'pubmail', 'visible', 'starred',
136 'unseen', 'deleted', 'origin', 'mention', 'global', 'network',
137 'title', 'content-warning', 'body', 'location', 'coord', 'app',
138 'rendered-hash', 'rendered-html', 'object-type', 'object', 'target-type', 'target',
139 'author-id', 'author-link', 'author-name', 'author-avatar', 'author-network',
140 'owner-id', 'owner-link', 'owner-name', 'owner-avatar', 'causer-id'
143 // List of all verbs that don't need additional content data.
144 // Never reorder or remove entries from this list. Just add new ones at the end, if needed.
146 Activity::LIKE, Activity::DISLIKE,
147 Activity::ATTEND, Activity::ATTENDNO, Activity::ATTENDMAYBE,
157 // Item weight for query ordering
158 const GRAVITY_PARENT = 0;
159 const GRAVITY_ACTIVITY = 3;
160 const GRAVITY_COMMENT = 6;
161 const GRAVITY_UNKNOWN = 9;
164 * Update existing item entries
166 * @param array $fields The fields that are to be changed
167 * @param array $condition The condition for finding the item entries
169 * In the future we may have to change permissions as well.
170 * Then we had to add the user id as third parameter.
172 * A return value of "0" doesn't mean an error - but that 0 rows had been changed.
174 * @return integer|boolean number of affected rows - or "false" if there was an error
175 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
177 public static function update(array $fields, array $condition)
179 if (empty($condition) || empty($fields)) {
183 if (isset($fields['extid'])) {
184 $fields['external-id'] = ItemURI::getIdByURI($fields['extid']);
187 if (!empty($fields['verb'])) {
188 $fields['vid'] = Verb::getID($fields['verb']);
191 if (!empty($fields['edited'])) {
192 $previous = Post::selectFirst(['edited'], $condition);
195 $rows = Post::update($fields, $condition);
196 if (is_bool($rows)) {
200 // We only need to call the line by line update for specific fields
202 empty($fields['body']) && empty($fields['file']) &&
203 empty($fields['attach']) && empty($fields['edited'])
208 Logger::info('Updating per single row method', ['fields' => $fields, 'condition' => $condition]);
210 $items = Post::select(['id', 'origin', 'uri-id', 'uid', 'author-network', 'quote-uri-id'], $condition);
214 while ($item = DBA::fetch($items)) {
215 if (!empty($fields['body'])) {
216 if (!empty($item['quote-uri-id'])) {
217 $fields['body'] = BBCode::removeSharedData($fields['body']);
219 if (!empty($fields['raw-body'])) {
220 $fields['raw-body'] = BBCode::removeSharedData($fields['raw-body']);
224 $content_fields = ['raw-body' => trim($fields['raw-body'] ?? $fields['body'])];
226 // Remove all media attachments from the body and store them in the post-media table
227 // @todo On shared postings (Diaspora style and commented reshare) don't fetch content from the shared part
228 $content_fields['raw-body'] = Post\Media::insertFromBody($item['uri-id'], $content_fields['raw-body']);
229 $content_fields['raw-body'] = self::setHashtags($content_fields['raw-body']);
231 Post\Media::insertFromRelevantUrl($item['uri-id'], $content_fields['raw-body'], $fields['body'], $item['author-network']);
233 Post\Media::insertFromAttachmentData($item['uri-id'], $fields['body']);
234 $content_fields['raw-body'] = BBCode::removeAttachment($content_fields['raw-body']);
236 Post\Content::update($item['uri-id'], $content_fields);
239 if (!empty($fields['file'])) {
240 Post\Category::storeTextByURIId($item['uri-id'], $item['uid'], $fields['file']);
243 if (!empty($fields['attach'])) {
244 Post\Media::insertFromAttachment($item['uri-id'], $fields['attach']);
247 // We only need to notify others when it is an original entry from us.
248 // Only call the notifier when the item had been edited and records had been changed.
249 if ($item['origin'] && !empty($fields['edited']) && ($previous['edited'] != $fields['edited'])) {
250 $notify_items[] = $item['id'];
256 foreach ($notify_items as $notify_item) {
257 $post = Post::selectFirst([], ['id' => $notify_item]);
259 if ($post['gravity'] != self::GRAVITY_PARENT) {
260 $signed = Diaspora::createCommentSignature($post);
261 if (!empty($signed)) {
262 DBA::replace('diaspora-interaction', ['uri-id' => $post['uri-id'], 'interaction' => json_encode($signed)]);
266 Worker::add(Worker::PRIORITY_HIGH, 'Notifier', Delivery::POST, (int)$post['uri-id'], (int)$post['uid']);
273 * Delete an item and notify others about it - if it was ours
275 * @param array $condition The condition for finding the item entries
276 * @param integer $priority Priority for the notification
278 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
280 public static function markForDeletion(array $condition, int $priority = Worker::PRIORITY_HIGH)
282 $items = Post::select(['id'], $condition);
283 while ($item = Post::fetch($items)) {
284 self::markForDeletionById($item['id'], $priority);
290 * Delete an item for an user and notify others about it - if it was ours
292 * @param array $condition The condition for finding the item entries
293 * @param integer $uid User who wants to delete this item
295 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
297 public static function deleteForUser(array $condition, int $uid)
303 $items = Post::select(['id', 'uid', 'uri-id'], $condition);
304 while ($item = Post::fetch($items)) {
305 if (in_array($item['uid'], [$uid, 0])) {
306 Post\User::update($item['uri-id'], $uid, ['hidden' => true], true);
307 Post\ThreadUser::update($item['uri-id'], $uid, ['hidden' => true], true);
310 if ($item['uid'] == $uid) {
311 self::markForDeletionById($item['id'], Worker::PRIORITY_HIGH);
312 } elseif ($item['uid'] != 0) {
313 Logger::warning('Wrong ownership. Not deleting item', ['id' => $item['id']]);
320 * Mark an item for deletion, delete related data and notify others about it - if it was ours
322 * @param integer $item_id
323 * @param integer $priority Priority for the notification
324 * @return boolean success
325 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
327 public static function markForDeletionById(int $item_id, int $priority = Worker::PRIORITY_HIGH): bool
329 Logger::info('Mark item for deletion by id', ['id' => $item_id, 'callstack' => System::callstack()]);
330 // locate item to be deleted
332 'id', 'uri', 'uri-id', 'uid', 'parent', 'parent-uri-id', 'origin',
333 'deleted', 'resource-id', 'event-id',
334 'verb', 'object-type', 'object', 'target', 'contact-id', 'psid', 'gravity'
336 $item = Post::selectFirst($fields, ['id' => $item_id]);
337 if (!DBA::isResult($item)) {
338 Logger::info('Item not found.', ['id' => $item_id]);
342 if ($item['deleted']) {
343 Logger::info('Item has already been marked for deletion.', ['id' => $item_id]);
347 $parent = Post::selectFirst(['origin'], ['id' => $item['parent']]);
348 if (!DBA::isResult($parent)) {
349 $parent = ['origin' => false];
352 // clean up categories and tags so they don't end up as orphans
353 Post\Category::deleteByURIId($item['uri-id'], $item['uid']);
356 * If item is a link to a photo resource, nuke all the associated photos
357 * (visitors will not have photo resources)
358 * This only applies to photos uploaded from the photos page. Photos inserted into a post do not
359 * generate a resource-id and therefore aren't intimately linked to the item.
361 /// @TODO: this should first check if photo is used elsewhere
362 if ($item['resource-id']) {
363 Photo::delete(['resource-id' => $item['resource-id'], 'uid' => $item['uid']]);
366 // If item is a link to an event, delete the event.
367 if (intval($item['event-id'])) {
368 Event::delete($item['event-id']);
371 // If item has attachments, drop them
372 $attachments = Post\Media::getByURIId($item['uri-id'], [Post\Media::DOCUMENT]);
373 foreach ($attachments as $attachment) {
374 if (preg_match('|attach/(\d+)|', $attachment['url'], $matches)) {
375 Attach::delete(['id' => $matches[1], 'uid' => $item['uid']]);
379 // Set the item to "deleted"
380 $item_fields = ['deleted' => true, 'edited' => DateTimeFormat::utcNow(), 'changed' => DateTimeFormat::utcNow()];
381 Post::update($item_fields, ['id' => $item['id']]);
383 Post\Category::storeTextByURIId($item['uri-id'], $item['uid'], '');
385 if (!Post::exists(["`uri-id` = ? AND `uid` != 0 AND NOT `deleted`", $item['uri-id']])) {
386 self::markForDeletion(['uri-id' => $item['uri-id'], 'uid' => 0, 'deleted' => false], $priority);
389 Post\DeliveryData::delete($item['uri-id']);
391 // If it's the parent of a comment thread, kill all the kids
392 if ($item['gravity'] == self::GRAVITY_PARENT) {
393 self::markForDeletion(['parent' => $item['parent'], 'deleted' => false], $priority);
396 // Is it our comment and/or our thread?
397 if (($item['origin'] || $parent['origin']) && ($item['uid'] != 0)) {
398 // When we delete the original post we will delete all existing copies on the server as well
399 self::markForDeletion(['uri-id' => $item['uri-id'], 'deleted' => false], $priority);
401 // send the notification upstream/downstream
403 Worker::add(['priority' => $priority, 'dont_fork' => true], 'Notifier', Delivery::DELETION, (int)$item['uri-id'], (int)$item['uid']);
405 } elseif ($item['uid'] != 0) {
406 Post\User::update($item['uri-id'], $item['uid'], ['hidden' => true]);
407 Post\ThreadUser::update($item['uri-id'], $item['uid'], ['hidden' => true]);
410 DI::notify()->deleteForItem($item['uri-id']);
411 DI::notification()->deleteForItem($item['uri-id']);
413 Logger::info('Item has been marked for deletion.', ['id' => $item_id]);
419 * Get guid from given item record
421 * @param array $item Item record
422 * @param bool Whether to notify (?)
423 * @return string Guid
425 public static function guid(array $item, bool $notify): string
427 if (!empty($item['guid'])) {
428 return trim($item['guid']);
432 // We have to avoid duplicates. So we create the GUID in form of a hash of the plink or uri.
433 // We add the hash of our own host because our host is the original creator of the post.
434 $prefix_host = DI::baseUrl()->getHost();
438 // We are only storing the post so we create a GUID from the original hostname.
439 if (!empty($item['author-link'])) {
440 $parsed = parse_url($item['author-link']);
441 if (!empty($parsed['host'])) {
442 $prefix_host = $parsed['host'];
446 if (empty($prefix_host) && !empty($item['plink'])) {
447 $parsed = parse_url($item['plink']);
448 if (!empty($parsed['host'])) {
449 $prefix_host = $parsed['host'];
453 if (empty($prefix_host) && !empty($item['uri'])) {
454 $parsed = parse_url($item['uri']);
455 if (!empty($parsed['host'])) {
456 $prefix_host = $parsed['host'];
460 // Is it in the format data@host.tld? - Used for mail contacts
461 if (empty($prefix_host) && !empty($item['author-link']) && strstr($item['author-link'], '@')) {
462 $mailparts = explode('@', $item['author-link']);
463 $prefix_host = array_pop($mailparts);
467 if (!empty($item['plink'])) {
468 $guid = self::guidFromUri($item['plink'], $prefix_host);
469 } elseif (!empty($item['uri'])) {
470 $guid = self::guidFromUri($item['uri'], $prefix_host);
472 $guid = System::createUUID(hash('crc32', $prefix_host));
479 * Returns contact id from given item record
481 * @param array $item Item record
482 * @return int Contact id
484 private static function contactId(array $item): int
486 if ($item['uid'] == 0) {
487 return $item['owner-id'];
490 if ($item['origin']) {
491 $owner = User::getOwnerDataById($item['uid']);
496 $user_contact_id = 0;
497 foreach (['group-link', 'causer-link', 'owner-link', 'author-link'] as $field) {
498 if (empty($item[$field])) {
501 if (!$user_contact_id && Contact::isSharingByURL($item[$field], $item['uid'], true)) {
502 $user_contact_id = Contact::getIdForURL($item[$field], $item['uid']);
503 } elseif (!$contact_id) {
504 $contact_id = Contact::getIdForURL($item[$field]);
508 if ($user_contact_id) {
509 return $user_contact_id;
512 if (!empty($item['causer-id']) && Contact::isSharing($item['causer-id'], $item['uid'], true)) {
513 $cdata = Contact::getPublicAndUserContactID($item['causer-id'], $item['uid']);
514 if (!empty($cdata['user'])) {
515 return $cdata['user'];
523 Logger::warning('contact-id could not be fetched, using self contact instead.', ['uid' => $item['uid'], 'item' => $item]);
524 $self = Contact::selectFirst(['id'], ['self' => true, 'uid' => $item['uid']]);
529 * Write an item array into a spool file to be inserted later.
530 * This command is called whenever there are issues storing an item.
532 * @param array $item The item fields that are to be inserted
535 private static function spool(array $item)
537 // Now we store the data in the spool directory
538 // We use "microtime" to keep the arrival order and "mt_rand" to avoid duplicates
539 $file = 'item-' . round(microtime(true) * 10000) . '-' . mt_rand() . '.msg';
541 $spoolpath = System::getSpoolPath();
542 if ($spoolpath != '') {
543 $spool = $spoolpath . '/' . $file;
545 file_put_contents($spool, json_encode($item));
546 Logger::warning("Item wasn't stored - Item was spooled into file", ['file' => $file]);
551 * Check if the item array is a duplicate
553 * @param array $item Item record
554 * @return boolean is it a duplicate?
556 private static function isDuplicate(array $item): bool
558 // Checking if there is already an item with the same guid
559 $condition = ['guid' => $item['guid'], 'network' => $item['network'], 'uid' => $item['uid']];
560 if (Post::exists($condition)) {
561 Logger::notice('Found already existing item', $condition);
566 'uri-id' => $item['uri-id'], 'uid' => $item['uid'],
567 'network' => [$item['network'], Protocol::DFRN]
569 if (Post::exists($condition)) {
570 Logger::notice('duplicated item with the same uri found.', $condition);
574 // On Friendica and Diaspora the GUID is unique
575 if (in_array($item['network'], [Protocol::DFRN, Protocol::DIASPORA])) {
576 $condition = ['guid' => $item['guid'], 'uid' => $item['uid']];
577 if (Post::exists($condition)) {
578 Logger::notice('duplicated item with the same guid found.', $condition);
581 } elseif ($item['network'] == Protocol::OSTATUS) {
582 // Check for an existing post with the same content. There seems to be a problem with OStatus.
584 "`body` = ? AND `network` = ? AND `created` = ? AND `contact-id` = ? AND `uid` = ?",
585 $item['body'], $item['network'], $item['created'], $item['contact-id'], $item['uid']
587 if (Post::exists($condition)) {
588 Logger::notice('duplicated item with the same body found.', $item);
594 * Check for already added items.
595 * There is a timing issue here that sometimes creates double postings.
596 * An unique index would help - but the limitations of MySQL (maximum size of index values) prevent this.
598 if (($item['uid'] == 0) && Post::exists(['uri-id' => $item['uri-id'], 'uid' => 0])) {
599 Logger::notice('Global item already stored.', ['uri-id' => $item['uri-id'], 'network' => $item['network']]);
607 * Check if the item array is valid
609 * @param array $item Item record
610 * @return boolean item is valid
612 public static function isValid(array $item): bool
614 // When there is no content then we don't post it
615 if (($item['body'] . $item['title'] == '') && empty($item['quote-uri-id']) && empty($item['attachments']) && (empty($item['uri-id']) || !Post\Media::existsByURIId($item['uri-id']))) {
616 Logger::notice('No body, no title.');
620 if (!empty($item['uid'])) {
621 $owner = User::getOwnerDataById($item['uid'], false);
623 Logger::warning('Missing item user owner data', ['uid' => $item['uid']]);
627 if ($owner['account_expired'] || $owner['account_removed']) {
628 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']]);
633 if (!empty($item['author-id']) && Contact::isBlocked($item['author-id'])) {
634 Logger::notice('Author is blocked node-wide', ['author-link' => $item['author-link'], 'item-uri' => $item['uri']]);
638 if (!empty($item['author-link']) && Network::isUrlBlocked($item['author-link'])) {
639 Logger::notice('Author server is blocked', ['author-link' => $item['author-link'], 'item-uri' => $item['uri']]);
643 if (!empty($item['owner-id']) && Contact::isBlocked($item['owner-id'])) {
644 Logger::notice('Owner is blocked node-wide', ['owner-link' => $item['owner-link'], 'item-uri' => $item['uri']]);
648 if (!empty($item['owner-link']) && Network::isUrlBlocked($item['owner-link'])) {
649 Logger::notice('Owner server is blocked', ['owner-link' => $item['owner-link'], 'item-uri' => $item['uri']]);
653 if ($item['verb'] == Activity::FOLLOW) {
654 if (!$item['origin'] && ($item['author-id'] == Contact::getPublicIdByUserId($item['uid']))) {
655 // Our own follow request can be relayed to us. We don't store it to avoid notification chaos.
656 Logger::info("Follow: Don't store not origin follow request", ['parent-uri' => $item['parent-uri']]);
661 'verb' => Activity::FOLLOW, 'uid' => $item['uid'],
662 'parent-uri' => $item['parent-uri'], 'author-id' => $item['author-id']
664 if (Post::exists($condition)) {
665 // It happens that we receive multiple follow requests by the same author - we only store one.
666 Logger::info('Follow: Found existing follow request from author', ['author-id' => $item['author-id'], 'parent-uri' => $item['parent-uri']]);
675 * Check if the item array is too old
677 * @param array $item Item record
678 * @return boolean item is too old
680 public static function isTooOld(array $item): bool
682 // check for create date and expire time
683 $expire_interval = DI::config()->get('system', 'dbclean-expire-days', 0);
685 $user = DBA::selectFirst('user', ['expire'], ['uid' => $item['uid']]);
686 if (DBA::isResult($user) && ($user['expire'] > 0) && (($user['expire'] < $expire_interval) || ($expire_interval == 0))) {
687 $expire_interval = $user['expire'];
690 if (($expire_interval > 0) && !empty($item['created'])) {
691 $expire_date = time() - ($expire_interval * 86400);
692 $created_date = strtotime($item['created']);
693 if ($created_date < $expire_date) {
694 Logger::notice('Item created before expiration interval.', [
695 'created' => date('c', $created_date),
696 'expired' => date('c', $expire_date),
707 * Return the id of the given item array if it has been stored before
709 * @param array $item Item record
710 * @return integer Item id or zero on error
712 private static function getDuplicateID(array $item): int
714 if (empty($item['network']) || in_array($item['network'], Protocol::FEDERATED)) {
716 '`uri-id` = ? AND `uid` = ? AND `network` IN (?, ?, ?, ?)',
719 Protocol::ACTIVITYPUB,
724 $existing = Post::selectFirst(['id', 'network'], $condition);
725 if (DBA::isResult($existing)) {
726 // We only log the entries with a different user id than 0. Otherwise we would have too many false positives
727 if ($item['uid'] != 0) {
728 Logger::notice('Item already existed for user', [
729 'uri-id' => $item['uri-id'],
730 'uid' => $item['uid'],
731 'network' => $item['network'],
732 'existing_id' => $existing['id'],
733 'existing_network' => $existing['network']
737 return $existing['id'];
744 * Fetch the uri-id of the parent for the given uri-id
746 * @param integer $uriid
749 public static function getParent(int $uriid): int
751 $thread_parent = Post::selectFirstPost(['thr-parent-id', 'gravity'], ['uri-id' => $uriid]);
752 if (empty($thread_parent)) {
756 if ($thread_parent['gravity'] == Item::GRAVITY_PARENT) {
760 return self::getParent($thread_parent['thr-parent-id']);
764 * Fetch top-level parent data for the given item array
767 * @return array item array with parent data
770 private static function getTopLevelParent(array $item): array
773 'uid', 'uri', 'parent-uri', 'id', 'deleted',
774 'uri-id', 'parent-uri-id',
775 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid',
776 'wall', 'private', 'origin', 'author-id'
778 $condition = ['uri-id' => [$item['thr-parent-id'], $item['parent-uri-id']], 'uid' => $item['uid']];
779 $params = ['order' => ['id' => false]];
780 $parent = Post::selectFirst($fields, $condition, $params);
782 if (!DBA::isResult($parent) && Post::exists(['uri-id' => [$item['thr-parent-id'], $item['parent-uri-id']], 'uid' => 0])) {
783 $stored = Item::storeForUserByUriId($item['thr-parent-id'], $item['uid'], ['post-reason' => Item::PR_COMPLETION]);
784 if (!$stored && ($item['thr-parent-id'] != $item['parent-uri-id'])) {
785 $stored = Item::storeForUserByUriId($item['parent-uri-id'], $item['uid'], ['post-reason' => Item::PR_COMPLETION]);
788 Logger::info('Stored thread parent item for user', ['uri-id' => $item['thr-parent-id'], 'uid' => $item['uid'], 'stored' => $stored]);
789 $parent = Post::selectFirst($fields, $condition, $params);
793 if (!DBA::isResult($parent)) {
794 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)]);
798 if ($parent['uri-id'] == $parent['parent-uri-id']) {
803 'uri-id' => $parent['parent-uri-id'],
804 'parent-uri-id' => $parent['parent-uri-id'],
805 'uid' => $parent['uid']
807 $params = ['order' => ['id' => false]];
808 $toplevel_parent = Post::selectFirst($fields, $condition, $params);
810 if (!DBA::isResult($toplevel_parent) && $item['origin']) {
811 $stored = Item::storeForUserByUriId($item['parent-uri-id'], $item['uid'], ['post-reason' => Item::PR_COMPLETION]);
812 Logger::info('Stored parent item for user', ['uri-id' => $item['parent-uri-id'], 'uid' => $item['uid'], 'stored' => $stored]);
813 $toplevel_parent = Post::selectFirst($fields, $condition, $params);
816 if (!DBA::isResult($toplevel_parent)) {
817 Logger::notice('item top level parent was not found - ignoring item', ['parent-uri-id' => $parent['parent-uri-id'], 'uid' => $parent['uid']]);
821 return $toplevel_parent;
825 * Get the gravity for the given item array
828 * @return integer gravity
830 private static function getGravity(array $item): int
832 $activity = DI::activity();
834 if (isset($item['gravity'])) {
835 return intval($item['gravity']);
836 } elseif ($item['parent-uri-id'] === $item['uri-id']) {
837 return self::GRAVITY_PARENT;
838 } elseif ($activity->match($item['verb'], Activity::POST)) {
839 return self::GRAVITY_COMMENT;
840 } elseif ($activity->match($item['verb'], Activity::FOLLOW)) {
841 return self::GRAVITY_ACTIVITY;
842 } elseif ($activity->match($item['verb'], Activity::ANNOUNCE)) {
843 return self::GRAVITY_ACTIVITY;
846 Logger::info('Unknown gravity for verb', ['verb' => $item['verb']]);
847 return self::GRAVITY_UNKNOWN; // Should not happen
850 private static function prepareOriginPost(array $item): array
852 $item = DI::contentItem()->initializePost($item);
853 $item = DI::contentItem()->finalizePost($item);
859 * Inserts item record
861 * @param array $item Item array to be inserted
862 * @param int $notify Notification (type?)
863 * @param bool $post_local (???)
864 * @return int Zero means error, otherwise primary key (id) is being returned
866 public static function insert(array $item, int $notify = 0, bool $post_local = true): int
870 $priority = Worker::PRIORITY_HIGH;
872 // If it is a posting where users should get notifications, then define it as wall posting
874 $item = self::prepareOriginPost($item);
876 if (is_int($notify) && in_array($notify, Worker::PRIORITIES)) {
880 $item['network'] = trim(($item['network'] ?? '') ?: Protocol::PHANTOM);
883 $uid = intval($item['uid']);
885 $item['guid'] = self::guid($item, $notify);
886 $item['uri'] = substr(trim($item['uri'] ?? '') ?: self::newURI($item['guid']), 0, 255);
889 $item['uri-id'] = ItemURI::insert(['uri' => $item['uri'], 'guid' => $item['guid']]);
891 // Backward compatibility: parent-uri used to be the direct parent uri.
892 // If it is provided without a thr-parent, it probably is the old behavior.
893 if (empty($item['thr-parent']) || empty($item['parent-uri'])) {
894 $item['thr-parent'] = trim($item['thr-parent'] ?? $item['parent-uri'] ?? $item['uri']);
895 $item['parent-uri'] = $item['thr-parent'];
898 $item['thr-parent-id'] = ItemURI::getIdByURI($item['thr-parent']);
899 $item['parent-uri-id'] = ItemURI::getIdByURI($item['parent-uri']);
901 // Store conversation data
902 $source = $item['source'] ?? '';
903 unset($item['conversation-uri']);
904 unset($item['conversation-href']);
905 unset($item['source']);
908 * Do we already have this item?
909 * We have to check several networks since Friendica posts could be repeated
910 * via OStatus (maybe Diaspora as well)
912 $duplicate = self::getDuplicateID($item);
917 // Additional duplicate checks
918 /// @todo Check why the first duplication check returns the item number and the second a 0
919 if (self::isDuplicate($item)) {
923 if (!isset($item['post-type'])) {
924 $item['post-type'] = empty($item['title']) ? self::PT_NOTE : self::PT_ARTICLE;
927 $defined_permissions = isset($item['allow_cid']) && isset($item['allow_gid']) && isset($item['deny_cid']) && isset($item['deny_gid']) && isset($item['private']);
929 $item['wall'] = intval($item['wall'] ?? 0);
930 $item['extid'] = trim($item['extid'] ?? '');
931 $item['author-name'] = trim($item['author-name'] ?? '');
932 $item['author-link'] = trim($item['author-link'] ?? '');
933 $item['author-avatar'] = trim($item['author-avatar'] ?? '');
934 $item['owner-name'] = trim($item['owner-name'] ?? '');
935 $item['owner-link'] = trim($item['owner-link'] ?? '');
936 $item['owner-avatar'] = trim($item['owner-avatar'] ?? '');
937 $item['received'] = (isset($item['received']) ? DateTimeFormat::utc($item['received']) : DateTimeFormat::utcNow());
938 $item['created'] = (isset($item['created']) ? DateTimeFormat::utc($item['created']) : $item['received']);
939 $item['edited'] = (isset($item['edited']) ? DateTimeFormat::utc($item['edited']) : $item['created']);
940 $item['changed'] = (isset($item['changed']) ? DateTimeFormat::utc($item['changed']) : $item['created']);
941 $item['commented'] = (isset($item['commented']) ? DateTimeFormat::utc($item['commented']) : $item['created']);
942 $item['title'] = substr(trim($item['title'] ?? ''), 0, 255);
943 $item['location'] = trim($item['location'] ?? '');
944 $item['coord'] = trim($item['coord'] ?? '');
945 $item['visible'] = (isset($item['visible']) ? intval($item['visible']) : 1);
946 $item['deleted'] = 0;
947 $item['verb'] = trim($item['verb'] ?? '');
948 $item['object-type'] = trim($item['object-type'] ?? '');
949 $item['object'] = trim($item['object'] ?? '');
950 $item['target-type'] = trim($item['target-type'] ?? '');
951 $item['target'] = trim($item['target'] ?? '');
952 $item['plink'] = substr(trim($item['plink'] ?? ''), 0, 255);
953 $item['allow_cid'] = trim($item['allow_cid'] ?? '');
954 $item['allow_gid'] = trim($item['allow_gid'] ?? '');
955 $item['deny_cid'] = trim($item['deny_cid'] ?? '');
956 $item['deny_gid'] = trim($item['deny_gid'] ?? '');
957 $item['private'] = intval($item['private'] ?? self::PUBLIC);
958 $item['body'] = trim($item['body'] ?? '');
959 $item['raw-body'] = trim($item['raw-body'] ?? $item['body']);
960 $item['app'] = trim($item['app'] ?? '');
961 $item['origin'] = intval($item['origin'] ?? 0);
962 $item['postopts'] = trim($item['postopts'] ?? '');
963 $item['resource-id'] = trim($item['resource-id'] ?? '');
964 $item['event-id'] = intval($item['event-id'] ?? 0);
965 $item['inform'] = trim($item['inform'] ?? '');
966 $item['file'] = trim($item['file'] ?? '');
968 // Communities aren't working with the Diaspora protocol
969 if (($uid != 0) && ($item['network'] == Protocol::DIASPORA)) {
970 $user = User::getById($uid, ['account-type']);
971 if ($user['account-type'] == Contact::TYPE_COMMUNITY) {
972 Logger::info('Community posts are not supported via Diaspora');
977 // Items cannot be stored before they happen ...
978 if ($item['created'] > DateTimeFormat::utcNow()) {
979 $item['created'] = DateTimeFormat::utcNow();
982 // We haven't invented time travel by now.
983 if ($item['edited'] > DateTimeFormat::utcNow()) {
984 $item['edited'] = DateTimeFormat::utcNow();
987 $item['plink'] = ($item['plink'] ?? '') ?: DI::baseUrl() . '/display/' . urlencode($item['guid']);
989 $item['gravity'] = self::getGravity($item);
992 'url' => $item['author-link'], 'name' => $item['author-name'],
993 'photo' => $item['author-avatar'], 'network' => $item['network']
995 $item['author-id'] = ($item['author-id'] ?? 0) ?: Contact::getIdForURL($item['author-link'], 0, null, $default);
998 'url' => $item['owner-link'], 'name' => $item['owner-name'],
999 'photo' => $item['owner-avatar'], 'network' => $item['network']
1001 $item['owner-id'] = ($item['owner-id'] ?? 0) ?: Contact::getIdForURL($item['owner-link'], 0, null, $default);
1003 $item['post-reason'] = self::getPostReason($item);
1005 // Ensure that there is an avatar cache
1006 Contact::checkAvatarCache($item['author-id']);
1007 Contact::checkAvatarCache($item['owner-id']);
1009 $item['contact-id'] = self::contactId($item);
1012 !empty($item['direction']) && in_array($item['direction'], [Conversation::PUSH, Conversation::RELAY]) &&
1013 empty($item['origin']) && self::isTooOld($item)
1015 Logger::info('Item is too old', ['item' => $item]);
1019 if (!self::isValid($item)) {
1023 if ($item['gravity'] !== self::GRAVITY_PARENT) {
1024 $toplevel_parent = self::getTopLevelParent($item);
1025 if (empty($toplevel_parent)) {
1029 $parent_id = $toplevel_parent['id'];
1030 $item['parent-uri'] = $toplevel_parent['uri'];
1031 $item['parent-uri-id'] = $toplevel_parent['uri-id'];
1032 $item['deleted'] = $toplevel_parent['deleted'];
1033 $item['wall'] = $toplevel_parent['wall'];
1035 // Reshares have to keep their permissions to allow groups to work
1036 if (!$defined_permissions && (!$item['origin'] || ($item['verb'] != Activity::ANNOUNCE))) {
1037 $item['allow_cid'] = $toplevel_parent['allow_cid'];
1038 $item['allow_gid'] = $toplevel_parent['allow_gid'];
1039 $item['deny_cid'] = $toplevel_parent['deny_cid'];
1040 $item['deny_gid'] = $toplevel_parent['deny_gid'];
1043 $parent_origin = $toplevel_parent['origin'];
1045 // Don't federate received participation messages
1046 if ($item['verb'] != Activity::FOLLOW) {
1047 $item['wall'] = $toplevel_parent['wall'];
1049 $item['wall'] = false;
1050 // Participations are technical messages, so they are set to "seen" automatically
1051 $item['unseen'] = false;
1055 * If the parent is private, force privacy for the entire conversation
1056 * This differs from the above settings as it subtly allows comments from
1057 * email correspondents to be private even if the overall thread is not.
1059 if (!$defined_permissions && $toplevel_parent['private']) {
1060 $item['private'] = $toplevel_parent['private'];
1063 // If its a post that originated here then tag the thread as "mention"
1064 if ($item['origin'] && $item['uid']) {
1065 DBA::update('post-thread-user', ['mention' => true], ['uri-id' => $item['parent-uri-id'], 'uid' => $item['uid']]);
1066 Logger::info('tagged thread as mention', ['parent' => $parent_id, 'parent-uri-id' => $item['parent-uri-id'], 'uid' => $item['uid']]);
1069 // Update the contact relations
1070 Contact\Relation::store($toplevel_parent['author-id'], $item['author-id'], $item['created']);
1073 $parent_origin = $item['origin'];
1075 if ($item['wall'] && empty($item['conversation'])) {
1076 $item['conversation'] = $item['parent-uri'] . '#context';
1080 if ($item['origin']) {
1082 Photo::setPermissionFromBody($item['body'], $item['uid'], $item['contact-id'], $item['allow_cid'], $item['allow_gid'], $item['deny_cid'], $item['deny_gid'])
1083 && ($item['object-type'] != Activity\ObjectType::EVENT)
1085 $item['object-type'] = Activity\ObjectType::IMAGE;
1088 $item = DI::contentItem()->moveAttachmentsFromBodyToAttach($item);
1091 $item['parent-uri-id'] = ItemURI::getIdByURI($item['parent-uri']);
1092 $item['thr-parent-id'] = ItemURI::getIdByURI($item['thr-parent']);
1094 if (!empty($item['conversation']) && empty($item['conversation-id'])) {
1095 $item['conversation-id'] = ItemURI::getIdByURI($item['conversation']);
1098 // Is this item available in the global items (with uid=0)?
1099 if ($item['uid'] == 0) {
1100 $item['global'] = true;
1102 // Set the global flag on all items if this was a global item entry
1103 Post::update(['global' => true], ['uri-id' => $item['uri-id']]);
1105 $item['global'] = Post::exists(['uid' => 0, 'uri-id' => $item['uri-id']]);
1109 if (!$defined_permissions && !empty($item['allow_cid'] . $item['allow_gid'] . $item['deny_cid'] . $item['deny_gid'])) {
1110 $item['private'] = self::PRIVATE;
1113 if ($notify && $post_local) {
1114 $item['edit'] = false;
1115 $item['parent'] = $parent_id;
1117 // Trigger automatic reactions for addons
1118 if (!isset($item['api_source'])) {
1119 $item['api_source'] = true;
1122 // We have to tell the hooks who we are - this really should be improved
1123 if (!DI::userSession()->getLocalUserId()) {
1124 $_SESSION['authenticated'] = true;
1125 $_SESSION['uid'] = $uid;
1126 $dummy_session = true;
1128 $dummy_session = false;
1131 Hook::callAll('post_local', $item);
1133 if ($dummy_session) {
1134 unset($_SESSION['authenticated']);
1135 unset($_SESSION['uid']);
1137 } elseif (!$notify) {
1138 Hook::callAll('post_remote', $item);
1141 if (!empty($item['cancel'])) {
1142 Logger::notice('post cancelled by addon.');
1146 if (empty($item['vid']) && !empty($item['verb'])) {
1147 $item['vid'] = Verb::getID($item['verb']);
1150 // Creates or assigns the permission set
1151 $item['psid'] = DI::permissionSet()->selectOrCreate(
1152 DI::permissionSetFactory()->createFromString(
1161 if (!empty($item['extid'])) {
1162 $item['external-id'] = ItemURI::getIdByURI($item['extid']);
1165 if ($item['verb'] == Activity::ANNOUNCE) {
1166 self::setOwnerforResharedItem($item);
1169 if (isset($item['attachments'])) {
1170 foreach ($item['attachments'] as $attachment) {
1171 $attachment['uri-id'] = $item['uri-id'];
1172 Post\Media::insert($attachment);
1174 unset($item['attachments']);
1177 if (empty($item['quote-uri-id'])) {
1178 $quote_id = self::getQuoteUriId($item['body']);
1179 if (!empty($quote_id)) {
1180 // This is one of these "should not happen" situations.
1181 // The protocol implementations should already have done this job.
1182 Logger::notice('Quote-uri-id detected in post', ['id' => $quote_id, 'guid' => $item['guid'], 'uri-id' => $item['uri-id'], 'callstack' => System::callstack(20)]);
1183 $item['quote-uri-id'] = $quote_id;
1187 if (!empty($item['quote-uri-id']) && ($item['quote-uri-id'] == $item['uri-id'])) {
1188 Logger::info('Quote-Uri-Id is identical to Uri-Id', ['uri-id' => $item['uri-id'], 'guid' => $item['guid']]);
1189 unset($item['quote-uri-id']);
1192 if (!empty($item['quote-uri-id'])) {
1193 $item['raw-body'] = BBCode::removeSharedData($item['raw-body']);
1194 $item['body'] = BBCode::removeSharedData($item['body']);
1197 // Remove all media attachments from the body and store them in the post-media table
1198 $item['raw-body'] = Post\Media::insertFromBody($item['uri-id'], $item['raw-body']);
1199 $item['raw-body'] = self::setHashtags($item['raw-body']);
1201 $author = Contact::getById($item['author-id'], ['network']);
1202 Post\Media::insertFromRelevantUrl($item['uri-id'], $item['raw-body'], $item['body'], $author['network'] ?? '');
1204 Post\Media::insertFromAttachmentData($item['uri-id'], $item['body']);
1205 $item['body'] = BBCode::removeAttachment($item['body']);
1206 $item['raw-body'] = BBCode::removeAttachment($item['raw-body']);
1208 // Check for hashtags in the body and repair or add hashtag links
1209 $item['body'] = self::setHashtags($item['body']);
1211 $item['language'] = self::getLanguage($item);
1213 $notify_type = Delivery::POST;
1215 // Filling item related side tables
1216 if (!empty($item['attach'])) {
1217 Post\Media::insertFromAttachment($item['uri-id'], $item['attach']);
1220 if (empty($item['event-id'])) {
1221 unset($item['event-id']);
1223 $ev = Event::fromBBCode($item['body']);
1224 if ((!empty($ev['desc']) || !empty($ev['summary'])) && !empty($ev['start'])) {
1225 Logger::info('Event found.');
1226 $ev['cid'] = $item['contact-id'];
1227 $ev['uid'] = $item['uid'];
1228 $ev['uri'] = $item['uri'];
1229 $ev['edited'] = $item['edited'];
1230 $ev['private'] = $item['private'];
1231 $ev['guid'] = $item['guid'];
1232 $ev['plink'] = $item['plink'];
1233 $ev['network'] = $item['network'];
1234 $ev['protocol'] = $item['protocol'] ?? Conversation::PARCEL_UNKNOWN;
1235 $ev['direction'] = $item['direction'] ?? Conversation::UNKNOWN;
1236 $ev['source'] = $item['source'] ?? '';
1238 $event = DBA::selectFirst('event', ['id'], ['uri' => $item['uri'], 'uid' => $item['uid']]);
1239 if (DBA::isResult($event)) {
1240 $ev['id'] = $event['id'];
1243 $event_id = Event::store($ev);
1244 $item = Event::getItemArrayForImportedId($event_id, $item);
1246 Logger::info('Event was stored', ['id' => $event_id]);
1250 if (empty($item['causer-id'])) {
1251 unset($item['causer-id']);
1254 if (in_array($item['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN])) {
1255 $content_warning = BBCode::getAbstract($item['body'], Protocol::ACTIVITYPUB);
1256 if (!empty($content_warning) && empty($item['content-warning'])) {
1257 $item['content-warning'] = BBCode::toPlaintext($content_warning);
1261 $inserted = Post::insert($item['uri-id'], $item);
1263 if ($item['gravity'] == self::GRAVITY_PARENT) {
1264 Post\Thread::insert($item['uri-id'], $item);
1267 // The content of activities normally doesn't matter - except for likes from Misskey
1268 if (!in_array($item['verb'], self::ACTIVITIES) || in_array($item['verb'], [Activity::LIKE, Activity::DISLIKE]) && !empty($item['body']) && (mb_strlen($item['body']) == 1)) {
1269 Post\Content::insert($item['uri-id'], $item);
1272 $item['parent'] = $parent_id;
1274 // Create Diaspora signature
1275 if ($item['origin'] && empty($item['diaspora_signed_text']) && ($item['gravity'] != self::GRAVITY_PARENT)) {
1276 $signed = Diaspora::createCommentSignature($item);
1277 if (!empty($signed)) {
1278 $item['diaspora_signed_text'] = json_encode($signed);
1282 if (!empty($item['diaspora_signed_text'])) {
1283 DBA::replace('diaspora-interaction', ['uri-id' => $item['uri-id'], 'interaction' => $item['diaspora_signed_text']]);
1286 // Attached file links
1287 if (!empty($item['file'])) {
1288 Post\Category::storeTextByURIId($item['uri-id'], $item['uid'], $item['file']);
1291 // Delivery relevant data
1292 $delivery_data = Post\DeliveryData::extractFields($item);
1294 if (!empty($item['origin']) || !empty($item['wall']) || !empty($delivery_data['postopts']) || !empty($delivery_data['inform'])) {
1295 Post\DeliveryData::insert($item['uri-id'], $delivery_data);
1298 // Store tags from the body if this hadn't been handled previously in the protocol classes
1299 if (!Tag::existsForPost($item['uri-id'])) {
1300 Tag::storeFromBody($item['uri-id'], $item['body']);
1303 $condition = ['uri-id' => $item['uri-id'], 'uid' => $item['uid']];
1304 if (Post::exists($condition)) {
1305 Logger::notice('Item is already inserted - aborting', $condition);
1309 $post_user_id = Post\User::insert($item['uri-id'], $item['uid'], $item);
1310 if (!$post_user_id) {
1311 Logger::notice('Post-User is already inserted - aborting', ['uid' => $item['uid'], 'uri-id' => $item['uri-id']]);
1315 if ($item['gravity'] == self::GRAVITY_PARENT) {
1316 $item['post-user-id'] = $post_user_id;
1317 Post\ThreadUser::insert($item['uri-id'], $item['uid'], $item);
1320 Logger::notice('created item', ['post-id' => $post_user_id, 'uid' => $item['uid'], 'network' => $item['network'], 'uri-id' => $item['uri-id'], 'guid' => $item['guid']]);
1322 $posted_item = Post::selectFirst(self::ITEM_FIELDLIST, ['post-user-id' => $post_user_id]);
1323 if (!DBA::isResult($posted_item)) {
1324 // On failure store the data into a spool file so that the "SpoolPost" worker can try again later.
1325 Logger::warning('Could not store item. it will be spooled', ['id' => $post_user_id]);
1326 self::spool($orig_item);
1330 // update the commented timestamp on the parent
1331 if (DI::config()->get('system', 'like_no_comment')) {
1332 // Update when it is a comment
1333 $update_commented = in_array($posted_item['gravity'], [self::GRAVITY_PARENT, self::GRAVITY_COMMENT]);
1335 // Update when it isn't a follow or tag verb
1336 $update_commented = !in_array($posted_item['verb'], [Activity::FOLLOW, Activity::TAG]);
1339 if ($update_commented) {
1340 $fields = ['commented' => DateTimeFormat::utcNow(), 'changed' => DateTimeFormat::utcNow()];
1342 $fields = ['changed' => DateTimeFormat::utcNow()];
1345 Post::update($fields, ['uri-id' => $posted_item['parent-uri-id'], 'uid' => $posted_item['uid']]);
1347 // In that function we check if this is a group post. Additionally we delete the item under certain circumstances
1348 if (self::tagDeliver($posted_item['uid'], $post_user_id)) {
1349 // Get the user information for the logging
1350 $user = User::getById($uid);
1352 Logger::notice('Item had been deleted', ['id' => $post_user_id, 'user' => $uid, 'account-type' => $user['account-type']]);
1357 DI::contentItem()->postProcessPost($posted_item);
1359 Hook::callAll('post_remote_end', $posted_item);
1362 if ($posted_item['gravity'] === self::GRAVITY_PARENT) {
1363 self::addShadow($post_user_id);
1365 self::addShadowPost($post_user_id);
1368 self::updateContact($posted_item);
1370 Post\UserNotification::setNotification($posted_item['uri-id'], $posted_item['uid']);
1372 // Distribute items to users who subscribed to their tags
1373 self::distributeByTags($posted_item);
1375 // Automatically reshare the item if the "remote_self" option is selected
1376 self::autoReshare($posted_item);
1378 $transmit = $notify || ($posted_item['visible'] && ($parent_origin || $posted_item['origin']));
1381 if ($posted_item['uid'] && Contact\User::isBlocked($posted_item['author-id'], $posted_item['uid'])) {
1382 Logger::info('Message from blocked author will not be relayed', ['item' => $posted_item['id'], 'uri' => $posted_item['uri'], 'cid' => $posted_item['author-id']]);
1385 if ($transmit && $posted_item['uid'] && Contact\User::isBlocked($posted_item['owner-id'], $posted_item['uid'])) {
1386 Logger::info('Message from blocked owner will not be relayed', ['item' => $posted_item['id'], 'uri' => $posted_item['uri'], 'cid' => $posted_item['owner-id']]);
1389 if ($transmit && !empty($posted_item['causer-id']) && $posted_item['uid'] && Contact\User::isBlocked($posted_item['causer-id'], $posted_item['uid'])) {
1390 Logger::info('Message from blocked causer will not be relayed', ['item' => $posted_item['id'], 'uri' => $posted_item['uri'], 'cid' => $posted_item['causer-id']]);
1394 // Don't relay participation messages
1395 if (($posted_item['verb'] == Activity::FOLLOW) &&
1396 (!$posted_item['origin'] || ($posted_item['author-id'] != Contact::getPublicIdByUserId($uid)))
1398 Logger::info('Participation messages will not be relayed', ['item' => $posted_item['id'], 'uri' => $posted_item['uri'], 'verb' => $posted_item['verb']]);
1403 if (!empty($source) && ($transmit || DI::config()->get('debug', 'store_source'))) {
1404 Post\Activity::insert($item['uri-id'], $source);
1408 Worker::add(['priority' => $priority, 'dont_fork' => true], 'Notifier', $notify_type, (int)$posted_item['uri-id'], (int)$posted_item['uid']);
1411 // Fill the cache with the rendered content.
1412 if (in_array($posted_item['gravity'], [self::GRAVITY_PARENT, self::GRAVITY_COMMENT]) && ($posted_item['uid'] == 0)) {
1413 self::updateDisplayCache($posted_item['uri-id']);
1417 Post\Engagement::storeFromItem($posted_item);
1420 return $post_user_id;
1424 * Fetch the post reason for a given item array
1426 * @param array $item
1430 public static function getPostReason(array $item): int
1432 $actor = ($item['gravity'] == self::GRAVITY_PARENT) ? $item['owner-id'] : $item['author-id'];
1433 if (empty($item['origin']) && ($item['uid'] != 0) && Contact::isSharing($actor, $item['uid'])) {
1434 return self::PR_FOLLOWER;
1437 if (!empty($item['origin']) && empty($item['post-reason'])) {
1438 return self::PR_LOCAL;
1441 return $item['post-reason'] ?? self::PR_NONE;
1445 * Update the display cache
1447 * @param integer $uri_id
1449 * @throws InternalServerErrorException
1450 * @throws \ImagickException
1452 public static function updateDisplayCache(int $uri_id)
1454 $item = Post::selectFirst(self::DISPLAY_FIELDLIST, ['uri-id' => $uri_id]);
1459 self::prepareBody($item, false, false, true);
1463 * Change the owner of a parent item if it had been shared by a group
1465 * (public) group posts in the new format consist of the regular post by the author
1466 * followed by an announce message sent from the group account.
1467 * Changing the owner helps in grouping group posts.
1469 * @param array $item
1472 private static function setOwnerforResharedItem(array $item)
1474 $parent = Post::selectFirst(
1475 ['id', 'causer-id', 'owner-id', 'author-id', 'author-link', 'origin', 'post-reason'],
1476 ['uri-id' => $item['thr-parent-id'], 'uid' => $item['uid']]
1478 if (!DBA::isResult($parent)) {
1479 Logger::error('Parent not found', ['uri-id' => $item['thr-parent-id'], 'uid' => $item['uid']]);
1483 $author = Contact::selectFirst(['url', 'contact-type', 'network'], ['id' => $item['author-id']]);
1484 if (!DBA::isResult($author)) {
1485 Logger::error('Author not found', ['id' => $item['author-id']]);
1489 $self_contact = Contact::selectFirst(['id'], ['uid' => $item['uid'], 'self' => true]);
1490 $self = !empty($self_contact) ? $self_contact['id'] : 0;
1492 $cid = Contact::getIdForURL($author['url'], $item['uid']);
1493 if (empty($cid) || (!Contact::isSharing($cid, $item['uid']) && ($cid != $self))) {
1494 Logger::info('The resharer is not a following contact: quit', ['resharer' => $author['url'], 'uid' => $item['uid'], 'cid' => $cid]);
1498 if ($author['contact-type'] != Contact::TYPE_COMMUNITY) {
1499 if ($parent['post-reason'] == self::PR_ANNOUNCEMENT) {
1500 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']]);
1504 if (Contact::isSharing($parent['owner-id'], $item['uid'])) {
1505 Logger::info('The resharer is no group: quit', ['resharer' => $item['author-id'], 'owner' => $parent['owner-id'], 'author' => $parent['author-id'], 'uid' => $item['uid']]);
1510 self::update(['post-reason' => self::PR_ANNOUNCEMENT, 'causer-id' => $item['author-id']], ['id' => $parent['id']]);
1511 Logger::info('Set announcement post-reason', ['uri-id' => $item['uri-id'], 'thr-parent-id' => $item['thr-parent-id'], 'uid' => $item['uid']]);
1515 * Distribute the given item to users who subscribed to their tags
1517 * @param array $item Processed item
1519 private static function distributeByTags(array $item)
1521 if (($item['uid'] != 0) || ($item['gravity'] != self::GRAVITY_PARENT) || !in_array($item['network'], Protocol::FEDERATED)) {
1525 foreach (Tag::getUIDListByURIId($item['uri-id']) as $uid => $tags) {
1526 $stored = self::storeForUserByUriId($item['uri-id'], $uid, ['post-reason' => self::PR_TAG]);
1527 Logger::info('Stored item for users', ['uri-id' => $item['uri-id'], 'uid' => $uid, 'stored' => $stored]);
1528 foreach ($tags as $tag) {
1529 $stored = Category::storeFileByURIId($item['uri-id'], $uid, Category::SUBCRIPTION, $tag);
1530 Logger::debug('Stored tag subscription for user', ['uri-id' => $item['uri-id'], 'uid' => $uid, $tag, 'stored' => $stored]);
1536 * Distributes public items to the receivers
1538 * @param integer $itemid Item ID that should be added
1539 * @param string $signed_text Original text (for Diaspora signatures), JSON encoded.
1540 * @throws \Exception
1542 public static function distribute(int $itemid, string $signed_text = '')
1544 $condition = ["`id` IN (SELECT `parent` FROM `post-user-view` WHERE `id` = ?)", $itemid];
1545 $parent = Post::selectFirst(['owner-id'], $condition);
1546 if (!DBA::isResult($parent)) {
1547 Logger::warning('Item not found', ['condition' => $condition]);
1551 // Only distribute public items from native networks
1553 'id' => $itemid, 'uid' => 0,
1554 'network' => array_merge(Protocol::FEDERATED, ['']),
1555 'visible' => true, 'deleted' => false, 'private' => [self::PUBLIC, self::UNLISTED]
1557 $item = Post::selectFirst(array_merge(self::ITEM_FIELDLIST, ['protocol']), $condition);
1558 if (!DBA::isResult($item)) {
1559 Logger::warning('Item not found', ['condition' => $condition]);
1563 $origin = $item['origin'];
1567 /// @todo add a field "pcid" in the contact table that refers to the public contact id.
1568 $owner = DBA::selectFirst('contact', ['url', 'nurl', 'alias'], ['id' => $parent['owner-id']]);
1569 if (!DBA::isResult($owner)) {
1573 $condition = ['nurl' => $owner['nurl'], 'rel' => [Contact::SHARING, Contact::FRIEND]];
1574 $contacts = DBA::select('contact', ['uid'], $condition);
1575 while ($contact = DBA::fetch($contacts)) {
1576 if ($contact['uid'] == 0) {
1580 $users[$contact['uid']] = $contact['uid'];
1582 DBA::close($contacts);
1584 $condition = ['alias' => $owner['url'], 'rel' => [Contact::SHARING, Contact::FRIEND]];
1585 $contacts = DBA::select('contact', ['uid'], $condition);
1586 while ($contact = DBA::fetch($contacts)) {
1587 if ($contact['uid'] == 0) {
1591 $users[$contact['uid']] = $contact['uid'];
1593 DBA::close($contacts);
1595 if (!empty($owner['alias'])) {
1596 $condition = ['nurl' => Strings::normaliseLink($owner['alias']), 'rel' => [Contact::SHARING, Contact::FRIEND]];
1597 $contacts = DBA::select('contact', ['uid'], $condition);
1598 while ($contact = DBA::fetch($contacts)) {
1599 if ($contact['uid'] == 0) {
1603 $users[$contact['uid']] = $contact['uid'];
1605 DBA::close($contacts);
1610 if ($item['uri-id'] != $item['parent-uri-id']) {
1611 $parents = Post::select(['uid', 'origin'], ["`uri-id` = ? AND `uid` != 0", $item['parent-uri-id']]);
1612 while ($parent = Post::fetch($parents)) {
1613 $users[$parent['uid']] = $parent['uid'];
1614 if ($parent['origin'] && !$origin) {
1615 $origin_uid = $parent['uid'];
1618 DBA::close($parents);
1621 foreach ($users as $uid) {
1622 if ($origin_uid == $uid) {
1623 $item['diaspora_signed_text'] = $signed_text;
1625 $item['post-reason'] = self::PR_DISTRIBUTE;
1626 self::storeForUser($item, $uid);
1631 * Store a public item defined by their URI-ID for the given users
1633 * @param integer $uri_id URI-ID of the given item
1634 * @param integer $uid The user that will receive the item entry
1635 * @param array $fields Additional fields to be stored
1636 * @param integer $source_uid User id of the source post
1637 * @return integer stored item id
1639 public static function storeForUserByUriId(int $uri_id, int $uid, array $fields = [], int $source_uid = 0): int
1641 if ($uid == $source_uid) {
1642 Logger::warning('target UID must not be be equal to the source UID', ['uri-id' => $uri_id, 'uid' => $uid]);
1646 $item = Post::selectFirst(array_merge(self::ITEM_FIELDLIST, ['protocol']), ['uri-id' => $uri_id, 'uid' => $source_uid]);
1647 if (!DBA::isResult($item)) {
1648 Logger::warning('Item could not be fetched', ['uri-id' => $uri_id, 'uid' => $source_uid]);
1652 if (($uid != 0) && ($item['gravity'] == self::GRAVITY_PARENT)) {
1653 $owner = User::getOwnerDataById($uid);
1654 if (($owner['contact-type'] == User::ACCOUNT_TYPE_COMMUNITY) && !Tag::isMentioned($uri_id, $owner['url'])) {
1655 Logger::info('Target user is a group but is not mentioned here, thread will not be stored', ['uid' => $uid, 'uri-id' => $uri_id]);
1660 if (($source_uid == 0) && (($item['private'] == self::PRIVATE) || !in_array($item['network'], Protocol::FEDERATED))) {
1661 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']]);
1665 $item['post-reason'] = self::PR_STORED;
1667 $item = array_merge($item, $fields);
1669 if (($uid != 0) && Contact::isSharing(($item['gravity'] == Item::GRAVITY_PARENT) ? $item['owner-id'] : $item['author-id'], $uid)) {
1670 $item['post-reason'] = self::PR_FOLLOWER;
1673 $is_reshare = ($item['gravity'] == self::GRAVITY_ACTIVITY) && ($item['verb'] == Activity::ANNOUNCE);
1675 if (($uid != 0) && (($item['gravity'] == self::GRAVITY_PARENT) || $is_reshare) &&
1676 DI::pConfig()->get($uid, 'system', 'accept_only_sharer') == self::COMPLETION_NONE &&
1677 !in_array($item['post-reason'], [self::PR_FOLLOWER, self::PR_TAG, self::PR_TO, self::PR_CC, self::PR_ACTIVITY, self::PR_AUDIENCE])
1679 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']]);
1683 $causer = $item['causer-id'] ?: $item['author-id'];
1685 if (($uri_id != $item['parent-uri-id']) && ($item['gravity'] == self::GRAVITY_COMMENT) && !Post::exists(['uri-id' => $item['parent-uri-id'], 'uid' => $uid])) {
1686 if (!self::fetchParent($item['parent-uri-id'], $uid, $causer)) {
1687 Logger::info('Parent post had not been added', ['uri-id' => $item['parent-uri-id'], 'uid' => $uid, 'causer' => $causer]);
1690 Logger::info('Fetched parent post', ['uri-id' => $item['parent-uri-id'], 'uid' => $uid, 'causer' => $causer]);
1691 } elseif (($uri_id != $item['thr-parent-id']) && $is_reshare && !Post::exists(['uri-id' => $item['thr-parent-id'], 'uid' => $uid])) {
1692 if (!self::fetchParent($item['thr-parent-id'], $uid, $causer)) {
1693 Logger::info('Thread parent had not been added', ['uri-id' => $item['thr-parent-id'], 'uid' => $uid, 'causer' => $causer]);
1696 Logger::info('Fetched thread parent', ['uri-id' => $item['thr-parent-id'], 'uid' => $uid, 'causer' => $causer]);
1699 $stored = self::storeForUser($item, $uid);
1700 Logger::info('Item stored for user', ['uri-id' => $item['uri-id'], 'uid' => $uid, 'causer' => $causer, 'source-uid' => $source_uid, 'stored' => $stored]);
1705 * Fetch the parent with the given uri-id
1707 * @param integer $uri_id
1708 * @param integer $uid
1709 * @param integer $causer
1713 private static function fetchParent(int $uri_id, int $uid, int $causer): int
1715 // Fetch the origin user for the post
1716 $origin_uid = self::GetOriginUidForUriId($uri_id, $uid);
1717 if (is_null($origin_uid)) {
1718 Logger::info('Origin item was not found', ['uid' => $uid, 'uri-id' => $uri_id]);
1722 return self::storeForUserByUriId($uri_id, $uid, ['causer-id' => $causer, 'post-reason' => self::PR_FETCHED], $origin_uid);
1726 * Returns the origin uid of a post if the given user is allowed to see it.
1732 private static function GetOriginUidForUriId(int $uriid, int $uid)
1734 if (Post::exists(['uri-id' => $uriid, 'uid' => $uid])) {
1738 $post = Post::selectFirst(['uid', 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid', 'private'], ['uri-id' => $uriid, 'origin' => true]);
1739 if (!empty($post)) {
1740 if (in_array($post['private'], [Item::PUBLIC, Item::UNLISTED])) {
1741 return $post['uid'];
1744 $pcid = Contact::getPublicIdByUserId($uid);
1749 foreach (Item::enumeratePermissions($post, true) as $receiver) {
1750 if ($receiver == $pcid) {
1751 return $post['uid'];
1758 if (Post::exists(['uri-id' => $uriid, 'uid' => 0])) {
1762 // When the post belongs to a a group then all group users are allowed to access it
1763 foreach (Tag::getByURIId($uriid, [Tag::MENTION, Tag::EXCLUSIVE_MENTION]) as $tag) {
1764 if (DBA::exists('contact', ['uid' => $uid, 'nurl' => Strings::normaliseLink($tag['url']), 'contact-type' => Contact::TYPE_COMMUNITY])) {
1765 $target_uid = User::getIdForURL($tag['url']);
1766 if (!empty($target_uid)) {
1776 * Store a public item array for the given users
1778 * @param array $item The item entry that will be stored
1779 * @param integer $uid The user that will receive the item entry
1780 * @return integer stored item id
1781 * @throws \Exception
1783 private static function storeForUser(array $item, int $uid): int
1785 $post = Post::selectFirst(['id'], ['uri-id' => $item['uri-id'], 'uid' => $uid]);
1786 if (!empty($post['id'])) {
1787 if (!empty($item['event-id'])) {
1788 $event_post = Post::selectFirst(['event-id'], ['uri-id' => $item['uri-id'], 'uid' => $uid]);
1789 if (!empty($event_post['event-id'])) {
1790 $event = DBA::selectFirst('event', ['edited', 'start', 'finish', 'summary', 'desc', 'location', 'nofinish'], ['id' => $item['event-id']]);
1791 if (!empty($event)) {
1792 // We aren't using "Event::store" here, since we don't want to trigger any further action
1793 $ret = DBA::update('event', $event, ['id' => $event_post['event-id']]);
1794 Logger::info('Event updated', ['uid' => $uid, 'source-event' => $item['event-id'], 'target-event' => $event_post['event-id'], 'ret' => $ret]);
1798 Logger::info('Item already exists', ['uri-id' => $item['uri-id'], 'uid' => $uid, 'id' => $post['id']]);
1802 // Data from the "post-user" table
1804 unset($item['mention']);
1805 unset($item['starred']);
1806 unset($item['unseen']);
1807 unset($item['psid']);
1808 unset($item['pinned']);
1809 unset($item['ignored']);
1810 unset($item['pubmail']);
1811 unset($item['event-id']);
1812 unset($item['hidden']);
1813 unset($item['notification-type']);
1815 // Data from the "post-delivery-data" table
1816 unset($item['postopts']);
1817 unset($item['inform']);
1819 $item['uid'] = $uid;
1820 $item['origin'] = 0;
1824 if ($item['gravity'] == self::GRAVITY_PARENT) {
1825 $contact = DBA::selectFirst('contact', [], ['id' => $item['contact-id'], 'self' => false]);
1826 if (DBA::isResult($contact)) {
1827 $notify = self::isRemoteSelf($contact, $item);
1828 $item['wall'] = (bool)$notify;
1832 $item['contact-id'] = self::contactId($item);
1833 $distributed = self::insert($item, $notify);
1835 if (!$distributed) {
1836 Logger::info("Distributed item wasn't stored", ['uri-id' => $item['uri-id'], 'user' => $uid]);
1838 Logger::info('Distributed item was stored', ['uri-id' => $item['uri-id'], 'user' => $uid, 'stored' => $distributed]);
1840 return $distributed;
1844 * Add a shadow entry for a given item id that is a thread starter
1846 * We store every public item entry additionally with the user id "0".
1847 * This is used for the community page and for the search.
1848 * It is planned that in the future we will store public item entries only once.
1850 * @param integer $itemid Item ID that should be added
1851 * @throws \Exception
1853 private static function addShadow(int $itemid)
1855 $fields = ['uid', 'private', 'visible', 'deleted', 'network', 'uri-id'];
1856 $condition = ['id' => $itemid, 'gravity' => self::GRAVITY_PARENT];
1857 $item = Post::selectFirst($fields, $condition);
1859 if (!DBA::isResult($item)) {
1863 // is it already a copy?
1864 if (($itemid == 0) || ($item['uid'] == 0)) {
1868 // Is it a visible public post?
1869 if (!$item["visible"] || $item["deleted"] || ($item["private"] == self::PRIVATE)) {
1873 // is it an entry from a connector? Only add an entry for natively connected networks
1874 if (!in_array($item["network"], array_merge(Protocol::FEDERATED, ['']))) {
1878 if (Post::exists(['uri-id' => $item['uri-id'], 'uid' => 0])) {
1882 $item = Post::selectFirst(array_merge(self::ITEM_FIELDLIST, ['protocol']), ['id' => $itemid]);
1884 if (DBA::isResult($item)) {
1885 // Preparing public shadow (removing user specific data)
1888 unset($item['parent']);
1889 unset($item['wall']);
1890 unset($item['mention']);
1891 unset($item['origin']);
1892 unset($item['starred']);
1893 unset($item['postopts']);
1894 unset($item['inform']);
1895 unset($item['post-reason']);
1896 if ($item['uri-id'] == $item['parent-uri-id']) {
1897 $item['contact-id'] = $item['owner-id'];
1899 $item['contact-id'] = $item['author-id'];
1902 $public_shadow = self::insert($item);
1904 Logger::info('Stored public shadow', ['thread' => $itemid, 'id' => $public_shadow]);
1909 * Add a shadow entry for a given item id that is a comment
1911 * This function does the same like the function above - but for comments
1913 * @param integer $itemid Item ID that should be added
1914 * @throws \Exception
1916 private static function addShadowPost(int $itemid)
1918 $item = Post::selectFirst(array_merge(self::ITEM_FIELDLIST, ['protocol']), ['id' => $itemid]);
1919 if (!DBA::isResult($item)) {
1923 // Is it a toplevel post?
1924 if ($item['gravity'] == self::GRAVITY_PARENT) {
1925 self::addShadow($itemid);
1929 // Is this a shadow entry?
1930 if ($item['uid'] == 0) {
1934 // Is there a shadow parent?
1935 if (!Post::exists(['uri-id' => $item['parent-uri-id'], 'uid' => 0])) {
1939 // Is there already a shadow entry?
1940 if (Post::exists(['uri-id' => $item['uri-id'], 'uid' => 0])) {
1944 // Save "origin" and "parent" state
1945 $origin = $item['origin'];
1946 $parent = $item['parent'];
1948 // Preparing public shadow (removing user specific data)
1951 unset($item['parent']);
1952 unset($item['wall']);
1953 unset($item['mention']);
1954 unset($item['origin']);
1955 unset($item['starred']);
1956 unset($item['postopts']);
1957 unset($item['inform']);
1958 unset($item['post-reason']);
1959 $item['contact-id'] = Contact::getIdForURL($item['author-link']);
1961 $public_shadow = self::insert($item);
1963 Logger::info('Stored public shadow', ['uri-id' => $item['uri-id'], 'id' => $public_shadow]);
1965 // If this was a comment to a Diaspora post we don't get our comment back.
1966 // This means that we have to distribute the comment by ourselves.
1967 if ($origin && Post::exists(['id' => $parent, 'network' => Protocol::DIASPORA])) {
1968 self::distribute($public_shadow);
1973 * Adds a language specification in a "language" element of given $arr.
1974 * Expects "body" element to exist in $arr.
1976 * @param array $item
1977 * @return string detected language
1978 * @throws \Text_LanguageDetect_Exception
1980 private static function getLanguage(array $item): string
1982 if (!empty($item['language'])) {
1983 return $item['language'];
1986 if (!in_array($item['gravity'], [self::GRAVITY_PARENT, self::GRAVITY_COMMENT]) || empty($item['body'])) {
1990 $languages = self::getLanguageArray(trim($item['title'] . "\n" . $item['body']), 3, $item['uri-id'], $item['author-id']);
1991 if (empty($languages)) {
1995 return json_encode($languages);
1999 * Get a language array from a given text
2001 * @param string $body
2002 * @param integer $count
2003 * @param integer $uri_id
2004 * @param integer $author_id
2007 public static function getLanguageArray(string $body, int $count, int $uri_id = 0, int $author_id = 0): array
2009 $naked_body = BBCode::toSearchText($body, $uri_id);
2011 if ((count(explode(' ', $naked_body)) < 10) && (mb_strlen($naked_body) < 30) && $author_id) {
2012 $author = Contact::selectFirst(['about'], ['id' => $author_id]);
2013 if (!empty($author['about'])) {
2014 $about = BBCode::toSearchText($author['about'], 0);
2015 $about = self::getDominantLanguage($about);
2016 Logger::debug('About field added', ['author' => $author_id, 'body' => $naked_body, 'about' => $about]);
2017 $naked_body .= ' ' . $about;
2021 if (empty($naked_body)) {
2025 $naked_body = self::getDominantLanguage($naked_body);
2027 $availableLanguages = DI::l10n()->getAvailableLanguages(true);
2028 $availableLanguages = DI::l10n()->convertForLanguageDetection($availableLanguages);
2030 $ld = new Language(array_keys($availableLanguages));
2031 $languages = $ld->detect($naked_body)->limit(0, $count)->close() ?: [];
2034 'text' => $naked_body,
2035 'detected' => $languages,
2036 'uri-id' => $uri_id,
2039 Hook::callAll('detect_languages', $data);
2040 $languages = $data['detected'];
2046 * Check if latin or non latin are dominant in the body and only return the dominant one
2048 * @param string $body
2051 private static function getDominantLanguage(string $body): string
2055 for ($i = 0; $i < mb_strlen($body); $i++) {
2056 $character = mb_substr($body, $i, 1);
2057 $ord = mb_ord($character);
2059 // We add the most common characters to both strings.
2060 if (($ord <= 64) || ($ord >= 91 && $ord <= 96) || ($ord >= 123 && $ord <= 191) || in_array($ord, [215, 247]) || ($ord >= 697 && $ord <= 735) || ($ord > 65535)) {
2061 $latin .= $character;
2062 $non_latin .= $character;
2063 } elseif ($ord < 768) {
2064 $latin .= $character;
2066 $non_latin .= $character;
2069 return (mb_strlen($latin) > mb_strlen($non_latin)) ? $latin : $non_latin;
2072 public static function getLanguageMessage(array $item): string
2074 $iso639 = new \Matriphe\ISO639\ISO639;
2076 $used_languages = '';
2077 foreach (json_decode($item['language'], true) as $language => $reliability) {
2078 $used_languages .= $iso639->languageByCode1($language) . ' (' . $language . "): " . number_format($reliability, 5) . '\n';
2080 $used_languages = DI::l10n()->t('Detected languages in this post:\n%s', $used_languages);
2081 return $used_languages;
2085 * Creates an unique guid out of a given uri.
2086 * This function is used for messages outside the fediverse (Connector posts, feeds, Mails, ...)
2087 * Posts that are created on this system are using System::createUUID.
2088 * Received ActivityPub posts are using Processor::getGUIDByURL.
2090 * @param string $uri uri of an item entry
2091 * @param string|null $host hostname for the GUID prefix
2092 * @return string Unique guid
2093 * @throws \Exception
2095 public static function guidFromUri(string $uri, string $host = null): string
2097 // Our regular guid routine is using this kind of prefix as well
2098 // We have to avoid that different routines could accidentally create the same value
2099 $parsed = parse_url($uri);
2101 // Remove the scheme to make sure that "https" and "http" doesn't make a difference
2102 unset($parsed['scheme']);
2104 $hostPart = $host ?: $parsed['host'] ?? '';
2106 Logger::warning('Empty host GUID part', ['uri' => $uri, 'host' => $host, 'parsed' => $parsed, 'callstack' => System::callstack(10)]);
2109 // Glue it together to be able to make a hash from it
2110 if (!empty($parsed)) {
2111 $host_id = implode('/', $parsed);
2116 // Use a mixture of several hashes to provide some GUID like experience
2117 return hash('crc32', $hostPart) . '-' . hash('joaat', $host_id) . '-' . hash('fnv164', $host_id);
2121 * generate an unique URI
2123 * @param string $guid An existing GUID (Otherwise it will be generated)
2126 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2128 public static function newURI(string $guid = ''): string
2131 $guid = System::createUUID();
2134 return DI::baseUrl() . '/objects/' . $guid;
2138 * Set "success_update" and "last-item" to the date of the last time we heard from this contact
2140 * This can be used to filter for inactive contacts.
2141 * Only do this for public postings to avoid privacy problems, since poco data is public.
2142 * Don't set this value if it isn't from the owner (could be an author that we don't know)
2144 * @param array $arr Contains the just posted item record
2145 * @throws \Exception
2147 private static function updateContact(array $arr)
2149 // Unarchive the author
2150 $contact = DBA::selectFirst('contact', [], ['id' => $arr["author-id"]]);
2151 if (DBA::isResult($contact)) {
2152 Contact::unmarkForArchival($contact);
2155 // Unarchive the contact if it's not our own contact
2156 $contact = DBA::selectFirst('contact', [], ['id' => $arr["contact-id"], 'self' => false]);
2157 if (DBA::isResult($contact)) {
2158 Contact::unmarkForArchival($contact);
2161 /// @todo On private posts we could obfuscate the date
2162 $update = ($arr['private'] != self::PRIVATE) || in_array($arr['network'], Protocol::FEDERATED);
2164 // Is it a group? Then we don't care about the rules from above
2165 if (!$update && in_array($arr["network"], [Protocol::ACTIVITYPUB, Protocol::DFRN]) && ($arr["parent-uri-id"] === $arr["uri-id"])) {
2166 if (DBA::exists('contact', ['id' => $arr['contact-id'], 'forum' => true])) {
2172 // The "self" contact id is used (for example in the connectors) when the contact is unknown
2173 // So we have to ensure to only update the last item when it had been our own post,
2174 // or it had been done by a "regular" contact.
2175 if (!empty($arr['wall'])) {
2176 $condition = ['id' => $arr['contact-id']];
2178 $condition = ['id' => $arr['contact-id'], 'self' => false];
2180 Contact::update(['failed' => false, 'local-data' => true, 'success_update' => $arr['received'], 'last-item' => $arr['received']], $condition);
2182 // Now do the same for the system wide contacts with uid=0
2183 if ($arr['private'] != self::PRIVATE) {
2185 ['failed' => false, 'local-data' => true, 'success_update' => $arr['received'], 'last-item' => $arr['received']],
2186 ['id' => $arr['owner-id']]
2189 if ($arr['owner-id'] != $arr['author-id']) {
2191 ['failed' => false, 'local-data' => true, 'success_update' => $arr['received'], 'last-item' => $arr['received']],
2192 ['id' => $arr['author-id']]
2198 public static function setHashtags(string $body): string
2200 $body = BBCode::performWithEscapedTags($body, ['noparse', 'pre', 'code', 'img'], function ($body) {
2201 $tags = BBCode::getTags($body);
2204 if (!count($tags)) {
2208 // This sorting is important when there are hashtags that are part of other hashtags
2209 // Otherwise there could be problems with hashtags like #test and #test2
2210 // Because of this we are sorting from the longest to the shortest tag.
2211 usort($tags, function ($a, $b) {
2212 return strlen($b) <=> strlen($a);
2215 $URLSearchString = "^\[\]";
2217 // All hashtags should point to the home server if "local_tags" is activated
2218 if (DI::config()->get('system', 'local_tags')) {
2219 $body = preg_replace(
2220 "/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
2221 "#[url=" . DI::baseUrl() . "/search?tag=$2]$2[/url]",
2226 // mask hashtags inside of url, bookmarks and attachments to avoid urls in urls
2227 $body = preg_replace_callback(
2228 "/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
2230 return ("[url=" . str_replace("#", "#", $match[1]) . "]" . str_replace("#", "#", $match[2]) . "[/url]");
2235 $body = preg_replace_callback(
2236 "/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism",
2238 return ("[bookmark=" . str_replace("#", "#", $match[1]) . "]" . str_replace("#", "#", $match[2]) . "[/bookmark]");
2243 $body = preg_replace_callback(
2244 "/\[attachment (.*?)\](.*?)\[\/attachment\]/ism",
2246 return ("[attachment " . str_replace("#", "#", $match[1]) . "]" . $match[2] . "[/attachment]");
2251 // Repair recursive urls
2252 $body = preg_replace(
2253 "/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
2258 foreach ($tags as $tag) {
2259 if ((strpos($tag, '#') !== 0) || strpos($tag, '[url=') || strlen($tag) < 2 || $tag[1] == '#') {
2263 $basetag = str_replace('_', ' ', substr($tag, 1));
2264 $newtag = '#[url=' . DI::baseUrl() . '/search?tag=' . $basetag . ']' . $basetag . '[/url]';
2266 $body = str_replace($tag, $newtag, $body);
2269 // Convert back the masked hashtags
2270 $body = str_replace("#", "#", $body);
2279 * look for mention tags and setup a second delivery chain for group/community posts if appropriate
2282 * @param int $item_id
2283 * @return boolean true if item was deleted, else false
2284 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2285 * @throws \ImagickException
2287 private static function tagDeliver(int $uid, int $item_id): bool
2289 $owner = User::getOwnerDataById($uid);
2290 if (!DBA::isResult($owner)) {
2291 Logger::warning('User not found, quitting here.', ['uid' => $uid]);
2295 if ($owner['contact-type'] != User::ACCOUNT_TYPE_COMMUNITY) {
2296 Logger::debug('Owner is no community, quitting here.', ['uid' => $uid, 'id' => $item_id]);
2300 $item = Post::selectFirst(self::ITEM_FIELDLIST, ['id' => $item_id, 'gravity' => [self::GRAVITY_PARENT, self::GRAVITY_COMMENT], 'origin' => false]);
2301 if (!DBA::isResult($item)) {
2302 Logger::debug('Post is an activity or origin or not found at all, quitting here.', ['id' => $item_id]);
2306 if ($item['gravity'] == self::GRAVITY_PARENT) {
2307 if (Tag::isMentioned($item['uri-id'], $owner['url'])) {
2308 Logger::info('Mention found in tag.', ['uri' => $item['uri'], 'uid' => $uid, 'id' => $item_id, 'uri-id' => $item['uri-id'], 'guid' => $item['guid']]);
2310 Logger::info('Top-level post without mention is deleted.', ['uri' => $item['uri'], $uid, 'id' => $item_id, 'uri-id' => $item['uri-id'], 'guid' => $item['guid']]);
2311 Post\User::delete(['uri-id' => $item['uri-id'], 'uid' => $item['uid']]);
2315 $arr = ['item' => $item, 'user' => $owner];
2317 Hook::callAll('tagged', $arr);
2319 if (Tag::isMentioned($item['parent-uri-id'], $owner['url'])) {
2320 Logger::info('Mention found in parent tag.', ['uri' => $item['uri'], 'uid' => $uid, 'id' => $item_id, 'uri-id' => $item['uri-id'], 'guid' => $item['guid']]);
2322 Logger::debug('No mentions found in parent, quitting here.', ['id' => $item_id, 'uri-id' => $item['uri-id'], 'guid' => $item['guid']]);
2327 Logger::info('Community post will be distributed', ['uri' => $item['uri'], 'uid' => $uid, 'id' => $item_id, 'uri-id' => $item['uri-id'], 'guid' => $item['guid']]);
2329 if ($owner['page-flags'] == User::PAGE_FLAGS_PRVGROUP) {
2331 $allow_gid = '<' . Circle::FOLLOWERS . '>';
2334 self::performActivity($item['id'], 'announce', $uid, $allow_cid, $allow_gid, $deny_cid, $deny_gid);
2336 self::performActivity($item['id'], 'announce', $uid);
2339 Logger::info('Community post had been distributed', ['uri' => $item['uri'], 'uid' => $uid, 'id' => $item_id, 'uri-id' => $item['uri-id'], 'guid' => $item['guid']]);
2344 * Automatically reshare the item if the "remote_self" option is selected
2346 * @param array $item
2349 private static function autoReshare(array $item)
2351 if ($item['gravity'] != self::GRAVITY_PARENT) {
2355 $cdata = Contact::getPublicAndUserContactID($item['author-id'], $item['uid']);
2356 if (empty($cdata['user']) || ($cdata['user'] != $item['contact-id'])) {
2360 if (!DBA::exists('contact', ['id' => $cdata['user'], 'remote_self' => LocalRelationship::MIRROR_NATIVE_RESHARE])) {
2364 if (!in_array($item['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN])) {
2368 if (User::getById($item['uid'], ['blocked'])['blocked'] ?? false) {
2372 Logger::info('Automatically reshare item', ['uid' => $item['uid'], 'id' => $item['id'], 'guid' => $item['guid'], 'uri-id' => $item['uri-id']]);
2374 self::performActivity($item['id'], 'announce', $item['uid']);
2377 public static function isRemoteSelf(array $contact, array &$datarray): bool
2379 if ($contact['remote_self'] != LocalRelationship::MIRROR_OWN_POST) {
2383 // Prevent the forwarding of posts that are forwarded
2384 if (!empty($datarray['extid']) && ($datarray['extid'] == Protocol::DFRN)) {
2385 Logger::info('Already forwarded');
2389 // Prevent to forward already forwarded posts
2390 if ($datarray['app'] == DI::baseUrl()->getHost()) {
2391 Logger::info('Already forwarded (second test)');
2395 // Only forward posts
2396 if ($datarray['verb'] != Activity::POST) {
2397 Logger::info('No post');
2401 if (($contact['network'] != Protocol::FEED) && ($datarray['private'] == self::PRIVATE)) {
2402 Logger::info('Not public');
2406 if (User::getById($contact['uid'], ['blocked'])['blocked'] ?? false) {
2407 Logger::info('User is blocked', ['contact' => $contact]);
2411 $datarray2 = $datarray;
2412 Logger::info('remote-self start', ['contact' => $contact['url'], 'remote_self' => $contact['remote_self'], 'item' => $datarray]);
2414 $self = DBA::selectFirst(
2416 ['id', 'name', 'url', 'thumb'],
2417 ['uid' => $contact['uid'], 'self' => true]
2419 if (!DBA::isResult($self)) {
2420 Logger::error('Self contact not found', ['uid' => $contact['uid']]);
2424 $datarray['contact-id'] = $self['id'];
2426 $datarray['author-name'] = $datarray['owner-name'] = $self['name'];
2427 $datarray['author-link'] = $datarray['owner-link'] = $self['url'];
2428 $datarray['author-avatar'] = $datarray['owner-avatar'] = $self['thumb'];
2430 unset($datarray['edited']);
2432 unset($datarray['network']);
2433 unset($datarray['owner-id']);
2434 unset($datarray['author-id']);
2436 if ($contact['network'] != Protocol::FEED) {
2437 $old_uri_id = $datarray['uri-id'] ?? 0;
2438 $datarray['guid'] = System::createUUID();
2439 unset($datarray['plink']);
2440 $datarray['uri'] = self::newURI($datarray['guid']);
2441 $datarray['uri-id'] = ItemURI::getIdByURI($datarray['uri']);
2442 $datarray['extid'] = Protocol::DFRN;
2443 $urlpart = parse_url($datarray2['author-link']);
2444 $datarray['app'] = $urlpart['host'];
2445 if (!empty($old_uri_id)) {
2446 Post\Media::copy($old_uri_id, $datarray['uri-id']);
2449 unset($datarray['parent-uri']);
2450 unset($datarray['thr-parent']);
2452 // Store the original post
2453 $result = self::insert($datarray2);
2454 Logger::info('remote-self post original item', ['contact' => $contact['url'], 'result' => $result, 'item' => $datarray2]);
2456 $datarray['private'] = self::PUBLIC;
2457 $datarray['app'] = 'Feed';
2461 return (bool)$result;
2468 * @param array $item
2471 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2472 * @throws \ImagickException
2474 public static function fixPrivatePhotos(string $s, int $uid, array $item = null, int $cid = 0): string
2476 if (DI::config()->get('system', 'disable_embedded')) {
2480 Logger::info('check for photos');
2481 $site = substr(DI::baseUrl(), strpos(DI::baseUrl(), '://'));
2486 $img_start = strpos($orig_body, '[img');
2487 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
2488 $img_len = ($img_start !== false ? strpos(substr($orig_body, $img_start + $img_st_close + 1), '[/img]') : false);
2490 while (($img_st_close !== false) && ($img_len !== false)) {
2491 $img_st_close++; // make it point to AFTER the closing bracket
2492 $image = substr($orig_body, $img_start + $img_st_close, $img_len);
2494 Logger::info('found photo', ['image' => $image]);
2496 if (stristr($image, $site . '/photo/')) {
2497 // Only embed locally hosted photos
2499 $i = basename($image);
2500 $i = str_replace(['.jpg', '.png', '.gif'], ['', '', ''], $i);
2501 $x = strpos($i, '-');
2504 $res = substr($i, $x + 1);
2505 $i = substr($i, 0, $x);
2506 $photo = Photo::getPhotoForUser($uid, $i, $res);
2507 if (DBA::isResult($photo)) {
2509 * Check to see if we should replace this photo link with an embedded image
2510 * 1. No need to do so if the photo is public
2511 * 2. If there's a contact-id provided, see if they're in the access list
2512 * for the photo. If so, embed it.
2513 * 3. Otherwise, if we have an item, see if the item permissions match the photo
2514 * permissions, regardless of order but first check to see if they're an exact
2515 * match to save some processing overhead.
2517 if (self::hasPermissions($photo)) {
2519 $recips = self::enumeratePermissions($photo);
2520 if (in_array($cid, $recips)) {
2524 if (self::samePermissions($uid, $item, $photo)) {
2530 $photo_img = Photo::getImageForPhoto($photo);
2531 // If a custom width and height were specified, apply before embedding
2532 if (preg_match("/\[img\=([0-9]*)x([0-9]*)\]/is", substr($orig_body, $img_start, $img_st_close), $match)) {
2533 Logger::info('scaling photo');
2535 $width = intval($match[1]);
2536 $height = intval($match[2]);
2538 $photo_img->scaleDown(max($width, $height));
2541 $data = $photo_img->asString();
2542 $type = $photo_img->getType();
2544 Logger::info('replacing photo');
2545 $image = 'data:' . $type . ';base64,' . base64_encode($data);
2546 Logger::debug('replaced', ['image' => $image]);
2552 $new_body = $new_body . substr($orig_body, 0, $img_start + $img_st_close) . $image . '[/img]';
2553 $orig_body = substr($orig_body, $img_start + $img_st_close + $img_len + strlen('[/img]'));
2554 if ($orig_body === false) {
2558 $img_start = strpos($orig_body, '[img');
2559 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
2560 $img_len = ($img_start !== false ? strpos(substr($orig_body, $img_start + $img_st_close + 1), '[/img]') : false);
2563 $new_body = $new_body . $orig_body;
2568 private static function hasPermissions(array $obj)
2570 return !empty($obj['allow_cid']) || !empty($obj['allow_gid']) ||
2571 !empty($obj['deny_cid']) || !empty($obj['deny_gid']);
2574 // @TODO $uid is unused parameter
2575 private static function samePermissions($uid, array $obj1, array $obj2): bool
2577 // first part is easy. Check that these are exactly the same.
2578 if (($obj1['allow_cid'] == $obj2['allow_cid'])
2579 && ($obj1['allow_gid'] == $obj2['allow_gid'])
2580 && ($obj1['deny_cid'] == $obj2['deny_cid'])
2581 && ($obj1['deny_gid'] == $obj2['deny_gid'])
2586 // This is harder. Parse all the permissions and compare the resulting set.
2587 $recipients1 = self::enumeratePermissions($obj1);
2588 $recipients2 = self::enumeratePermissions($obj2);
2592 /// @TODO Comparison of arrays, maybe use array_diff_assoc() here?
2593 return ($recipients1 == $recipients2);
2597 * Returns an array of contact-ids that are allowed to see this object
2599 * @param array $obj Item array with at least uid, allow_cid, allow_gid, deny_cid and deny_gid
2600 * @param bool $check_dead Prunes unavailable contacts from the result
2601 * @param bool $expand_followers Expand the list of followers
2603 * @throws \Exception
2605 public static function enumeratePermissions(array $obj, bool $check_dead = false, bool $expand_followers = true): array
2607 $aclFormatter = DI::aclFormatter();
2609 if (!$expand_followers && (!empty($obj['deny_cid']) || !empty($obj['deny_gid']))) {
2610 $expand_followers = true;
2613 $allow_people = $aclFormatter->expand($obj['allow_cid']);
2614 $allow_circles = Circle::expand($obj['uid'], $aclFormatter->expand($obj['allow_gid']), $check_dead, $expand_followers);
2615 $deny_people = $aclFormatter->expand($obj['deny_cid']);
2616 $deny_circles = Circle::expand($obj['uid'], $aclFormatter->expand($obj['deny_gid']), $check_dead);
2617 $recipients = array_unique(array_merge($allow_people, $allow_circles));
2618 $deny = array_unique(array_merge($deny_people, $deny_circles));
2619 $recipients = array_diff($recipients, $deny);
2623 public static function expire(int $uid, int $days, string $network = "", bool $force = false)
2625 if (!$uid || ($days < 1)) {
2630 "`uid` = ? AND NOT `deleted` AND `gravity` = ?",
2631 $uid, self::GRAVITY_PARENT
2635 * $expire_network_only = save your own wall posts
2636 * and just expire conversations started by others
2638 $expire_network_only = DI::pConfig()->get($uid, 'expire', 'network_only', false);
2640 if ($expire_network_only) {
2641 $condition[0] .= " AND NOT `wall`";
2644 if ($network != "") {
2645 $condition[0] .= " AND `network` = ?";
2646 $condition[] = $network;
2649 $condition[0] .= " AND `received` < ?";
2650 $condition[] = DateTimeFormat::utc('now - ' . $days . ' day');
2652 $items = Post::select(['resource-id', 'starred', 'id', 'post-type', 'uid', 'uri-id'], $condition);
2654 if (!DBA::isResult($items)) {
2658 $expire_items = (bool)DI::pConfig()->get($uid, 'expire', 'items', true);
2660 // Forcing expiring of items - but not notes and marked items
2662 $expire_items = true;
2665 $expire_notes = (bool)DI::pConfig()->get($uid, 'expire', 'notes', true);
2666 $expire_starred = (bool)DI::pConfig()->get($uid, 'expire', 'starred', true);
2667 $expire_photos = (bool)DI::pConfig()->get($uid, 'expire', 'photos', false);
2671 $priority = DI::config()->get('system', 'expire-notify-priority');
2673 while ($item = Post::fetch($items)) {
2674 // don't expire filed items
2675 if (DBA::exists('post-category', ['uri-id' => $item['uri-id'], 'uid' => $item['uid'], 'type' => Post\Category::FILE])) {
2679 // Only expire posts, not photos and photo comments
2681 if (!$expire_photos && !empty($item['resource-id'])) {
2683 } elseif (!$expire_starred && intval($item['starred'])) {
2685 } elseif (!$expire_notes && ($item['post-type'] == self::PT_PERSONAL_NOTE)) {
2687 } elseif (!$expire_items && ($item['post-type'] != self::PT_PERSONAL_NOTE)) {
2691 self::markForDeletionById($item['id'], $priority);
2696 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]);
2699 public static function firstPostDate(int $uid, bool $wall = false)
2701 $user = User::getById($uid, ['register_date']);
2707 "`uid` = ? AND `wall` = ? AND NOT `deleted` AND `visible` AND `received` >= ?",
2708 $uid, $wall, $user['register_date']
2710 $params = ['order' => ['received' => false]];
2711 $thread = Post::selectFirstThread(['received'], $condition, $params);
2712 if (DBA::isResult($thread)) {
2713 $postdate = substr(DateTimeFormat::local($thread['received']), 0, 10);
2720 * add/remove activity to an item
2722 * Toggle activities as like,dislike,attend of an item
2724 * @param int $item_id
2725 * @param string $verb
2726 * Activity verb. One of
2727 * like, unlike, dislike, undislike, attendyes, unattendyes,
2728 * attendno, unattendno, attendmaybe, unattendmaybe,
2729 * announce, unannounce
2731 * @param string $allow_cid
2732 * @param string $allow_gid
2733 * @param string $deny_cid
2734 * @param string $deny_gid
2736 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2737 * @throws \ImagickException
2738 * @hook 'post_local_end'
2740 * 'post_id' => ID of posted item
2742 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
2748 Logger::notice('Start create activity', ['verb' => $verb, 'item' => $item_id, 'user' => $uid]);
2750 $item = Post::selectFirst(self::ITEM_FIELDLIST, ['id' => $item_id]);
2751 if (!DBA::isResult($item)) {
2752 Logger::warning('Post had not been fetched', ['id' => $item_id]);
2756 $uri_id = $item['uri-id'];
2758 if (!in_array($item['uid'], [0, $uid])) {
2762 if (!Post::exists(['uri-id' => $item['parent-uri-id'], 'uid' => $uid])) {
2763 $stored = self::storeForUserByUriId($item['parent-uri-id'], $uid, ['post-reason' => Item::PR_ACTIVITY]);
2764 if (($item['parent-uri-id'] == $item['uri-id']) && !empty($stored)) {
2765 $item = Post::selectFirst(self::ITEM_FIELDLIST, ['id' => $stored]);
2766 if (!DBA::isResult($item)) {
2767 Logger::info('Could not fetch just created item - should not happen', ['stored' => $stored, 'uid' => $uid, 'uri-id' => $uri_id]);
2773 // Retrieves the local post owner
2774 $owner = User::getOwnerDataById($uid);
2775 if (empty($owner)) {
2776 Logger::info('Empty owner for user', ['uid' => $uid]);
2780 // Retrieve the current logged in user's public contact
2781 $author_id = Contact::getPublicIdByUserId($uid);
2782 if (empty($author_id)) {
2783 Logger::info('Empty public contact');
2791 $activity = Activity::LIKE;
2795 $activity = Activity::DISLIKE;
2799 $activity = Activity::ATTEND;
2803 $activity = Activity::ATTENDNO;
2806 case 'unattendmaybe':
2807 $activity = Activity::ATTENDMAYBE;
2811 $activity = Activity::FOLLOW;
2815 $activity = Activity::ANNOUNCE;
2818 Logger::warning('unknown verb', ['verb' => $verb, 'item' => $item_id]);
2822 $mode = Strings::startsWith($verb, 'un') ? 'delete' : 'create';
2824 // Enable activity toggling instead of on/off
2825 $event_verb_flag = $activity === Activity::ATTEND || $activity === Activity::ATTENDNO || $activity === Activity::ATTENDMAYBE;
2827 // Look for an existing verb row
2828 // Event participation activities are mutually exclusive, only one of them can exist at all times.
2829 if ($event_verb_flag) {
2830 $verbs = [Activity::ATTEND, Activity::ATTENDNO, Activity::ATTENDMAYBE];
2832 // Translate to the index based activity index
2834 foreach ($verbs as $verb) {
2835 $vids[] = Verb::getID($verb);
2838 $vids = Verb::getID($activity);
2842 'vid' => $vids, 'deleted' => false, 'gravity' => self::GRAVITY_ACTIVITY,
2843 'author-id' => $author_id, 'uid' => $uid, 'thr-parent-id' => $uri_id
2845 $like_item = Post::selectFirst(['id', 'guid', 'verb'], $condition);
2847 if (DBA::isResult($like_item)) {
2849 * Truth table for existing activities
2851 * | Inputs || Outputs |
2852 * |----------------------------||-------------------|
2853 * | Mode | Event | Same verb || Delete? | Return? |
2854 * |--------|-------|-----------||---------|---------|
2855 * | create | Yes | Yes || No | Yes |
2856 * | create | Yes | No || Yes | No |
2857 * | create | No | Yes || No | Yes |
2858 * | create | No | No || N/A†|
2859 * | delete | Yes | Yes || Yes | N/A‡ |
2860 * | delete | Yes | No || No | N/A‡ |
2861 * | delete | No | Yes || Yes | N/A‡ |
2862 * | delete | No | No || N/A†|
2863 * |--------|-------|-----------||---------|---------|
2864 * | A | B | C || A xor C | !B or C |
2866 * †Can't happen: It's impossible to find an existing non-event activity without
2867 * the same verb because we are only looking for this single verb.
2869 * ‡ The "mode = delete" is returning early whether an existing activity was found or not.
2871 if ($mode == 'create' xor $like_item['verb'] == $activity) {
2872 self::markForDeletionById($like_item['id']);
2875 if (!$event_verb_flag || $like_item['verb'] == $activity) {
2880 // No need to go further if we aren't creating anything
2881 if ($mode == 'delete') {
2885 $objtype = $item['resource-id'] ? Activity\ObjectType::IMAGE : Activity\ObjectType::NOTE;
2888 'guid' => System::createUUID(),
2889 'uri' => self::newURI(),
2891 'contact-id' => $owner['id'],
2892 'wall' => $item['wall'],
2894 'network' => Protocol::DFRN,
2895 'protocol' => Conversation::PARCEL_DIRECT,
2896 'direction' => Conversation::PUSH,
2897 'gravity' => self::GRAVITY_ACTIVITY,
2898 'parent' => $item['id'],
2899 'thr-parent' => $item['uri'],
2900 'owner-id' => $author_id,
2901 'author-id' => $author_id,
2902 'body' => $activity,
2903 'verb' => $activity,
2904 'object-type' => $objtype,
2905 'allow_cid' => $allow_cid ?? $item['allow_cid'],
2906 'allow_gid' => $allow_gid ?? $item['allow_gid'],
2907 'deny_cid' => $deny_cid ?? $item['deny_cid'],
2908 'deny_gid' => $deny_gid ?? $item['deny_gid'],
2913 if (in_array($activity, [Activity::LIKE, Activity::DISLIKE])) {
2914 $signed = Diaspora::createLikeSignature($uid, $new_item);
2915 if (!empty($signed)) {
2916 $new_item['diaspora_signed_text'] = json_encode($signed);
2920 self::insert($new_item, true);
2922 // If the parent item isn't visible then set it to visible
2923 // @todo Check if this is still needed
2924 if (!$item['visible']) {
2925 self::update(['visible' => true], ['id' => $item['id']]);
2931 * Fetch the SQL condition for the given user id
2933 * @param integer $owner_id User ID for which the permissions should be fetched
2934 * @return array condition
2936 public static function getPermissionsConditionArrayByUserId(int $owner_id): array
2938 $local_user = DI::userSession()->getLocalUserId();
2939 $remote_user = DI::userSession()->getRemoteContactID($owner_id);
2941 // default permissions - anonymous user
2942 $condition = ["`private` != ?", self::PRIVATE];
2944 if ($local_user && ($local_user == $owner_id)) {
2945 // Profile owner - everything is visible
2947 } elseif ($remote_user) {
2948 // Authenticated visitor - fetch the matching permissionsets
2949 $permissionSets = DI::permissionSet()->selectByContactId($remote_user, $owner_id);
2952 "(`private` != ? OR (`private` = ? AND `wall`
2953 AND `psid` IN (" . implode(', ', array_fill(0, count($set), '?')) . ")))",
2954 self::PRIVATE, self::PRIVATE
2956 $condition = array_merge($condition, $permissionSets->column('id'));
2964 * Get a permission SQL string for the given user
2966 * @param int $owner_id
2967 * @param string $table
2970 public static function getPermissionsSQLByUserId(int $owner_id, string $table = ''): string
2972 $local_user = DI::userSession()->getLocalUserId();
2973 $remote_user = DI::userSession()->getRemoteContactID($owner_id);
2975 if (!empty($table)) {
2976 $table = DBA::quoteIdentifier($table) . '.';
2980 * Construct permissions
2982 * default permissions - anonymous user
2984 $sql = sprintf(" AND " . $table . "`private` != %d", self::PRIVATE);
2986 // Profile owner - everything is visible
2987 if ($local_user && ($local_user == $owner_id)) {
2989 } elseif ($remote_user) {
2991 * Authenticated visitor. Unless pre-verified,
2992 * check that the contact belongs to this $owner_id
2993 * and load the circles the visitor belongs to.
2994 * If pre-verified, the caller is expected to have already
2995 * done this and passed the circles into this function.
2997 $permissionSets = DI::permissionSet()->selectByContactId($remote_user, $owner_id);
3000 $sql_set = sprintf(" OR (" . $table . "`private` = %d AND " . $table . "`wall` AND " . $table . "`psid` IN (", self::PRIVATE) . implode(',', $permissionSets->column('id')) . "))";
3005 $sql = sprintf(" AND (" . $table . "`private` != %d", self::PRIVATE) . $sql_set . ")";
3012 * get translated item type
3014 * @param array $item
3015 * @param \Friendica\Core\L10n $l10n
3018 public static function postType(array $item, \Friendica\Core\L10n $l10n): string
3020 if (!empty($item['event-id'])) {
3021 return $l10n->t('event');
3022 } elseif (!empty($item['resource-id'])) {
3023 return $l10n->t('photo');
3024 } elseif ($item['gravity'] == self::GRAVITY_ACTIVITY) {
3025 return $l10n->t('activity');
3026 } elseif ($item['gravity'] == self::GRAVITY_COMMENT) {
3027 return $l10n->t('comment');
3030 return $l10n->t('post');
3034 * Sets the "rendered-html" field of the provided item
3036 * Body is preserved to avoid side-effects as we modify it just-in-time for spoilers and private image links
3038 * @param array $item
3040 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3041 * @todo Remove reference, simply return "rendered-html" and "rendered-hash"
3043 private static function putInCache(&$item)
3045 // Save original body to prevent addons to modify it
3046 $body = $item['body'];
3048 $rendered_hash = $item['rendered-hash'] ?? '';
3049 $rendered_html = $item['rendered-html'] ?? '';
3052 $rendered_hash == ''
3053 || $rendered_html == ''
3054 || $rendered_hash != hash('md5', BBCode::VERSION . '::' . $body)
3055 || DI::config()->get('system', 'ignore_cache')
3057 $item['rendered-html'] = BBCode::convertForUriId($item['uri-id'], $item['body']);
3058 $item['rendered-hash'] = hash('md5', BBCode::VERSION . '::' . $body);
3060 $hook_data = ['item' => $item, 'rendered-html' => $item['rendered-html'], 'rendered-hash' => $item['rendered-hash']];
3061 Hook::callAll('put_item_in_cache', $hook_data);
3062 $item['rendered-html'] = $hook_data['rendered-html'];
3063 $item['rendered-hash'] = $hook_data['rendered-hash'];
3066 // Update if the generated values differ from the existing ones
3067 if ((($rendered_hash != $item['rendered-hash']) || ($rendered_html != $item['rendered-html'])) && !empty($item['id'])) {
3070 'rendered-html' => $item['rendered-html'],
3071 'rendered-hash' => $item['rendered-hash']
3073 ['id' => $item['id']]
3078 $item['body'] = $body;
3082 * Given an item array, convert the body element from bbcode to html and add smilie icons.
3083 * If attach is true, also add icons for item attachments.
3085 * @param array $item Record from item table
3086 * @param boolean $attach If true, add icons for item attachments as well
3087 * @param boolean $is_preview Whether this is a preview
3088 * @param boolean $only_cache Whether only cached HTML should be updated
3089 * @return string item body html
3090 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3091 * @throws \ImagickException
3092 * @hook prepare_body_init item array before any work
3093 * @hook prepare_body_content_filter ('item'=>item array, 'filter_reasons'=>string array) before first bbcode to html
3094 * @hook prepare_body ('item'=>item array, 'html'=>body string, 'is_preview'=>boolean, 'filter_reasons'=>string array) after first bbcode to html
3095 * @hook prepare_body_final ('item'=>item array, 'html'=>body string) after attach icons and blockquote special case handling (spoiler, author)
3097 public static function prepareBody(array &$item, bool $attach = false, bool $is_preview = false, bool $only_cache = false): string
3100 Hook::callAll('prepare_body_init', $item);
3103 // In order to provide theme developers more possibilities, event items
3104 // are treated differently.
3105 if ($item['object-type'] === Activity\ObjectType::EVENT && isset($item['event-id'])) {
3106 $ev = Event::getItemHTML($item);
3110 $tags = Tag::populateFromItem($item);
3112 $item['tags'] = $tags['tags'];
3113 $item['hashtags'] = $tags['hashtags'];
3114 $item['mentions'] = $tags['mentions'];
3117 $item['body'] = preg_replace("#\s*\[attachment .*?].*?\[/attachment]\s*#ism", "\n", $item['body']);
3118 $item['body'] = Post\Media::removeFromEndOfBody($item['body'] ?? '');
3119 $item['body'] = Post\Media::replaceImage($item['body']);
3122 $body = $item['body'];
3124 $item['body'] = preg_replace("#\s*\[attachment .*?].*?\[/attachment]\s*#ism", "\n", $item['body']);
3127 $fields = ['uri-id', 'uri', 'body', 'title', 'author-name', 'author-link', 'author-avatar', 'guid', 'created', 'plink', 'network', 'has-media', 'quote-uri-id', 'post-type'];
3131 $quote_shared_links = [];
3133 $shared = DI::contentItem()->getSharedPost($item, $fields);
3134 if (!empty($shared['post'])) {
3135 $shared_item = $shared['post'];
3136 $shared_item['body'] = Post\Media::removeFromEndOfBody($shared_item['body']);
3137 $shared_item['body'] = Post\Media::replaceImage($shared_item['body']);
3138 $quote_uri_id = $shared['post']['uri-id'];
3139 $shared_links[] = strtolower($shared['post']['uri']);
3140 $item['body'] = BBCode::removeSharedData($item['body']);
3141 } elseif (empty($shared_item['uri-id']) && empty($item['quote-uri-id']) && ($item['network'] != Protocol::DIASPORA)) {
3142 $media = Post\Media::getByURIId($item['uri-id'], [Post\Media::ACTIVITY]);
3143 if (!empty($media) && ($media[0]['media-uri-id'] != $item['uri-id'])) {
3144 $shared_item = Post::selectFirst($fields, ['uri-id' => $media[0]['media-uri-id'], 'uid' => [$item['uid'], 0]]);
3145 if (empty($shared_item['uri-id'])) {
3146 $shared_item = Post::selectFirst($fields, ['plink' => $media[0]['url'], 'uid' => [$item['uid'], 0]]);
3147 } elseif (!in_array(strtolower($media[0]['url']), $shared_links)) {
3148 $shared_links[] = strtolower($media[0]['url']);
3151 if (empty($shared_item['uri-id'])) {
3152 $shared_item = Post::selectFirst($fields, ['uri' => $media[0]['url'], 'uid' => [$item['uid'], 0]]);
3153 $shared_links[] = strtolower($media[0]['url']);
3156 if (!empty($shared_item['uri-id'])) {
3157 $data = BBCode::getAttachmentData($shared_item['body']);
3158 if (!empty($data['url'])) {
3159 $quote_shared_links[] = $data['url'];
3162 $quote_uri_id = $shared_item['uri-id'];
3167 if (!empty($quote_uri_id)) {
3168 if (isset($shared_item['plink'])) {
3169 $item['body'] .= "\n" . DI::contentItem()->createSharedBlockByArray($shared_item, false, true);
3171 DI::logger()->warning('Missing plink in shared item', ['item' => $item, 'shared' => $shared, 'quote_uri_id' => $quote_uri_id, 'shared_item' => $shared_item]);
3175 if (!empty($shared_item['uri-id'])) {
3176 $shared_uri_id = $shared_item['uri-id'];
3177 $shared_links[] = strtolower($shared_item['plink']);
3178 $shared_attachments = Post\Media::splitAttachments($shared_uri_id, [], $shared_item['has-media']);
3179 $shared_links = array_merge($shared_links, array_column($shared_attachments['visual'], 'url'));
3180 $shared_links = array_merge($shared_links, array_column($shared_attachments['link'], 'url'));
3181 $shared_links = array_merge($shared_links, array_column($shared_attachments['additional'], 'url'));
3182 $item['body'] = self::replaceVisualAttachments($shared_attachments, $item['body']);
3185 $attachments = Post\Media::splitAttachments($item['uri-id'], $shared_links, $item['has-media'] ?? false);
3186 $item['body'] = self::replaceVisualAttachments($attachments, $item['body'] ?? '');
3188 self::putInCache($item);
3189 $item['body'] = $body;
3190 $s = $item["rendered-html"];
3196 // Compile eventual content filter reasons
3197 $filter_reasons = [];
3198 if (!$is_preview && DI::userSession()->getPublicContactId() != $item['author-id']) {
3199 if (!empty($item['user-blocked-author']) || !empty($item['user-blocked-owner'])) {
3200 $filter_reasons[] = DI::l10n()->t('%s is blocked', $item['author-name']);
3201 } elseif (!empty($item['user-ignored-author']) || !empty($item['user-ignored-owner'])) {
3202 $filter_reasons[] = DI::l10n()->t('%s is ignored', $item['author-name']);
3203 } elseif (!empty($item['user-collapsed-author']) || !empty($item['user-collapsed-owner'])) {
3204 $filter_reasons[] = DI::l10n()->t('Content from %s is collapsed', $item['author-name']);
3207 if (!empty($item['content-warning']) && (!DI::userSession()->getLocalUserId() || !DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'system', 'disable_cw', false))) {
3208 $filter_reasons[] = DI::l10n()->t('Content warning: %s', $item['content-warning']);
3211 $item['attachments'] = $attachments;
3215 'filter_reasons' => $filter_reasons
3217 Hook::callAll('prepare_body_content_filter', $hook_data);
3218 $filter_reasons = $hook_data['filter_reasons'];
3225 'preview' => $is_preview,
3226 'filter_reasons' => $filter_reasons
3228 Hook::callAll('prepare_body', $hook_data);
3229 $s = $hook_data['html'];
3234 // Replace the blockquotes with quotes that are used in mails.
3235 $mailquote = '<blockquote type="cite" class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex;">';
3236 $s = str_replace(['<blockquote>', '<blockquote class="spoiler">', '<blockquote class="author">'], [$mailquote, $mailquote, $mailquote], $s);
3240 if (!empty($shared_attachments)) {
3241 $s = self::addGallery($s, $shared_attachments, $item['uri-id']);
3242 $s = self::addVisualAttachments($shared_attachments, $shared_item, $s, true);
3243 $s = self::addLinkAttachment($shared_uri_id ?: $item['uri-id'], $shared_attachments, $body, $s, true, $quote_shared_links);
3244 $s = self::addNonVisualAttachments($shared_attachments, $item, $s, true);
3245 $body = BBCode::removeSharedData($body);
3248 $pos = strpos($s, BBCode::SHARED_ANCHOR);
3250 $shared_html = substr($s, $pos + strlen(BBCode::SHARED_ANCHOR));
3251 $s = substr($s, 0, $pos);
3254 $s = self::addGallery($s, $attachments, $item['uri-id']);
3255 $s = self::addVisualAttachments($attachments, $item, $s, false);
3256 $s = self::addLinkAttachment($item['uri-id'], $attachments, $body, $s, false, $shared_links);
3257 $s = self::addNonVisualAttachments($attachments, $item, $s, false);
3258 $s = self::addQuestions($item, $s);
3261 if (strpos($s, '<div class="map">') !== false && !empty($item['coord'])) {
3262 $x = Map::byCoordinates(trim($item['coord']));
3264 $s = preg_replace('/\<div class\=\"map\"\>/', '$0' . $x, $s);
3268 // Replace friendica image url size with theme preference.
3269 if (!empty($a->getThemeInfoValue('item_image_size'))) {
3270 $ps = $a->getThemeInfoValue('item_image_size');
3271 $s = preg_replace('|(<img[^>]+src="[^"]+/photo/[0-9a-f]+)-[0-9]|', "$1-" . $ps, $s);
3274 if (!empty($shared_html)) {
3278 $s = HTML::applyContentFilter($s, $filter_reasons);
3280 $hook_data = ['item' => $item, 'html' => $s];
3281 Hook::callAll('prepare_body_final', $hook_data);
3282 return $hook_data['html'];
3286 * @param array $images
3288 * @throws \Friendica\Network\HTTPException\ServiceUnavailableException
3290 private static function makeImageGrid(array $images): string
3292 // Image for first column (fc) and second column (sc)
3296 for ($i = 0; $i < count($images); $i++) {
3297 ($i % 2 == 0) ? ($images_fc[] = $images[$i]) : ($images_sc[] = $images[$i]);
3300 return Renderer::replaceMacros(Renderer::getMarkupTemplate('content/image_grid.tpl'), [
3309 * Modify links to pictures to links for the "Fancybox" gallery
3312 * @param array $attachments
3313 * @param integer $uri_id
3316 private static function addGallery(string $s, array $attachments, int $uri_id): string
3318 foreach ($attachments['visual'] as $attachment) {
3319 if (empty($attachment['preview']) || ($attachment['type'] != Post\Media::IMAGE)) {
3322 $s = str_replace('<a href="' . $attachment['url'] . '"', '<a data-fancybox="' . $uri_id . '" href="' . $attachment['url'] . '"', $s);
3328 * Check if the body contains a link
3330 * @param string $body
3331 * @param string $url
3335 public static function containsLink(string $body, string $url, int $type = 0): bool
3337 // Make sure that for example site parameters aren't used when testing if the link is contained in the body
3338 $urlparts = parse_url($url);
3339 if (empty($urlparts)) {
3343 unset($urlparts['query']);
3344 unset($urlparts['fragment']);
3347 $url = (string)Uri::fromParts($urlparts);
3348 } catch (\InvalidArgumentException $e) {
3349 DI::logger()->notice('Invalid URL', ['$url' => $url, '$urlparts' => $urlparts]);
3350 /* See https://github.com/friendica/friendica/issues/12113
3351 * Malformed URLs will result in a Fatal Error
3356 // Remove media links to only search in embedded content
3357 // @todo Check images for image link, audio for audio links, ...
3358 if (in_array($type, [Post\Media::AUDIO, Post\Media::VIDEO, Post\Media::IMAGE])) {
3359 $body = preg_replace("/\[url=[^\[\]]*\](.*)\[\/url\]/Usi", ' $1 ', $body);
3362 if (strpos($body, $url)) {
3366 foreach ([0, 1, 2] as $size) {
3368 preg_match('#/photo/.*-' . $size . '\.#ism', $url) &&
3369 strpos(preg_replace('#(/photo/.*)-[012]\.#ism', '$1-' . $size . '.', $body), $url)
3379 * Replace visual attachments in the body
3381 * @param array $attachments
3382 * @param string $body
3383 * @return string modified body
3385 private static function replaceVisualAttachments(array $attachments, string $body): string
3387 DI::profiler()->startRecording('rendering');
3389 foreach ($attachments['visual'] as $attachment) {
3390 if (!empty($attachment['preview'])) {
3391 if (Network::isLocalLink($attachment['preview'])) {
3394 $proxy = Post\Media::getPreviewUrlForId($attachment['id'], Proxy::SIZE_LARGE);
3395 $search = ['[img=' . $attachment['preview'] . ']', ']' . $attachment['preview'] . '[/img]'];
3396 $replace = ['[img=' . $proxy . ']', ']' . $proxy . '[/img]'];
3398 $body = str_replace($search, $replace, $body);
3399 } elseif ($attachment['filetype'] == 'image') {
3400 if (Network::isLocalLink($attachment['url'])) {
3403 $proxy = Post\Media::getUrlForId($attachment['id']);
3404 $search = ['[img=' . $attachment['url'] . ']', ']' . $attachment['url'] . '[/img]'];
3405 $replace = ['[img=' . $proxy . ']', ']' . $proxy . '[/img]'];
3407 $body = str_replace($search, $replace, $body);
3410 DI::profiler()->stopRecording();
3415 * Add visual attachments to the content
3417 * @param array $attachments
3418 * @param array $item
3419 * @param string $content
3420 * @return string modified content
3422 private static function addVisualAttachments(array $attachments, array $item, string $content, bool $shared): string
3424 DI::profiler()->startRecording('rendering');
3429 // @todo In the future we should make a single for the template engine with all media in it. This allows more flexibilty.
3430 foreach ($attachments['visual'] as $attachment) {
3431 if (self::containsLink($item['body'], $attachment['preview'] ?? $attachment['url'], $attachment['type'])) {
3435 if ($attachment['filetype'] == 'image') {
3436 $preview_url = Post\Media::getPreviewUrlForId($attachment['id'], ($attachment['width'] > $attachment['height']) ? Proxy::SIZE_MEDIUM : Proxy::SIZE_LARGE);
3437 } elseif (!empty($attachment['preview'])) {
3438 $preview_url = Post\Media::getPreviewUrlForId($attachment['id'], Proxy::SIZE_LARGE);
3443 if ($preview_url && self::containsLink($item['body'], $preview_url)) {
3447 if (($attachment['filetype'] == 'video')) {
3448 /// @todo Move the template to /content as well
3449 $media = Renderer::replaceMacros(Renderer::getMarkupTemplate('video_top.tpl'), [
3451 'id' => $attachment['id'],
3452 'src' => $attachment['url'],
3453 'name' => $attachment['name'] ?: $attachment['url'],
3454 'preview' => $preview_url,
3455 'mime' => $attachment['mimetype'],
3458 if (($item['post-type'] ?? null) == Item::PT_VIDEO) {
3461 $trailing .= $media;
3463 } elseif ($attachment['filetype'] == 'audio') {
3464 $media = Renderer::replaceMacros(Renderer::getMarkupTemplate('content/audio.tpl'), [
3466 'id' => $attachment['id'],
3467 'src' => $attachment['url'],
3468 'name' => $attachment['name'] ?: $attachment['url'],
3469 'mime' => $attachment['mimetype'],
3472 if (($item['post-type'] ?? null) == Item::PT_AUDIO) {
3475 $trailing .= $media;
3477 } elseif ($attachment['filetype'] == 'image') {
3478 $src_url = Post\Media::getUrlForId($attachment['id']);
3479 if (self::containsLink($item['body'], $src_url)) {
3482 $images[] = ['src' => $src_url, 'preview' => $preview_url, 'attachment' => $attachment, 'uri_id' => $item['uri-id']];
3487 if (count($images) > 1) {
3488 $media = self::makeImageGrid($images);
3489 } elseif (count($images) == 1) {
3490 $media = Renderer::replaceMacros(Renderer::getMarkupTemplate('content/image.tpl'), [
3491 '$image' => $images[0],
3495 // On Diaspora posts the attached pictures are leading
3496 if ($item['network'] == Protocol::DIASPORA) {
3499 $trailing .= $media;
3503 $content = str_replace(BBCode::TOP_ANCHOR, '<div class="body-attach">' . $leading . '</div>' . BBCode::TOP_ANCHOR, $content);
3504 $content = str_replace(BBCode::BOTTOM_ANCHOR, '<div class="body-attach">' . $trailing . '</div>' . BBCode::BOTTOM_ANCHOR, $content);
3506 if ($leading != '') {
3507 $content = '<div class="body-attach">' . $leading . '</div>' . $content;
3510 if ($trailing != '') {
3511 $content .= '<div class="body-attach">' . $trailing . '</div>';
3515 DI::profiler()->stopRecording();
3520 * Add link attachment to the content
3522 * @param array $attachments
3523 * @param string $body
3524 * @param string $content
3525 * @param bool $shared
3526 * @param array $ignore_links A list of URLs to ignore
3527 * @return string modified content
3529 private static function addLinkAttachment(int $uriid, array $attachments, string $body, string $content, bool $shared, array $ignore_links): string
3531 DI::profiler()->startRecording('rendering');
3532 // Don't show a preview when there is a visual attachment (audio or video)
3533 $types = array_column($attachments['visual'], 'type');
3534 $preview = !in_array(Post\Media::IMAGE, $types) && !in_array(Post\Media::VIDEO, $types);
3536 if (!empty($attachments['link'])) {
3537 foreach ($attachments['link'] as $link) {
3539 foreach ($ignore_links as $ignore_link) {
3540 if (Strings::compareLink($link['url'], $ignore_link)) {
3544 // @todo Judge between the links to use the one with most information
3545 if (!$found && (empty($attachment) || !empty($link['author-name']) ||
3546 (empty($attachment['name']) && !empty($link['name'])) ||
3547 (empty($attachment['description']) && !empty($link['description'])) ||
3548 (empty($attachment['preview']) && !empty($link['preview'])))) {
3549 $attachment = $link;
3554 if (!empty($attachment)) {
3557 'author_name' => $attachment['author-name'] ?? '',
3558 'author_url' => $attachment['author-url'] ?? '',
3559 'description' => $attachment['description'] ?? '',
3562 'provider_name' => $attachment['publisher-name'] ?? '',
3563 'provider_url' => $attachment['publisher-url'] ?? '',
3565 'title' => $attachment['name'] ?? '',
3567 'url' => $attachment['url']
3570 if ($preview && !empty($attachment['preview'])) {
3571 if ($attachment['preview-width'] >= 500) {
3572 $data['image'] = Post\Media::getPreviewUrlForId($attachment['id'], Proxy::SIZE_MEDIUM);
3574 $data['preview'] = Post\Media::getPreviewUrlForId($attachment['id'], Proxy::SIZE_MEDIUM);
3578 if (!empty($data['description']) && !empty($content)) {
3579 similar_text($data['description'], $content, $percent);
3584 if (!empty($data['description']) && (($data['title'] == $data['description']) || ($percent > 95) || (strpos($content, $data['description']) !== false))) {
3585 $data['description'] = '';
3588 if (($data['author_name'] ?? '') == ($data['provider_name'] ?? '')) {
3589 $data['author_name'] = '';
3592 if (($data['author_url'] ?? '') == ($data['provider_url'] ?? '')) {
3593 $data['author_url'] = '';
3595 } elseif (preg_match("/.*(\[attachment.*?\].*?\[\/attachment\]).*/ism", $body, $match)) {
3596 $data = BBCode::getAttachmentData($match[1]);
3598 DI::profiler()->stopRecording();
3600 if (isset($data['url']) && !in_array(strtolower($data['url']), $ignore_links)) {
3601 if (!empty($data['description']) || !empty($data['image']) || !empty($data['preview']) || (!empty($data['title']) && !Strings::compareLink($data['title'], $data['url']))) {
3602 $parts = parse_url($data['url']);
3603 if (!empty($parts['scheme']) && !empty($parts['host'])) {
3604 if (empty($data['provider_name'])) {
3605 $data['provider_name'] = $parts['host'];
3607 if (empty($data['provider_url']) || empty(parse_url($data['provider_url'], PHP_URL_SCHEME))) {
3608 $data['provider_url'] = $parts['scheme'] . '://' . $parts['host'];
3610 if (!empty($parts['port'])) {
3611 $data['provider_url'] .= ':' . $parts['port'];
3616 // @todo Use a template
3617 $preview_mode = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'system', 'preview_mode', BBCode::PREVIEW_LARGE);
3618 if ($preview_mode != BBCode::PREVIEW_NONE) {
3619 $rendered = BBCode::convertAttachment('', BBCode::INTERNAL, false, $data, $uriid, $preview_mode);
3623 } elseif (!self::containsLink($content, $data['url'], Post\Media::HTML)) {
3624 $rendered = Renderer::replaceMacros(Renderer::getMarkupTemplate('content/link.tpl'), [
3625 '$url' => $data['url'],
3626 '$title' => $data['title'],
3633 return str_replace(BBCode::BOTTOM_ANCHOR, BBCode::BOTTOM_ANCHOR . $rendered, $content);
3635 return $content . $rendered;
3642 * Add non visual attachments to the content
3644 * @param array $attachments
3645 * @param array $item
3646 * @param string $content
3647 * @return string modified content
3649 private static function addNonVisualAttachments(array $attachments, array $item, string $content): string
3651 DI::profiler()->startRecording('rendering');
3653 foreach ($attachments['additional'] as $attachment) {
3654 if (strpos($item['body'], $attachment['url'])) {
3660 'id' => $item['author-id'],
3661 'network' => $item['author-network'],
3662 'url' => $item['author-link'],
3663 'alias' => $item['author-alias']
3665 $the_url = Contact::magicLinkByContact($author, $attachment['url']);
3667 $title = Strings::escapeHtml(trim(($attachment['description'] ?? '') ?: $attachment['url']));
3669 if (!empty($attachment['size'])) {
3670 $title .= ' ' . $attachment['size'] . ' ' . DI::l10n()->t('bytes');
3673 /// @todo Use a template
3674 $icon = '<div class="attachtype icon s22 type-' . $attachment['filetype'] . ' subtype-' . $attachment['subtype'] . '"></div>';
3675 $trailing .= '<a href="' . strip_tags($the_url) . '" title="' . $title . '" class="attachlink" target="_blank" rel="noopener noreferrer" >' . $icon . '</a>';
3678 if ($trailing != '') {
3679 $content .= '<div class="body-attach">' . $trailing . '</div>';
3682 DI::profiler()->stopRecording();
3686 private static function addQuestions(array $item, string $content): string
3688 DI::profiler()->startRecording('rendering');
3689 if (!empty($item['question-id'])) {
3691 'id' => $item['question-id'],
3692 'multiple' => $item['question-multiple'],
3693 'voters' => $item['question-voters'],
3694 'endtime' => $item['question-end-time']
3697 $options = Post\QuestionOption::getByURIId($item['uri-id']);
3698 foreach ($options as $key => $option) {
3699 if ($question['voters'] > 0) {
3700 $percent = $option['replies'] / $question['voters'] * 100;
3701 $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));
3703 $options[$key]['vote'] = DI::l10n()->tt('%2$s (%1$d vote)', '%2$s (%1$d votes)', $option['replies'], $option['name']);
3707 if (!empty($question['voters']) && !empty($question['endtime'])) {
3708 $summary = DI::l10n()->tt('%d voter. Poll end: %s', '%d voters. Poll end: %s', $question['voters'], Temporal::getRelativeDate($question['endtime']));
3709 } elseif (!empty($question['voters'])) {
3710 $summary = DI::l10n()->tt('%d voter.', '%d voters.', $question['voters']);
3711 } elseif (!empty($question['endtime'])) {
3712 $summary = DI::l10n()->t('Poll end: %s', Temporal::getRelativeDate($question['endtime']));
3717 $content .= Renderer::replaceMacros(Renderer::getMarkupTemplate('content/question.tpl'), [
3718 '$question' => $question,
3719 '$options' => $options,
3720 '$summary' => $summary,
3723 DI::profiler()->stopRecording();
3728 * get private link for item
3730 * @param array $item
3731 * @return boolean|array False if item has not plink, otherwise array('href'=>plink url, 'title'=>translated title)
3732 * @throws \Exception
3734 public static function getPlink(array $item)
3736 if (!empty($item['plink']) && Network::isValidHttpUrl($item['plink'])) {
3737 $plink = $item['plink'];
3738 } elseif (!empty($item['uri']) && Network::isValidHttpUrl($item['uri']) && !Network::isLocalLink($item['uri'])) {
3739 $plink = $item['uri'];
3742 if (DI::userSession()->getLocalUserId()) {
3744 'href' => "display/" . $item['guid'],
3745 'orig' => "display/" . $item['guid'],
3746 'title' => DI::l10n()->t('View on separate page'),
3747 'orig_title' => DI::l10n()->t('View on separate page'),
3750 if (!empty($plink) && ($item['private'] == self::PRIVATE)) {
3753 'id' => $item['author-id'],
3754 'network' => $item['author-network'],
3755 'url' => $item['author-link'],
3756 'alias' => $item['author-alias'],
3758 $plink = Contact::magicLinkByContact($author, $plink);
3761 if (!empty($plink)) {
3762 $ret['href'] = DI::baseUrl()->remove($plink);
3763 $ret['title'] = DI::l10n()->t('Link to source');
3765 } elseif (!empty($plink) && ($item['private'] != self::PRIVATE)) {
3769 'title' => DI::l10n()->t('Link to source'),
3770 'orig_title' => DI::l10n()->t('Link to source'),
3780 * Does the given uri-id belongs to a post that is sent as starting post to a group?
3781 * This does apply to posts that are sent via ! and not in parallel to a group via @
3783 * @param int $uri_id
3785 * @return boolean "true" when it is a group post
3787 public static function isGroupPost(int $uri_id): bool
3789 if (Post::exists(['private' => Item::PUBLIC, 'uri-id' => $uri_id])) {
3793 foreach (Tag::getByURIId($uri_id, [Tag::EXCLUSIVE_MENTION, Tag::AUDIENCE]) as $tag) {
3794 // @todo Possibly check for a public audience in the future, see https://socialhub.activitypub.rocks/t/fep-1b12-group-federation/2724
3795 // and https://codeberg.org/fediverse/fep/src/branch/main/feps/fep-1b12.md
3796 if (DBA::exists('contact', ['uid' => 0, 'nurl' => Strings::normaliseLink($tag['url']), 'contact-type' => Contact::TYPE_COMMUNITY])) {
3804 * Search item id for given URI or plink
3806 * @param string $uri
3807 * @param integer $uid
3809 * @return integer item id
3811 public static function searchByLink(string $uri, int $uid = 0): int
3813 $ssl_uri = str_replace('http://', 'https://', $uri);
3814 $uris = [$uri, $ssl_uri, Strings::normaliseLink($uri)];
3816 $item = Post::selectFirst(['id'], ['uri' => $uris, 'uid' => $uid]);
3817 if (DBA::isResult($item)) {
3821 $item = Post::selectFirst(['id'], ['plink' => $uris, 'uid' => $uid]);
3822 if (DBA::isResult($item)) {
3830 * Return the URI for a link to the post
3832 * @param string $uri URI or link to post
3834 * @return string URI
3836 public static function getURIByLink(string $uri): string
3838 $ssl_uri = str_replace('http://', 'https://', $uri);
3839 $uris = [$uri, $ssl_uri, Strings::normaliseLink($uri)];
3841 $item = Post::selectFirst(['uri'], ['uri' => $uris]);
3842 if (DBA::isResult($item)) {
3843 return $item['uri'];
3846 $item = Post::selectFirst(['uri'], ['plink' => $uris]);
3847 if (DBA::isResult($item)) {
3848 return $item['uri'];
3855 * Fetches item for given URI or plink
3857 * @param string $uri
3858 * @param integer $uid
3860 * @return integer item id
3862 public static function fetchByLink(string $uri, int $uid = 0): int
3864 Logger::info('Trying to fetch link', ['uid' => $uid, 'uri' => $uri]);
3865 $item_id = self::searchByLink($uri, $uid);
3866 if (!empty($item_id)) {
3867 Logger::info('Link found', ['uid' => $uid, 'uri' => $uri, 'id' => $item_id]);
3877 Hook::callAll('item_by_link', $hookData);
3879 if (isset($hookData['item_id'])) {
3880 return is_numeric($hookData['item_id']) ? $hookData['item_id'] : 0;
3883 $fetched_uri = ActivityPub\Processor::fetchMissingActivity($uri, [], '', ActivityPub\Receiver::COMPLETION_MANUAL, $uid);
3886 $item_id = self::searchByLink($fetched_uri, $uid);
3888 $item_id = Diaspora::fetchByURL($uri);
3891 if (!empty($item_id)) {
3892 Logger::info('Link fetched', ['uid' => $uid, 'uri' => $uri, 'id' => $item_id]);
3896 Logger::info('Link not found', ['uid' => $uid, 'uri' => $uri]);
3901 * Fetch the uri-id of a quote
3903 * @param string $body
3906 public static function getQuoteUriId(string $body, int $uid = 0): int
3908 $shared = BBCode::fetchShareAttributes($body);
3909 if (empty($shared['guid']) && empty($shared['message_id'])) {
3913 if (empty($shared['link']) && empty($shared['message_id'])) {
3914 Logger::notice('Invalid share block.', ['share' => $shared]);
3918 if (!empty($shared['guid'])) {
3919 $shared_item = Post::selectFirst(['uri-id'], ['guid' => $shared['guid'], 'uid' => [0, $uid]]);
3920 if (!empty($shared_item['uri-id'])) {
3921 Logger::debug('Found post by guid', ['guid' => $shared['guid'], 'uid' => $uid]);
3922 return $shared_item['uri-id'];
3926 if (!empty($shared['message_id'])) {
3927 $shared_item = Post::selectFirst(['uri-id'], ['uri' => $shared['message_id'], 'uid' => [0, $uid]]);
3928 if (!empty($shared_item['uri-id'])) {
3929 Logger::debug('Found post by message_id', ['message_id' => $shared['message_id'], 'uid' => $uid]);
3930 return $shared_item['uri-id'];
3934 if (!empty($shared['link'])) {
3935 $shared_item = Post::selectFirst(['uri-id'], ['plink' => $shared['link'], 'uid' => [0, $uid]]);
3936 if (!empty($shared_item['uri-id'])) {
3937 Logger::debug('Found post by link', ['link' => $shared['link'], 'uid' => $uid]);
3938 return $shared_item['uri-id'];
3942 $url = $shared['message_id'] ?: $shared['link'];
3943 $id = self::fetchByLink($url);
3945 Logger::notice('Post could not be fetched.', ['url' => $url, 'uid' => $uid]);
3949 $shared_item = Post::selectFirst(['uri-id'], ['id' => $id]);
3950 if (!empty($shared_item['uri-id'])) {
3951 Logger::debug('Fetched shared post', ['id' => $id, 'url' => $url, 'uid' => $uid]);
3952 return $shared_item['uri-id'];
3955 Logger::warning('Post does not exist although it was supposed to had been fetched.', ['id' => $id, 'url' => $url, 'uid' => $uid]);