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\Image;
26 use Friendica\Content\Post\Collection\PostMedias;
27 use Friendica\Content\Post\Entity\PostMedia;
28 use Friendica\Content\Text\BBCode;
29 use Friendica\Content\Text\HTML;
30 use Friendica\Core\Hook;
31 use Friendica\Core\Logger;
32 use Friendica\Core\Protocol;
33 use Friendica\Core\Renderer;
34 use Friendica\Core\System;
35 use Friendica\Core\Worker;
36 use Friendica\Database\DBA;
38 use Friendica\Model\Post\Category;
39 use Friendica\Network\HTTPException\InternalServerErrorException;
40 use Friendica\Network\HTTPException\ServiceUnavailableException;
41 use Friendica\Protocol\Activity;
42 use Friendica\Protocol\ActivityPub;
43 use Friendica\Protocol\Delivery;
44 use Friendica\Protocol\Diaspora;
45 use Friendica\Util\DateTimeFormat;
46 use Friendica\Util\Map;
47 use Friendica\Util\Network;
48 use Friendica\Util\Proxy;
49 use Friendica\Util\Strings;
50 use Friendica\Util\Temporal;
51 use GuzzleHttp\Psr7\Uri;
52 use LanguageDetection\Language;
56 // Posting types, inspired by https://www.w3.org/TR/activitystreams-vocabulary/#object-types
63 const PT_DOCUMENT = 19;
66 const PT_PERSONAL_NOTE = 128;
68 // Posting reasons (Why had a post been stored for a user?)
75 const PR_FOLLOWER = 69;
76 const PR_ANNOUNCEMENT = 70;
77 const PR_COMMENT = 71;
81 const PR_FETCHED = 75;
82 const PR_COMPLETION = 76;
84 const PR_ACTIVITY = 78;
85 const PR_DISTRIBUTE = 79;
88 const PR_AUDIENCE = 82;
90 // system.accept_only_sharer setting values
91 const COMPLETION_NONE = 1;
92 const COMPLETION_COMMENT = 0;
93 const COMPLETION_LIKE = 2;
95 // Field list that is used to display the items
96 const DISPLAY_FIELDLIST = [
97 'uid', 'id', 'parent', 'guid', 'network', 'gravity',
98 'uri-id', 'uri', 'thr-parent-id', 'thr-parent', 'parent-uri-id', 'parent-uri', 'conversation',
99 'commented', 'created', 'edited', 'received', 'verb', 'object-type', 'postopts', 'plink',
100 'wall', 'private', 'starred', 'origin', 'parent-origin', 'title', 'body', 'language',
101 'content-warning', 'location', 'coord', 'app', 'rendered-hash', 'rendered-html', 'object',
102 'quote-uri', 'quote-uri-id', 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid', 'mention', 'global',
103 'author-id', 'author-link', 'author-alias', 'author-name', 'author-avatar', 'author-network', 'author-updated', 'author-gsid', 'author-baseurl', 'author-addr', 'author-uri-id',
104 'owner-id', 'owner-link', 'owner-alias', 'owner-name', 'owner-avatar', 'owner-network', 'owner-contact-type', 'owner-updated', 'owner-gsid',
105 'causer-id', 'causer-link', 'causer-alias', 'causer-name', 'causer-avatar', 'causer-contact-type', 'causer-network', 'causer-gsid',
106 'contact-id', 'contact-uid', 'contact-link', 'contact-name', 'contact-avatar',
107 'writable', 'self', 'cid', 'alias',
108 'event-created', 'event-edited', 'event-start', 'event-finish',
109 'event-summary', 'event-desc', 'event-location', 'event-type',
110 'event-nofinish', 'event-ignore', 'event-id',
111 'question-id', 'question-multiple', 'question-voters', 'question-end-time',
112 'has-categories', 'has-media',
113 'delivery_queue_count', 'delivery_queue_done', 'delivery_queue_failed'
116 // Field list that is used to deliver items via the protocols
117 const DELIVER_FIELDLIST = [
118 'uid', 'id', 'parent', 'uri-id', 'uri', 'thr-parent', 'parent-uri', 'guid',
119 'parent-guid', 'conversation', 'received', 'created', 'edited', 'verb', 'object-type', 'object', 'target',
120 'private', 'title', 'body', 'raw-body', 'location', 'coord', 'app',
121 'inform', 'deleted', 'extid', 'post-type', 'post-reason', 'gravity',
122 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid',
123 'author-id', 'author-addr', 'author-link', 'author-name', 'author-avatar', 'owner-id', 'owner-link', 'contact-uid',
124 'signed_text', 'network', 'wall', 'contact-id', 'plink', 'origin',
125 'thr-parent-id', 'parent-uri-id', 'quote-uri', 'quote-uri-id', 'postopts', 'pubmail',
126 'event-created', 'event-edited', 'event-start', 'event-finish',
127 'event-summary', 'event-desc', 'event-location', 'event-type',
128 'event-nofinish', 'event-ignore', 'event-id'
131 // All fields in the item table
132 const ITEM_FIELDLIST = [
133 'id', 'uid', 'parent', 'uri', 'parent-uri', 'thr-parent',
134 'guid', 'uri-id', 'parent-uri-id', 'thr-parent-id', 'conversation', 'vid',
135 'quote-uri', 'quote-uri-id', 'contact-id', 'wall', 'gravity', 'extid', 'psid',
136 'created', 'edited', 'commented', 'received', 'changed', 'verb',
137 'postopts', 'plink', 'resource-id', 'event-id', 'inform',
138 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid', 'post-type', 'post-reason',
139 'private', 'pubmail', 'visible', 'starred',
140 'unseen', 'deleted', 'origin', 'mention', 'global', 'network',
141 'title', 'content-warning', 'body', 'location', 'coord', 'app',
142 'rendered-hash', 'rendered-html', 'object-type', 'object', 'target-type', 'target',
143 'author-id', 'author-link', 'author-name', 'author-avatar', 'author-network',
144 'owner-id', 'owner-link', 'owner-name', 'owner-avatar', 'causer-id'
147 // List of all verbs that don't need additional content data.
148 // Never reorder or remove entries from this list. Just add new ones at the end, if needed.
150 Activity::LIKE, Activity::DISLIKE,
151 Activity::ATTEND, Activity::ATTENDNO, Activity::ATTENDMAYBE,
161 // Item weight for query ordering
162 const GRAVITY_PARENT = 0;
163 const GRAVITY_ACTIVITY = 3;
164 const GRAVITY_COMMENT = 6;
165 const GRAVITY_UNKNOWN = 9;
168 * Update existing item entries
170 * @param array $fields The fields that are to be changed
171 * @param array $condition The condition for finding the item entries
173 * In the future we may have to change permissions as well.
174 * Then we had to add the user id as third parameter.
176 * A return value of "0" doesn't mean an error - but that 0 rows had been changed.
178 * @return integer|boolean number of affected rows - or "false" if there was an error
179 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
181 public static function update(array $fields, array $condition)
183 if (empty($condition) || empty($fields)) {
187 if (isset($fields['extid'])) {
188 $fields['external-id'] = ItemURI::getIdByURI($fields['extid']);
191 if (!empty($fields['verb'])) {
192 $fields['vid'] = Verb::getID($fields['verb']);
195 if (!empty($fields['edited'])) {
196 $previous = Post::selectFirst(['edited'], $condition);
199 $rows = Post::update($fields, $condition);
200 if (is_bool($rows)) {
204 // We only need to call the line by line update for specific fields
206 empty($fields['body']) && empty($fields['file']) &&
207 empty($fields['attach']) && empty($fields['edited'])
212 Logger::info('Updating per single row method', ['fields' => $fields, 'condition' => $condition]);
214 $items = Post::select(['id', 'origin', 'uri-id', 'uid', 'author-network', 'quote-uri-id'], $condition);
218 while ($item = DBA::fetch($items)) {
219 if (!empty($fields['body'])) {
220 if (!empty($item['quote-uri-id'])) {
221 $fields['body'] = BBCode::removeSharedData($fields['body']);
223 if (!empty($fields['raw-body'])) {
224 $fields['raw-body'] = BBCode::removeSharedData($fields['raw-body']);
228 $content_fields = ['raw-body' => trim($fields['raw-body'] ?? $fields['body'])];
230 // Remove all media attachments from the body and store them in the post-media table
231 // @todo On shared postings (Diaspora style and commented reshare) don't fetch content from the shared part
232 $content_fields['raw-body'] = Post\Media::insertFromBody($item['uri-id'], $content_fields['raw-body']);
233 $content_fields['raw-body'] = self::setHashtags($content_fields['raw-body']);
235 Post\Media::insertFromRelevantUrl($item['uri-id'], $content_fields['raw-body'], $fields['body'], $item['author-network']);
237 Post\Media::insertFromAttachmentData($item['uri-id'], $fields['body']);
238 $content_fields['raw-body'] = BBCode::removeAttachment($content_fields['raw-body']);
240 Post\Content::update($item['uri-id'], $content_fields);
243 if (!empty($fields['file'])) {
244 Post\Category::storeTextByURIId($item['uri-id'], $item['uid'], $fields['file']);
247 if (!empty($fields['attach'])) {
248 Post\Media::insertFromAttachment($item['uri-id'], $fields['attach']);
251 // We only need to notify others when it is an original entry from us.
252 // Only call the notifier when the item had been edited and records had been changed.
253 if ($item['origin'] && !empty($fields['edited']) && ($previous['edited'] != $fields['edited'])) {
254 $notify_items[] = $item['id'];
260 foreach ($notify_items as $notify_item) {
261 $post = Post::selectFirst([], ['id' => $notify_item]);
263 if ($post['gravity'] != self::GRAVITY_PARENT) {
264 $signed = Diaspora::createCommentSignature($post);
265 if (!empty($signed)) {
266 DBA::replace('diaspora-interaction', ['uri-id' => $post['uri-id'], 'interaction' => json_encode($signed)]);
270 Worker::add(Worker::PRIORITY_HIGH, 'Notifier', Delivery::POST, (int)$post['uri-id'], (int)$post['uid']);
277 * Delete an item and notify others about it - if it was ours
279 * @param array $condition The condition for finding the item entries
280 * @param integer $priority Priority for the notification
282 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
284 public static function markForDeletion(array $condition, int $priority = Worker::PRIORITY_HIGH)
286 $items = Post::select(['id'], $condition);
287 while ($item = Post::fetch($items)) {
288 self::markForDeletionById($item['id'], $priority);
294 * Delete an item for an user and notify others about it - if it was ours
296 * @param array $condition The condition for finding the item entries
297 * @param integer $uid User who wants to delete this item
299 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
301 public static function deleteForUser(array $condition, int $uid)
307 $items = Post::select(['id', 'uid', 'uri-id'], $condition);
308 while ($item = Post::fetch($items)) {
309 if (in_array($item['uid'], [$uid, 0])) {
310 Post\User::update($item['uri-id'], $uid, ['hidden' => true], true);
311 Post\ThreadUser::update($item['uri-id'], $uid, ['hidden' => true], true);
314 if ($item['uid'] == $uid) {
315 self::markForDeletionById($item['id'], Worker::PRIORITY_HIGH);
316 } elseif ($item['uid'] != 0) {
317 Logger::warning('Wrong ownership. Not deleting item', ['id' => $item['id']]);
324 * Mark an item for deletion, delete related data and notify others about it - if it was ours
326 * @param integer $item_id
327 * @param integer $priority Priority for the notification
328 * @return boolean success
329 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
331 public static function markForDeletionById(int $item_id, int $priority = Worker::PRIORITY_HIGH): bool
333 Logger::info('Mark item for deletion by id', ['id' => $item_id, 'callstack' => System::callstack()]);
334 // locate item to be deleted
336 'id', 'uri', 'uri-id', 'uid', 'parent', 'parent-uri-id', 'origin',
337 'deleted', 'resource-id', 'event-id',
338 'verb', 'object-type', 'object', 'target', 'contact-id', 'psid', 'gravity'
340 $item = Post::selectFirst($fields, ['id' => $item_id]);
341 if (!DBA::isResult($item)) {
342 Logger::info('Item not found.', ['id' => $item_id]);
346 if ($item['deleted']) {
347 Logger::info('Item has already been marked for deletion.', ['id' => $item_id]);
351 $parent = Post::selectFirst(['origin'], ['id' => $item['parent']]);
352 if (!DBA::isResult($parent)) {
353 $parent = ['origin' => false];
356 // clean up categories and tags so they don't end up as orphans
357 Post\Category::deleteByURIId($item['uri-id'], $item['uid']);
360 * If item is a link to a photo resource, nuke all the associated photos
361 * (visitors will not have photo resources)
362 * This only applies to photos uploaded from the photos page. Photos inserted into a post do not
363 * generate a resource-id and therefore aren't intimately linked to the item.
365 /// @TODO: this should first check if photo is used elsewhere
366 if ($item['resource-id']) {
367 Photo::delete(['resource-id' => $item['resource-id'], 'uid' => $item['uid']]);
370 // If item is a link to an event, delete the event.
371 if (intval($item['event-id'])) {
372 Event::delete($item['event-id']);
375 // If item has attachments, drop them
376 $attachments = Post\Media::getByURIId($item['uri-id'], [Post\Media::DOCUMENT]);
377 foreach ($attachments as $attachment) {
378 if (preg_match('|attach/(\d+)|', $attachment['url'], $matches)) {
379 Attach::delete(['id' => $matches[1], 'uid' => $item['uid']]);
383 // Set the item to "deleted"
384 $item_fields = ['deleted' => true, 'edited' => DateTimeFormat::utcNow(), 'changed' => DateTimeFormat::utcNow()];
385 Post::update($item_fields, ['id' => $item['id']]);
387 Post\Category::storeTextByURIId($item['uri-id'], $item['uid'], '');
389 if (!Post::exists(["`uri-id` = ? AND `uid` != 0 AND NOT `deleted`", $item['uri-id']])) {
390 self::markForDeletion(['uri-id' => $item['uri-id'], 'uid' => 0, 'deleted' => false], $priority);
393 Post\DeliveryData::delete($item['uri-id']);
395 // If it's the parent of a comment thread, kill all the kids
396 if ($item['gravity'] == self::GRAVITY_PARENT) {
397 self::markForDeletion(['parent' => $item['parent'], 'deleted' => false], $priority);
400 // Is it our comment and/or our thread?
401 if (($item['origin'] || $parent['origin']) && ($item['uid'] != 0)) {
402 // When we delete the original post we will delete all existing copies on the server as well
403 self::markForDeletion(['uri-id' => $item['uri-id'], 'deleted' => false], $priority);
405 // send the notification upstream/downstream
407 Worker::add(['priority' => $priority, 'dont_fork' => true], 'Notifier', Delivery::DELETION, (int)$item['uri-id'], (int)$item['uid']);
409 } elseif ($item['uid'] != 0) {
410 Post\User::update($item['uri-id'], $item['uid'], ['hidden' => true]);
411 Post\ThreadUser::update($item['uri-id'], $item['uid'], ['hidden' => true]);
414 DI::notify()->deleteForItem($item['uri-id']);
415 DI::notification()->deleteForItem($item['uri-id']);
417 Logger::info('Item has been marked for deletion.', ['id' => $item_id]);
423 * Get guid from given item record
425 * @param array $item Item record
426 * @param bool Whether to notify (?)
427 * @return string Guid
429 public static function guid(array $item, bool $notify): string
431 if (!empty($item['guid'])) {
432 return trim($item['guid']);
436 // We have to avoid duplicates. So we create the GUID in form of a hash of the plink or uri.
437 // We add the hash of our own host because our host is the original creator of the post.
438 $prefix_host = DI::baseUrl()->getHost();
442 // We are only storing the post so we create a GUID from the original hostname.
443 if (!empty($item['author-link'])) {
444 $parsed = parse_url($item['author-link']);
445 if (!empty($parsed['host'])) {
446 $prefix_host = $parsed['host'];
450 if (empty($prefix_host) && !empty($item['plink'])) {
451 $parsed = parse_url($item['plink']);
452 if (!empty($parsed['host'])) {
453 $prefix_host = $parsed['host'];
457 if (empty($prefix_host) && !empty($item['uri'])) {
458 $parsed = parse_url($item['uri']);
459 if (!empty($parsed['host'])) {
460 $prefix_host = $parsed['host'];
464 // Is it in the format data@host.tld? - Used for mail contacts
465 if (empty($prefix_host) && !empty($item['author-link']) && strstr($item['author-link'], '@')) {
466 $mailparts = explode('@', $item['author-link']);
467 $prefix_host = array_pop($mailparts);
471 if (!empty($item['plink'])) {
472 $guid = self::guidFromUri($item['plink'], $prefix_host);
473 } elseif (!empty($item['uri'])) {
474 $guid = self::guidFromUri($item['uri'], $prefix_host);
476 $guid = System::createUUID(hash('crc32', $prefix_host));
483 * Returns contact id from given item record
485 * @param array $item Item record
486 * @return int Contact id
488 private static function contactId(array $item): int
490 if ($item['uid'] == 0) {
491 return $item['owner-id'];
494 if ($item['origin']) {
495 $owner = User::getOwnerDataById($item['uid']);
500 $user_contact_id = 0;
501 foreach (['group-link', 'causer-link', 'owner-link', 'author-link'] as $field) {
502 if (empty($item[$field])) {
505 if (!$user_contact_id && Contact::isSharingByURL($item[$field], $item['uid'], true)) {
506 $user_contact_id = Contact::getIdForURL($item[$field], $item['uid']);
507 } elseif (!$contact_id) {
508 $contact_id = Contact::getIdForURL($item[$field]);
512 if ($user_contact_id) {
513 return $user_contact_id;
516 if (!empty($item['causer-id']) && Contact::isSharing($item['causer-id'], $item['uid'], true)) {
517 $cdata = Contact::getPublicAndUserContactID($item['causer-id'], $item['uid']);
518 if (!empty($cdata['user'])) {
519 return $cdata['user'];
527 Logger::warning('contact-id could not be fetched, using self contact instead.', ['uid' => $item['uid'], 'item' => $item]);
528 $self = Contact::selectFirst(['id'], ['self' => true, 'uid' => $item['uid']]);
533 * Write an item array into a spool file to be inserted later.
534 * This command is called whenever there are issues storing an item.
536 * @param array $item The item fields that are to be inserted
539 private static function spool(array $item)
541 // Now we store the data in the spool directory
542 // We use "microtime" to keep the arrival order and "mt_rand" to avoid duplicates
543 $file = 'item-' . round(microtime(true) * 10000) . '-' . mt_rand() . '.msg';
545 $spoolpath = System::getSpoolPath();
546 if ($spoolpath != '') {
547 $spool = $spoolpath . '/' . $file;
549 file_put_contents($spool, json_encode($item));
550 Logger::warning("Item wasn't stored - Item was spooled into file", ['file' => $file]);
555 * Check if the item array is a duplicate
557 * @param array $item Item record
558 * @return boolean is it a duplicate?
560 private static function isDuplicate(array $item): bool
562 // Checking if there is already an item with the same guid
563 $condition = ['guid' => $item['guid'], 'network' => $item['network'], 'uid' => $item['uid']];
564 if (Post::exists($condition)) {
565 Logger::notice('Found already existing item', $condition);
570 'uri-id' => $item['uri-id'], 'uid' => $item['uid'],
571 'network' => [$item['network'], Protocol::DFRN]
573 if (Post::exists($condition)) {
574 Logger::notice('duplicated item with the same uri found.', $condition);
578 // On Friendica and Diaspora the GUID is unique
579 if (in_array($item['network'], [Protocol::DFRN, Protocol::DIASPORA])) {
580 $condition = ['guid' => $item['guid'], 'uid' => $item['uid']];
581 if (Post::exists($condition)) {
582 Logger::notice('duplicated item with the same guid found.', $condition);
585 } elseif ($item['network'] == Protocol::OSTATUS) {
586 // Check for an existing post with the same content. There seems to be a problem with OStatus.
588 "`body` = ? AND `network` = ? AND `created` = ? AND `contact-id` = ? AND `uid` = ?",
589 $item['body'], $item['network'], $item['created'], $item['contact-id'], $item['uid']
591 if (Post::exists($condition)) {
592 Logger::notice('duplicated item with the same body found.', $item);
598 * Check for already added items.
599 * There is a timing issue here that sometimes creates double postings.
600 * An unique index would help - but the limitations of MySQL (maximum size of index values) prevent this.
602 if (($item['uid'] == 0) && Post::exists(['uri-id' => $item['uri-id'], 'uid' => 0])) {
603 Logger::notice('Global item already stored.', ['uri-id' => $item['uri-id'], 'network' => $item['network']]);
611 * Check if the item array is valid
613 * @param array $item Item record
614 * @return boolean item is valid
616 public static function isValid(array $item): bool
618 // When there is no content then we don't post it
619 if (($item['body'] . $item['title'] == '') && empty($item['quote-uri-id']) && empty($item['attachments']) && (empty($item['uri-id']) || !Post\Media::existsByURIId($item['uri-id']))) {
620 Logger::notice('No body, no title.');
624 if (!empty($item['uid'])) {
625 $owner = User::getOwnerDataById($item['uid'], false);
627 Logger::warning('Missing item user owner data', ['uid' => $item['uid']]);
631 if ($owner['account_expired'] || $owner['account_removed']) {
632 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']]);
637 if (!empty($item['author-id']) && Contact::isBlocked($item['author-id'])) {
638 Logger::notice('Author is blocked node-wide', ['author-link' => $item['author-link'], 'item-uri' => $item['uri']]);
642 if (!empty($item['author-link']) && Network::isUrlBlocked($item['author-link'])) {
643 Logger::notice('Author server is blocked', ['author-link' => $item['author-link'], 'item-uri' => $item['uri']]);
647 if (!empty($item['owner-id']) && Contact::isBlocked($item['owner-id'])) {
648 Logger::notice('Owner is blocked node-wide', ['owner-link' => $item['owner-link'], 'item-uri' => $item['uri']]);
652 if (!empty($item['owner-link']) && Network::isUrlBlocked($item['owner-link'])) {
653 Logger::notice('Owner server is blocked', ['owner-link' => $item['owner-link'], 'item-uri' => $item['uri']]);
657 if ($item['verb'] == Activity::FOLLOW) {
658 if (!$item['origin'] && ($item['author-id'] == Contact::getPublicIdByUserId($item['uid']))) {
659 // Our own follow request can be relayed to us. We don't store it to avoid notification chaos.
660 Logger::info("Follow: Don't store not origin follow request", ['parent-uri' => $item['parent-uri']]);
665 'verb' => Activity::FOLLOW, 'uid' => $item['uid'],
666 'parent-uri' => $item['parent-uri'], 'author-id' => $item['author-id']
668 if (Post::exists($condition)) {
669 // It happens that we receive multiple follow requests by the same author - we only store one.
670 Logger::info('Follow: Found existing follow request from author', ['author-id' => $item['author-id'], 'parent-uri' => $item['parent-uri']]);
679 * Check if the item array is too old
681 * @param array $item Item record
682 * @return boolean item is too old
684 public static function isTooOld(array $item): bool
686 // check for create date and expire time
687 $expire_interval = DI::config()->get('system', 'dbclean-expire-days', 0);
689 $user = DBA::selectFirst('user', ['expire'], ['uid' => $item['uid']]);
690 if (DBA::isResult($user) && ($user['expire'] > 0) && (($user['expire'] < $expire_interval) || ($expire_interval == 0))) {
691 $expire_interval = $user['expire'];
694 if (($expire_interval > 0) && !empty($item['created'])) {
695 $expire_date = time() - ($expire_interval * 86400);
696 $created_date = strtotime($item['created']);
697 if ($created_date < $expire_date) {
698 Logger::notice('Item created before expiration interval.', [
699 'created' => date('c', $created_date),
700 'expired' => date('c', $expire_date),
711 * Return the id of the given item array if it has been stored before
713 * @param array $item Item record
714 * @return integer Item id or zero on error
716 private static function getDuplicateID(array $item): int
718 if (empty($item['network']) || in_array($item['network'], Protocol::FEDERATED)) {
720 '`uri-id` = ? AND `uid` = ? AND `network` IN (?, ?, ?, ?)',
723 Protocol::ACTIVITYPUB,
728 $existing = Post::selectFirst(['id', 'network'], $condition);
729 if (DBA::isResult($existing)) {
730 // We only log the entries with a different user id than 0. Otherwise we would have too many false positives
731 if ($item['uid'] != 0) {
732 Logger::notice('Item already existed for user', [
733 'uri-id' => $item['uri-id'],
734 'uid' => $item['uid'],
735 'network' => $item['network'],
736 'existing_id' => $existing['id'],
737 'existing_network' => $existing['network']
741 return $existing['id'];
748 * Fetch the uri-id of the parent for the given uri-id
750 * @param integer $uriid
753 public static function getParent(int $uriid): int
755 $thread_parent = Post::selectFirstPost(['thr-parent-id', 'gravity'], ['uri-id' => $uriid]);
756 if (empty($thread_parent)) {
760 if ($thread_parent['gravity'] == Item::GRAVITY_PARENT) {
764 return self::getParent($thread_parent['thr-parent-id']);
768 * Fetch top-level parent data for the given item array
771 * @return array item array with parent data
774 private static function getTopLevelParent(array $item): array
777 'uid', 'uri', 'parent-uri', 'id', 'deleted',
778 'uri-id', 'parent-uri-id',
779 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid',
780 'wall', 'private', 'origin', 'author-id'
782 $condition = ['uri-id' => [$item['thr-parent-id'], $item['parent-uri-id']], 'uid' => $item['uid']];
783 $params = ['order' => ['id' => false]];
784 $parent = Post::selectFirst($fields, $condition, $params);
786 if (!DBA::isResult($parent) && Post::exists(['uri-id' => [$item['thr-parent-id'], $item['parent-uri-id']], 'uid' => 0])) {
787 $stored = Item::storeForUserByUriId($item['thr-parent-id'], $item['uid'], ['post-reason' => Item::PR_COMPLETION]);
788 if (!$stored && ($item['thr-parent-id'] != $item['parent-uri-id'])) {
789 $stored = Item::storeForUserByUriId($item['parent-uri-id'], $item['uid'], ['post-reason' => Item::PR_COMPLETION]);
792 Logger::info('Stored thread parent item for user', ['uri-id' => $item['thr-parent-id'], 'uid' => $item['uid'], 'stored' => $stored]);
793 $parent = Post::selectFirst($fields, $condition, $params);
797 if (!DBA::isResult($parent)) {
798 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)]);
802 if ($parent['uri-id'] == $parent['parent-uri-id']) {
807 'uri-id' => $parent['parent-uri-id'],
808 'parent-uri-id' => $parent['parent-uri-id'],
809 'uid' => $parent['uid']
811 $params = ['order' => ['id' => false]];
812 $toplevel_parent = Post::selectFirst($fields, $condition, $params);
814 if (!DBA::isResult($toplevel_parent) && $item['origin']) {
815 $stored = Item::storeForUserByUriId($item['parent-uri-id'], $item['uid'], ['post-reason' => Item::PR_COMPLETION]);
816 Logger::info('Stored parent item for user', ['uri-id' => $item['parent-uri-id'], 'uid' => $item['uid'], 'stored' => $stored]);
817 $toplevel_parent = Post::selectFirst($fields, $condition, $params);
820 if (!DBA::isResult($toplevel_parent)) {
821 Logger::notice('item top level parent was not found - ignoring item', ['parent-uri-id' => $parent['parent-uri-id'], 'uid' => $parent['uid']]);
825 return $toplevel_parent;
829 * Get the gravity for the given item array
832 * @return integer gravity
834 private static function getGravity(array $item): int
836 $activity = DI::activity();
838 if (isset($item['gravity'])) {
839 return intval($item['gravity']);
840 } elseif ($item['parent-uri-id'] === $item['uri-id']) {
841 return self::GRAVITY_PARENT;
842 } elseif ($activity->match($item['verb'], Activity::POST)) {
843 return self::GRAVITY_COMMENT;
844 } elseif ($activity->match($item['verb'], Activity::FOLLOW)) {
845 return self::GRAVITY_ACTIVITY;
846 } elseif ($activity->match($item['verb'], Activity::ANNOUNCE)) {
847 return self::GRAVITY_ACTIVITY;
850 Logger::info('Unknown gravity for verb', ['verb' => $item['verb']]);
851 return self::GRAVITY_UNKNOWN; // Should not happen
854 private static function prepareOriginPost(array $item): array
856 $item = DI::contentItem()->initializePost($item);
857 $item = DI::contentItem()->finalizePost($item);
863 * Inserts item record
865 * @param array $item Item array to be inserted
866 * @param int $notify Notification (type?)
867 * @param bool $post_local (???)
868 * @return int Zero means error, otherwise primary key (id) is being returned
870 public static function insert(array $item, int $notify = 0, bool $post_local = true): int
874 $priority = Worker::PRIORITY_HIGH;
876 // If it is a posting where users should get notifications, then define it as wall posting
878 $item = self::prepareOriginPost($item);
880 if (is_int($notify) && in_array($notify, Worker::PRIORITIES)) {
884 $item['network'] = trim(($item['network'] ?? '') ?: Protocol::PHANTOM);
887 $uid = intval($item['uid']);
889 $item['guid'] = self::guid($item, $notify);
890 $item['uri'] = substr(trim($item['uri'] ?? '') ?: self::newURI($item['guid']), 0, 255);
893 $item['uri-id'] = ItemURI::insert(['uri' => $item['uri'], 'guid' => $item['guid']]);
895 // Backward compatibility: parent-uri used to be the direct parent uri.
896 // If it is provided without a thr-parent, it probably is the old behavior.
897 if (empty($item['thr-parent']) || empty($item['parent-uri'])) {
898 $item['thr-parent'] = trim($item['thr-parent'] ?? $item['parent-uri'] ?? $item['uri']);
899 $item['parent-uri'] = $item['thr-parent'];
902 $item['thr-parent-id'] = ItemURI::getIdByURI($item['thr-parent']);
903 $item['parent-uri-id'] = ItemURI::getIdByURI($item['parent-uri']);
905 // Store conversation data
906 $source = $item['source'] ?? '';
907 unset($item['conversation-uri']);
908 unset($item['conversation-href']);
909 unset($item['source']);
912 * Do we already have this item?
913 * We have to check several networks since Friendica posts could be repeated
914 * via OStatus (maybe Diaspora as well)
916 $duplicate = self::getDuplicateID($item);
921 // Additional duplicate checks
922 /// @todo Check why the first duplication check returns the item number and the second a 0
923 if (self::isDuplicate($item)) {
927 if (!isset($item['post-type'])) {
928 $item['post-type'] = empty($item['title']) ? self::PT_NOTE : self::PT_ARTICLE;
931 $defined_permissions = isset($item['allow_cid']) && isset($item['allow_gid']) && isset($item['deny_cid']) && isset($item['deny_gid']) && isset($item['private']);
933 $item['wall'] = intval($item['wall'] ?? 0);
934 $item['extid'] = trim($item['extid'] ?? '');
935 $item['author-name'] = trim($item['author-name'] ?? '');
936 $item['author-link'] = trim($item['author-link'] ?? '');
937 $item['author-avatar'] = trim($item['author-avatar'] ?? '');
938 $item['owner-name'] = trim($item['owner-name'] ?? '');
939 $item['owner-link'] = trim($item['owner-link'] ?? '');
940 $item['owner-avatar'] = trim($item['owner-avatar'] ?? '');
941 $item['received'] = (isset($item['received']) ? DateTimeFormat::utc($item['received']) : DateTimeFormat::utcNow());
942 $item['created'] = (isset($item['created']) ? DateTimeFormat::utc($item['created']) : $item['received']);
943 $item['edited'] = (isset($item['edited']) ? DateTimeFormat::utc($item['edited']) : $item['created']);
944 $item['changed'] = (isset($item['changed']) ? DateTimeFormat::utc($item['changed']) : $item['created']);
945 $item['commented'] = (isset($item['commented']) ? DateTimeFormat::utc($item['commented']) : $item['created']);
946 $item['title'] = substr(trim($item['title'] ?? ''), 0, 255);
947 $item['location'] = trim($item['location'] ?? '');
948 $item['coord'] = trim($item['coord'] ?? '');
949 $item['visible'] = (isset($item['visible']) ? intval($item['visible']) : 1);
950 $item['deleted'] = 0;
951 $item['verb'] = trim($item['verb'] ?? '');
952 $item['object-type'] = trim($item['object-type'] ?? '');
953 $item['object'] = trim($item['object'] ?? '');
954 $item['target-type'] = trim($item['target-type'] ?? '');
955 $item['target'] = trim($item['target'] ?? '');
956 $item['plink'] = substr(trim($item['plink'] ?? ''), 0, 255);
957 $item['allow_cid'] = trim($item['allow_cid'] ?? '');
958 $item['allow_gid'] = trim($item['allow_gid'] ?? '');
959 $item['deny_cid'] = trim($item['deny_cid'] ?? '');
960 $item['deny_gid'] = trim($item['deny_gid'] ?? '');
961 $item['private'] = intval($item['private'] ?? self::PUBLIC);
962 $item['body'] = trim($item['body'] ?? '');
963 $item['raw-body'] = trim($item['raw-body'] ?? $item['body']);
964 $item['app'] = trim($item['app'] ?? '');
965 $item['origin'] = intval($item['origin'] ?? 0);
966 $item['postopts'] = trim($item['postopts'] ?? '');
967 $item['resource-id'] = trim($item['resource-id'] ?? '');
968 $item['event-id'] = intval($item['event-id'] ?? 0);
969 $item['inform'] = trim($item['inform'] ?? '');
970 $item['file'] = trim($item['file'] ?? '');
972 // Communities aren't working with the Diaspora protocol
973 if (($uid != 0) && ($item['network'] == Protocol::DIASPORA)) {
974 $user = User::getById($uid, ['account-type']);
975 if ($user['account-type'] == Contact::TYPE_COMMUNITY) {
976 Logger::info('Community posts are not supported via Diaspora');
981 // Items cannot be stored before they happen ...
982 if ($item['created'] > DateTimeFormat::utcNow()) {
983 $item['created'] = DateTimeFormat::utcNow();
986 // We haven't invented time travel by now.
987 if ($item['edited'] > DateTimeFormat::utcNow()) {
988 $item['edited'] = DateTimeFormat::utcNow();
991 $item['plink'] = ($item['plink'] ?? '') ?: DI::baseUrl() . '/display/' . urlencode($item['guid']);
993 $item['gravity'] = self::getGravity($item);
996 'url' => $item['author-link'], 'name' => $item['author-name'],
997 'photo' => $item['author-avatar'], 'network' => $item['network']
999 $item['author-id'] = ($item['author-id'] ?? 0) ?: Contact::getIdForURL($item['author-link'], 0, null, $default);
1002 'url' => $item['owner-link'], 'name' => $item['owner-name'],
1003 'photo' => $item['owner-avatar'], 'network' => $item['network']
1005 $item['owner-id'] = ($item['owner-id'] ?? 0) ?: Contact::getIdForURL($item['owner-link'], 0, null, $default);
1007 $item['post-reason'] = self::getPostReason($item);
1009 // Ensure that there is an avatar cache
1010 Contact::checkAvatarCache($item['author-id']);
1011 Contact::checkAvatarCache($item['owner-id']);
1013 $item['contact-id'] = self::contactId($item);
1016 !empty($item['direction']) && in_array($item['direction'], [Conversation::PUSH, Conversation::RELAY]) &&
1017 empty($item['origin']) && self::isTooOld($item)
1019 Logger::info('Item is too old', ['item' => $item]);
1023 if (!self::isValid($item)) {
1027 if ($item['gravity'] !== self::GRAVITY_PARENT) {
1028 $toplevel_parent = self::getTopLevelParent($item);
1029 if (empty($toplevel_parent)) {
1033 $parent_id = $toplevel_parent['id'];
1034 $item['parent-uri'] = $toplevel_parent['uri'];
1035 $item['parent-uri-id'] = $toplevel_parent['uri-id'];
1036 $item['deleted'] = $toplevel_parent['deleted'];
1037 $item['wall'] = $toplevel_parent['wall'];
1039 // Reshares have to keep their permissions to allow groups to work
1040 if (!$defined_permissions && (!$item['origin'] || ($item['verb'] != Activity::ANNOUNCE))) {
1041 $item['allow_cid'] = $toplevel_parent['allow_cid'];
1042 $item['allow_gid'] = $toplevel_parent['allow_gid'];
1043 $item['deny_cid'] = $toplevel_parent['deny_cid'];
1044 $item['deny_gid'] = $toplevel_parent['deny_gid'];
1047 $parent_origin = $toplevel_parent['origin'];
1049 // Don't federate received participation messages
1050 if ($item['verb'] != Activity::FOLLOW) {
1051 $item['wall'] = $toplevel_parent['wall'];
1053 $item['wall'] = false;
1054 // Participations are technical messages, so they are set to "seen" automatically
1055 $item['unseen'] = false;
1059 * If the parent is private, force privacy for the entire conversation
1060 * This differs from the above settings as it subtly allows comments from
1061 * email correspondents to be private even if the overall thread is not.
1063 if (!$defined_permissions && $toplevel_parent['private']) {
1064 $item['private'] = $toplevel_parent['private'];
1067 // If its a post that originated here then tag the thread as "mention"
1068 if ($item['origin'] && $item['uid']) {
1069 DBA::update('post-thread-user', ['mention' => true], ['uri-id' => $item['parent-uri-id'], 'uid' => $item['uid']]);
1070 Logger::info('tagged thread as mention', ['parent' => $parent_id, 'parent-uri-id' => $item['parent-uri-id'], 'uid' => $item['uid']]);
1073 // Update the contact relations
1074 Contact\Relation::store($toplevel_parent['author-id'], $item['author-id'], $item['created']);
1077 $parent_origin = $item['origin'];
1079 if ($item['wall'] && empty($item['conversation'])) {
1080 $item['conversation'] = $item['parent-uri'] . '#context';
1084 if ($item['origin']) {
1086 Photo::setPermissionFromBody($item['body'], $item['uid'], $item['contact-id'], $item['allow_cid'], $item['allow_gid'], $item['deny_cid'], $item['deny_gid'])
1087 && ($item['object-type'] != Activity\ObjectType::EVENT)
1089 $item['object-type'] = Activity\ObjectType::IMAGE;
1092 $item = DI::contentItem()->moveAttachmentsFromBodyToAttach($item);
1095 $item['parent-uri-id'] = ItemURI::getIdByURI($item['parent-uri']);
1096 $item['thr-parent-id'] = ItemURI::getIdByURI($item['thr-parent']);
1098 if (!empty($item['conversation']) && empty($item['conversation-id'])) {
1099 $item['conversation-id'] = ItemURI::getIdByURI($item['conversation']);
1102 // Is this item available in the global items (with uid=0)?
1103 if ($item['uid'] == 0) {
1104 $item['global'] = true;
1106 // Set the global flag on all items if this was a global item entry
1107 Post::update(['global' => true], ['uri-id' => $item['uri-id']]);
1109 $item['global'] = Post::exists(['uid' => 0, 'uri-id' => $item['uri-id']]);
1113 if (!$defined_permissions && !empty($item['allow_cid'] . $item['allow_gid'] . $item['deny_cid'] . $item['deny_gid'])) {
1114 $item['private'] = self::PRIVATE;
1117 if ($notify && $post_local) {
1118 $item['edit'] = false;
1119 $item['parent'] = $parent_id;
1121 // Trigger automatic reactions for addons
1122 if (!isset($item['api_source'])) {
1123 $item['api_source'] = true;
1126 // We have to tell the hooks who we are - this really should be improved
1127 if (!DI::userSession()->getLocalUserId()) {
1128 $_SESSION['authenticated'] = true;
1129 $_SESSION['uid'] = $uid;
1130 $dummy_session = true;
1132 $dummy_session = false;
1135 Hook::callAll('post_local', $item);
1137 if ($dummy_session) {
1138 unset($_SESSION['authenticated']);
1139 unset($_SESSION['uid']);
1141 } elseif (!$notify) {
1142 Hook::callAll('post_remote', $item);
1145 if (!empty($item['cancel'])) {
1146 Logger::notice('post cancelled by addon.');
1150 if (empty($item['vid']) && !empty($item['verb'])) {
1151 $item['vid'] = Verb::getID($item['verb']);
1154 // Creates or assigns the permission set
1155 $item['psid'] = DI::permissionSet()->selectOrCreate(
1156 DI::permissionSetFactory()->createFromString(
1165 if (!empty($item['extid'])) {
1166 $item['external-id'] = ItemURI::getIdByURI($item['extid']);
1169 if ($item['verb'] == Activity::ANNOUNCE) {
1170 self::setOwnerforResharedItem($item);
1173 if (isset($item['attachments'])) {
1174 foreach ($item['attachments'] as $attachment) {
1175 $attachment['uri-id'] = $item['uri-id'];
1176 Post\Media::insert($attachment);
1178 unset($item['attachments']);
1181 if (empty($item['quote-uri-id'])) {
1182 $quote_id = self::getQuoteUriId($item['body']);
1183 if (!empty($quote_id)) {
1184 // This is one of these "should not happen" situations.
1185 // The protocol implementations should already have done this job.
1186 Logger::notice('Quote-uri-id detected in post', ['id' => $quote_id, 'guid' => $item['guid'], 'uri-id' => $item['uri-id'], 'callstack' => System::callstack(20)]);
1187 $item['quote-uri-id'] = $quote_id;
1191 if (!empty($item['quote-uri-id']) && ($item['quote-uri-id'] == $item['uri-id'])) {
1192 Logger::info('Quote-Uri-Id is identical to Uri-Id', ['uri-id' => $item['uri-id'], 'guid' => $item['guid']]);
1193 unset($item['quote-uri-id']);
1196 if (!empty($item['quote-uri-id'])) {
1197 $item['raw-body'] = BBCode::removeSharedData($item['raw-body']);
1198 $item['body'] = BBCode::removeSharedData($item['body']);
1201 // Remove all media attachments from the body and store them in the post-media table
1202 $item['raw-body'] = Post\Media::insertFromBody($item['uri-id'], $item['raw-body']);
1203 $item['raw-body'] = self::setHashtags($item['raw-body']);
1205 $author = Contact::getById($item['author-id'], ['network']);
1206 Post\Media::insertFromRelevantUrl($item['uri-id'], $item['raw-body'], $item['body'], $author['network'] ?? '');
1208 Post\Media::insertFromAttachmentData($item['uri-id'], $item['body']);
1209 $item['body'] = BBCode::removeAttachment($item['body']);
1210 $item['raw-body'] = BBCode::removeAttachment($item['raw-body']);
1212 // Check for hashtags in the body and repair or add hashtag links
1213 $item['body'] = self::setHashtags($item['body']);
1215 $notify_type = Delivery::POST;
1217 // Filling item related side tables
1218 if (!empty($item['attach'])) {
1219 Post\Media::insertFromAttachment($item['uri-id'], $item['attach']);
1222 if (empty($item['event-id'])) {
1223 unset($item['event-id']);
1225 $ev = Event::fromBBCode($item['body']);
1226 if ((!empty($ev['desc']) || !empty($ev['summary'])) && !empty($ev['start'])) {
1227 Logger::info('Event found.');
1228 $ev['cid'] = $item['contact-id'];
1229 $ev['uid'] = $item['uid'];
1230 $ev['uri'] = $item['uri'];
1231 $ev['edited'] = $item['edited'];
1232 $ev['private'] = $item['private'];
1233 $ev['guid'] = $item['guid'];
1234 $ev['plink'] = $item['plink'];
1235 $ev['network'] = $item['network'];
1236 $ev['protocol'] = $item['protocol'] ?? Conversation::PARCEL_UNKNOWN;
1237 $ev['direction'] = $item['direction'] ?? Conversation::UNKNOWN;
1238 $ev['source'] = $item['source'] ?? '';
1240 $event = DBA::selectFirst('event', ['id'], ['uri' => $item['uri'], 'uid' => $item['uid']]);
1241 if (DBA::isResult($event)) {
1242 $ev['id'] = $event['id'];
1245 $event_id = Event::store($ev);
1246 $item = Event::getItemArrayForImportedId($event_id, $item);
1248 Logger::info('Event was stored', ['id' => $event_id]);
1252 if (empty($item['causer-id'])) {
1253 unset($item['causer-id']);
1256 if (in_array($item['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN])) {
1257 $content_warning = BBCode::getAbstract($item['body'], Protocol::ACTIVITYPUB);
1258 if (!empty($content_warning) && empty($item['content-warning'])) {
1259 $item['content-warning'] = BBCode::toPlaintext($content_warning);
1263 $item['language'] = self::getLanguage($item);
1265 $inserted = Post::insert($item['uri-id'], $item);
1267 if ($item['gravity'] == self::GRAVITY_PARENT) {
1268 Post\Thread::insert($item['uri-id'], $item);
1271 // The content of activities normally doesn't matter - except for likes from Misskey
1272 if (!in_array($item['verb'], self::ACTIVITIES) || in_array($item['verb'], [Activity::LIKE, Activity::DISLIKE]) && !empty($item['body']) && (mb_strlen($item['body']) == 1)) {
1273 Post\Content::insert($item['uri-id'], $item);
1276 $item['parent'] = $parent_id;
1278 // Create Diaspora signature
1279 if ($item['origin'] && empty($item['diaspora_signed_text']) && ($item['gravity'] != self::GRAVITY_PARENT)) {
1280 $signed = Diaspora::createCommentSignature($item);
1281 if (!empty($signed)) {
1282 $item['diaspora_signed_text'] = json_encode($signed);
1286 if (!empty($item['diaspora_signed_text'])) {
1287 DBA::replace('diaspora-interaction', ['uri-id' => $item['uri-id'], 'interaction' => $item['diaspora_signed_text']]);
1290 // Attached file links
1291 if (!empty($item['file'])) {
1292 Post\Category::storeTextByURIId($item['uri-id'], $item['uid'], $item['file']);
1295 // Delivery relevant data
1296 $delivery_data = Post\DeliveryData::extractFields($item);
1298 if (!empty($item['origin']) || !empty($item['wall']) || !empty($delivery_data['postopts']) || !empty($delivery_data['inform'])) {
1299 Post\DeliveryData::insert($item['uri-id'], $delivery_data);
1302 // Store tags from the body if this hadn't been handled previously in the protocol classes
1303 if (!Tag::existsForPost($item['uri-id'])) {
1304 Tag::storeFromBody($item['uri-id'], $item['body']);
1307 $condition = ['uri-id' => $item['uri-id'], 'uid' => $item['uid']];
1308 if (Post::exists($condition)) {
1309 Logger::notice('Item is already inserted - aborting', $condition);
1313 $post_user_id = Post\User::insert($item['uri-id'], $item['uid'], $item);
1314 if (!$post_user_id) {
1315 Logger::notice('Post-User is already inserted - aborting', ['uid' => $item['uid'], 'uri-id' => $item['uri-id']]);
1319 if ($item['gravity'] == self::GRAVITY_PARENT) {
1320 $item['post-user-id'] = $post_user_id;
1321 Post\ThreadUser::insert($item['uri-id'], $item['uid'], $item);
1324 Logger::notice('created item', ['post-id' => $post_user_id, 'uid' => $item['uid'], 'network' => $item['network'], 'uri-id' => $item['uri-id'], 'guid' => $item['guid']]);
1326 $posted_item = Post::selectFirst(self::ITEM_FIELDLIST, ['post-user-id' => $post_user_id]);
1327 if (!DBA::isResult($posted_item)) {
1328 // On failure store the data into a spool file so that the "SpoolPost" worker can try again later.
1329 Logger::warning('Could not store item. it will be spooled', ['id' => $post_user_id]);
1330 self::spool($orig_item);
1334 // update the commented timestamp on the parent
1335 if (DI::config()->get('system', 'like_no_comment')) {
1336 // Update when it is a comment
1337 $update_commented = in_array($posted_item['gravity'], [self::GRAVITY_PARENT, self::GRAVITY_COMMENT]);
1339 // Update when it isn't a follow or tag verb
1340 $update_commented = !in_array($posted_item['verb'], [Activity::FOLLOW, Activity::TAG]);
1343 if ($update_commented) {
1344 $fields = ['commented' => DateTimeFormat::utcNow(), 'changed' => DateTimeFormat::utcNow()];
1346 $fields = ['changed' => DateTimeFormat::utcNow()];
1349 Post::update($fields, ['uri-id' => $posted_item['parent-uri-id'], 'uid' => $posted_item['uid']]);
1351 // In that function we check if this is a group post. Additionally we delete the item under certain circumstances
1352 if (self::tagDeliver($posted_item['uid'], $post_user_id)) {
1353 // Get the user information for the logging
1354 $user = User::getById($uid);
1356 Logger::notice('Item had been deleted', ['id' => $post_user_id, 'user' => $uid, 'account-type' => $user['account-type']]);
1361 DI::contentItem()->postProcessPost($posted_item);
1363 Hook::callAll('post_remote_end', $posted_item);
1366 if ($posted_item['gravity'] === self::GRAVITY_PARENT) {
1367 self::addShadow($post_user_id);
1369 self::addShadowPost($post_user_id);
1372 self::updateContact($posted_item);
1374 Post\UserNotification::setNotification($posted_item['uri-id'], $posted_item['uid']);
1376 // Distribute items to users who subscribed to their tags
1377 self::distributeByTags($posted_item);
1379 // Automatically reshare the item if the "remote_self" option is selected
1380 self::autoReshare($posted_item);
1382 $transmit = $notify || ($posted_item['visible'] && ($parent_origin || $posted_item['origin']));
1385 if ($posted_item['uid'] && Contact\User::isBlocked($posted_item['author-id'], $posted_item['uid'])) {
1386 Logger::info('Message from blocked author will not be relayed', ['item' => $posted_item['id'], 'uri' => $posted_item['uri'], 'cid' => $posted_item['author-id']]);
1389 if ($transmit && $posted_item['uid'] && Contact\User::isBlocked($posted_item['owner-id'], $posted_item['uid'])) {
1390 Logger::info('Message from blocked owner will not be relayed', ['item' => $posted_item['id'], 'uri' => $posted_item['uri'], 'cid' => $posted_item['owner-id']]);
1393 if ($transmit && !empty($posted_item['causer-id']) && $posted_item['uid'] && Contact\User::isBlocked($posted_item['causer-id'], $posted_item['uid'])) {
1394 Logger::info('Message from blocked causer will not be relayed', ['item' => $posted_item['id'], 'uri' => $posted_item['uri'], 'cid' => $posted_item['causer-id']]);
1398 // Don't relay participation messages
1399 if (($posted_item['verb'] == Activity::FOLLOW) &&
1400 (!$posted_item['origin'] || ($posted_item['author-id'] != Contact::getPublicIdByUserId($uid)))
1402 Logger::info('Participation messages will not be relayed', ['item' => $posted_item['id'], 'uri' => $posted_item['uri'], 'verb' => $posted_item['verb']]);
1407 if (!empty($source) && ($transmit || DI::config()->get('debug', 'store_source'))) {
1408 Post\Activity::insert($item['uri-id'], $source);
1412 Worker::add(['priority' => $priority, 'dont_fork' => true], 'Notifier', $notify_type, (int)$posted_item['uri-id'], (int)$posted_item['uid']);
1415 // Fill the cache with the rendered content.
1416 if (in_array($posted_item['gravity'], [self::GRAVITY_PARENT, self::GRAVITY_COMMENT]) && ($posted_item['uid'] == 0)) {
1417 self::updateDisplayCache($posted_item['uri-id']);
1421 Post\Engagement::storeFromItem($posted_item);
1424 return $post_user_id;
1428 * Fetch the post reason for a given item array
1430 * @param array $item
1434 public static function getPostReason(array $item): int
1436 $actor = ($item['gravity'] == self::GRAVITY_PARENT) ? $item['owner-id'] : $item['author-id'];
1437 if (empty($item['origin']) && ($item['uid'] != 0) && Contact::isSharing($actor, $item['uid'])) {
1438 return self::PR_FOLLOWER;
1441 if (!empty($item['origin']) && empty($item['post-reason'])) {
1442 return self::PR_LOCAL;
1445 return $item['post-reason'] ?? self::PR_NONE;
1449 * Update the display cache
1451 * @param integer $uri_id
1453 * @throws InternalServerErrorException
1454 * @throws \ImagickException
1456 public static function updateDisplayCache(int $uri_id)
1458 $item = Post::selectFirst(self::DISPLAY_FIELDLIST, ['uri-id' => $uri_id]);
1463 self::prepareBody($item, false, false, true);
1467 * Change the owner of a parent item if it had been shared by a group
1469 * (public) group posts in the new format consist of the regular post by the author
1470 * followed by an announce message sent from the group account.
1471 * Changing the owner helps in grouping group posts.
1473 * @param array $item
1476 private static function setOwnerforResharedItem(array $item)
1478 $parent = Post::selectFirst(
1479 ['id', 'causer-id', 'owner-id', 'author-id', 'author-link', 'origin', 'post-reason'],
1480 ['uri-id' => $item['thr-parent-id'], 'uid' => $item['uid']]
1482 if (!DBA::isResult($parent)) {
1483 Logger::error('Parent not found', ['uri-id' => $item['thr-parent-id'], 'uid' => $item['uid']]);
1487 $author = Contact::selectFirst(['url', 'contact-type', 'network'], ['id' => $item['author-id']]);
1488 if (!DBA::isResult($author)) {
1489 Logger::error('Author not found', ['id' => $item['author-id']]);
1493 $self_contact = Contact::selectFirst(['id'], ['uid' => $item['uid'], 'self' => true]);
1494 $self = !empty($self_contact) ? $self_contact['id'] : 0;
1496 $cid = Contact::getIdForURL($author['url'], $item['uid']);
1497 if (empty($cid) || (!Contact::isSharing($cid, $item['uid']) && ($cid != $self))) {
1498 Logger::info('The resharer is not a following contact: quit', ['resharer' => $author['url'], 'uid' => $item['uid'], 'cid' => $cid]);
1502 if ($author['contact-type'] != Contact::TYPE_COMMUNITY) {
1503 if ($parent['post-reason'] == self::PR_ANNOUNCEMENT) {
1504 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']]);
1508 if (Contact::isSharing($parent['owner-id'], $item['uid'])) {
1509 Logger::info('The resharer is no group: quit', ['resharer' => $item['author-id'], 'owner' => $parent['owner-id'], 'author' => $parent['author-id'], 'uid' => $item['uid']]);
1514 self::update(['post-reason' => self::PR_ANNOUNCEMENT, 'causer-id' => $item['author-id']], ['id' => $parent['id']]);
1515 Logger::info('Set announcement post-reason', ['uri-id' => $item['uri-id'], 'thr-parent-id' => $item['thr-parent-id'], 'uid' => $item['uid']]);
1519 * Distribute the given item to users who subscribed to their tags
1521 * @param array $item Processed item
1523 private static function distributeByTags(array $item)
1525 if (($item['uid'] != 0) || ($item['gravity'] != self::GRAVITY_PARENT) || !in_array($item['network'], Protocol::FEDERATED)) {
1529 foreach (Tag::getUIDListByURIId($item['uri-id']) as $uid => $tags) {
1530 $stored = self::storeForUserByUriId($item['uri-id'], $uid, ['post-reason' => self::PR_TAG]);
1531 Logger::info('Stored item for users', ['uri-id' => $item['uri-id'], 'uid' => $uid, 'stored' => $stored]);
1532 foreach ($tags as $tag) {
1533 $stored = Category::storeFileByURIId($item['uri-id'], $uid, Category::SUBCRIPTION, $tag);
1534 Logger::debug('Stored tag subscription for user', ['uri-id' => $item['uri-id'], 'uid' => $uid, $tag, 'stored' => $stored]);
1540 * Distributes public items to the receivers
1542 * @param integer $itemid Item ID that should be added
1543 * @param string $signed_text Original text (for Diaspora signatures), JSON encoded.
1544 * @throws \Exception
1546 public static function distribute(int $itemid, string $signed_text = '')
1548 $condition = ["`id` IN (SELECT `parent` FROM `post-user-view` WHERE `id` = ?)", $itemid];
1549 $parent = Post::selectFirst(['owner-id'], $condition);
1550 if (!DBA::isResult($parent)) {
1551 Logger::warning('Item not found', ['condition' => $condition]);
1555 // Only distribute public items from native networks
1557 'id' => $itemid, 'uid' => 0,
1558 'network' => array_merge(Protocol::FEDERATED, ['']),
1559 'visible' => true, 'deleted' => false, 'private' => [self::PUBLIC, self::UNLISTED]
1561 $item = Post::selectFirst(array_merge(self::ITEM_FIELDLIST, ['protocol']), $condition);
1562 if (!DBA::isResult($item)) {
1563 Logger::warning('Item not found', ['condition' => $condition]);
1567 $origin = $item['origin'];
1571 /// @todo add a field "pcid" in the contact table that refers to the public contact id.
1572 $owner = DBA::selectFirst('contact', ['url', 'nurl', 'alias'], ['id' => $parent['owner-id']]);
1573 if (!DBA::isResult($owner)) {
1577 $condition = ['nurl' => $owner['nurl'], 'rel' => [Contact::SHARING, Contact::FRIEND]];
1578 $contacts = DBA::select('contact', ['uid'], $condition);
1579 while ($contact = DBA::fetch($contacts)) {
1580 if ($contact['uid'] == 0) {
1584 $users[$contact['uid']] = $contact['uid'];
1586 DBA::close($contacts);
1588 $condition = ['alias' => $owner['url'], 'rel' => [Contact::SHARING, Contact::FRIEND]];
1589 $contacts = DBA::select('contact', ['uid'], $condition);
1590 while ($contact = DBA::fetch($contacts)) {
1591 if ($contact['uid'] == 0) {
1595 $users[$contact['uid']] = $contact['uid'];
1597 DBA::close($contacts);
1599 if (!empty($owner['alias'])) {
1600 $condition = ['nurl' => Strings::normaliseLink($owner['alias']), 'rel' => [Contact::SHARING, Contact::FRIEND]];
1601 $contacts = DBA::select('contact', ['uid'], $condition);
1602 while ($contact = DBA::fetch($contacts)) {
1603 if ($contact['uid'] == 0) {
1607 $users[$contact['uid']] = $contact['uid'];
1609 DBA::close($contacts);
1614 if ($item['uri-id'] != $item['parent-uri-id']) {
1615 $parents = Post::select(['uid', 'origin'], ["`uri-id` = ? AND `uid` != 0", $item['parent-uri-id']]);
1616 while ($parent = Post::fetch($parents)) {
1617 $users[$parent['uid']] = $parent['uid'];
1618 if ($parent['origin'] && !$origin) {
1619 $origin_uid = $parent['uid'];
1622 DBA::close($parents);
1625 foreach ($users as $uid) {
1626 if ($origin_uid == $uid) {
1627 $item['diaspora_signed_text'] = $signed_text;
1629 $item['post-reason'] = self::PR_DISTRIBUTE;
1630 self::storeForUser($item, $uid);
1635 * Store a public item defined by their URI-ID for the given users
1637 * @param integer $uri_id URI-ID of the given item
1638 * @param integer $uid The user that will receive the item entry
1639 * @param array $fields Additional fields to be stored
1640 * @param integer $source_uid User id of the source post
1641 * @return integer stored item id
1643 public static function storeForUserByUriId(int $uri_id, int $uid, array $fields = [], int $source_uid = 0): int
1645 if ($uid == $source_uid) {
1646 Logger::warning('target UID must not be be equal to the source UID', ['uri-id' => $uri_id, 'uid' => $uid]);
1650 $item = Post::selectFirst(array_merge(self::ITEM_FIELDLIST, ['protocol']), ['uri-id' => $uri_id, 'uid' => $source_uid]);
1651 if (!DBA::isResult($item)) {
1652 Logger::warning('Item could not be fetched', ['uri-id' => $uri_id, 'uid' => $source_uid]);
1656 if (($uid != 0) && ($item['gravity'] == self::GRAVITY_PARENT)) {
1657 $owner = User::getOwnerDataById($uid);
1658 if (($owner['contact-type'] == User::ACCOUNT_TYPE_COMMUNITY) && !Tag::isMentioned($uri_id, $owner['url'])) {
1659 Logger::info('Target user is a group but is not mentioned here, thread will not be stored', ['uid' => $uid, 'uri-id' => $uri_id]);
1664 if (($source_uid == 0) && (($item['private'] == self::PRIVATE) || !in_array($item['network'], Protocol::FEDERATED))) {
1665 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']]);
1669 $item['post-reason'] = self::PR_STORED;
1671 $item = array_merge($item, $fields);
1673 if (($uid != 0) && Contact::isSharing(($item['gravity'] == Item::GRAVITY_PARENT) ? $item['owner-id'] : $item['author-id'], $uid)) {
1674 $item['post-reason'] = self::PR_FOLLOWER;
1677 $is_reshare = ($item['gravity'] == self::GRAVITY_ACTIVITY) && ($item['verb'] == Activity::ANNOUNCE);
1679 if (($uid != 0) && (($item['gravity'] == self::GRAVITY_PARENT) || $is_reshare) &&
1680 DI::pConfig()->get($uid, 'system', 'accept_only_sharer') == self::COMPLETION_NONE &&
1681 !in_array($item['post-reason'], [self::PR_FOLLOWER, self::PR_TAG, self::PR_TO, self::PR_CC, self::PR_ACTIVITY, self::PR_AUDIENCE])
1683 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']]);
1687 $causer = $item['causer-id'] ?: $item['author-id'];
1689 if (($uri_id != $item['parent-uri-id']) && ($item['gravity'] == self::GRAVITY_COMMENT) && !Post::exists(['uri-id' => $item['parent-uri-id'], 'uid' => $uid])) {
1690 if (!self::fetchParent($item['parent-uri-id'], $uid, $causer)) {
1691 Logger::info('Parent post had not been added', ['uri-id' => $item['parent-uri-id'], 'uid' => $uid, 'causer' => $causer]);
1694 Logger::info('Fetched parent post', ['uri-id' => $item['parent-uri-id'], 'uid' => $uid, 'causer' => $causer]);
1695 } elseif (($uri_id != $item['thr-parent-id']) && $is_reshare && !Post::exists(['uri-id' => $item['thr-parent-id'], 'uid' => $uid])) {
1696 if (!self::fetchParent($item['thr-parent-id'], $uid, $causer)) {
1697 Logger::info('Thread parent had not been added', ['uri-id' => $item['thr-parent-id'], 'uid' => $uid, 'causer' => $causer]);
1700 Logger::info('Fetched thread parent', ['uri-id' => $item['thr-parent-id'], 'uid' => $uid, 'causer' => $causer]);
1703 $stored = self::storeForUser($item, $uid);
1704 Logger::info('Item stored for user', ['uri-id' => $item['uri-id'], 'uid' => $uid, 'causer' => $causer, 'source-uid' => $source_uid, 'stored' => $stored]);
1709 * Fetch the parent with the given uri-id
1711 * @param integer $uri_id
1712 * @param integer $uid
1713 * @param integer $causer
1717 private static function fetchParent(int $uri_id, int $uid, int $causer): int
1719 // Fetch the origin user for the post
1720 $origin_uid = self::GetOriginUidForUriId($uri_id, $uid);
1721 if (is_null($origin_uid)) {
1722 Logger::info('Origin item was not found', ['uid' => $uid, 'uri-id' => $uri_id]);
1726 return self::storeForUserByUriId($uri_id, $uid, ['causer-id' => $causer, 'post-reason' => self::PR_FETCHED], $origin_uid);
1730 * Returns the origin uid of a post if the given user is allowed to see it.
1736 private static function GetOriginUidForUriId(int $uriid, int $uid)
1738 if (Post::exists(['uri-id' => $uriid, 'uid' => $uid])) {
1742 $post = Post::selectFirst(['uid', 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid', 'private'], ['uri-id' => $uriid, 'origin' => true]);
1743 if (!empty($post)) {
1744 if (in_array($post['private'], [Item::PUBLIC, Item::UNLISTED])) {
1745 return $post['uid'];
1748 $pcid = Contact::getPublicIdByUserId($uid);
1753 foreach (Item::enumeratePermissions($post, true) as $receiver) {
1754 if ($receiver == $pcid) {
1755 return $post['uid'];
1762 if (Post::exists(['uri-id' => $uriid, 'uid' => 0])) {
1766 // When the post belongs to a a group then all group users are allowed to access it
1767 foreach (Tag::getByURIId($uriid, [Tag::MENTION, Tag::EXCLUSIVE_MENTION]) as $tag) {
1768 if (DBA::exists('contact', ['uid' => $uid, 'nurl' => Strings::normaliseLink($tag['url']), 'contact-type' => Contact::TYPE_COMMUNITY])) {
1769 $target_uid = User::getIdForURL($tag['url']);
1770 if (!empty($target_uid)) {
1780 * Store a public item array for the given users
1782 * @param array $item The item entry that will be stored
1783 * @param integer $uid The user that will receive the item entry
1784 * @return integer stored item id
1785 * @throws \Exception
1787 private static function storeForUser(array $item, int $uid): int
1789 $post = Post::selectFirst(['id'], ['uri-id' => $item['uri-id'], 'uid' => $uid]);
1790 if (!empty($post['id'])) {
1791 if (!empty($item['event-id'])) {
1792 $event_post = Post::selectFirst(['event-id'], ['uri-id' => $item['uri-id'], 'uid' => $uid]);
1793 if (!empty($event_post['event-id'])) {
1794 $event = DBA::selectFirst('event', ['edited', 'start', 'finish', 'summary', 'desc', 'location', 'nofinish'], ['id' => $item['event-id']]);
1795 if (!empty($event)) {
1796 // We aren't using "Event::store" here, since we don't want to trigger any further action
1797 $ret = DBA::update('event', $event, ['id' => $event_post['event-id']]);
1798 Logger::info('Event updated', ['uid' => $uid, 'source-event' => $item['event-id'], 'target-event' => $event_post['event-id'], 'ret' => $ret]);
1802 Logger::info('Item already exists', ['uri-id' => $item['uri-id'], 'uid' => $uid, 'id' => $post['id']]);
1806 // Data from the "post-user" table
1808 unset($item['mention']);
1809 unset($item['starred']);
1810 unset($item['unseen']);
1811 unset($item['psid']);
1812 unset($item['pinned']);
1813 unset($item['ignored']);
1814 unset($item['pubmail']);
1815 unset($item['event-id']);
1816 unset($item['hidden']);
1817 unset($item['notification-type']);
1819 // Data from the "post-delivery-data" table
1820 unset($item['postopts']);
1821 unset($item['inform']);
1823 $item['uid'] = $uid;
1824 $item['origin'] = 0;
1828 if ($item['gravity'] == self::GRAVITY_PARENT) {
1829 $contact = DBA::selectFirst('contact', [], ['id' => $item['contact-id'], 'self' => false]);
1830 if (DBA::isResult($contact)) {
1831 $notify = self::isRemoteSelf($contact, $item);
1832 $item['wall'] = (bool)$notify;
1836 $item['contact-id'] = self::contactId($item);
1837 $distributed = self::insert($item, $notify);
1839 if (!$distributed) {
1840 Logger::info("Distributed item wasn't stored", ['uri-id' => $item['uri-id'], 'user' => $uid]);
1842 Logger::info('Distributed item was stored', ['uri-id' => $item['uri-id'], 'user' => $uid, 'stored' => $distributed]);
1844 return $distributed;
1848 * Add a shadow entry for a given item id that is a thread starter
1850 * We store every public item entry additionally with the user id "0".
1851 * This is used for the community page and for the search.
1852 * It is planned that in the future we will store public item entries only once.
1854 * @param integer $itemid Item ID that should be added
1855 * @throws \Exception
1857 private static function addShadow(int $itemid)
1859 $fields = ['uid', 'private', 'visible', 'deleted', 'network', 'uri-id'];
1860 $condition = ['id' => $itemid, 'gravity' => self::GRAVITY_PARENT];
1861 $item = Post::selectFirst($fields, $condition);
1863 if (!DBA::isResult($item)) {
1867 // is it already a copy?
1868 if (($itemid == 0) || ($item['uid'] == 0)) {
1872 // Is it a visible public post?
1873 if (!$item["visible"] || $item["deleted"] || ($item["private"] == self::PRIVATE)) {
1877 // is it an entry from a connector? Only add an entry for natively connected networks
1878 if (!in_array($item["network"], array_merge(Protocol::FEDERATED, ['']))) {
1882 if (Post::exists(['uri-id' => $item['uri-id'], 'uid' => 0])) {
1886 $item = Post::selectFirst(array_merge(self::ITEM_FIELDLIST, ['protocol']), ['id' => $itemid]);
1888 if (DBA::isResult($item)) {
1889 // Preparing public shadow (removing user specific data)
1892 unset($item['parent']);
1893 unset($item['wall']);
1894 unset($item['mention']);
1895 unset($item['origin']);
1896 unset($item['starred']);
1897 unset($item['postopts']);
1898 unset($item['inform']);
1899 unset($item['post-reason']);
1900 if ($item['uri-id'] == $item['parent-uri-id']) {
1901 $item['contact-id'] = $item['owner-id'];
1903 $item['contact-id'] = $item['author-id'];
1906 $public_shadow = self::insert($item);
1908 Logger::info('Stored public shadow', ['thread' => $itemid, 'id' => $public_shadow]);
1913 * Add a shadow entry for a given item id that is a comment
1915 * This function does the same like the function above - but for comments
1917 * @param integer $itemid Item ID that should be added
1918 * @throws \Exception
1920 private static function addShadowPost(int $itemid)
1922 $item = Post::selectFirst(array_merge(self::ITEM_FIELDLIST, ['protocol']), ['id' => $itemid]);
1923 if (!DBA::isResult($item)) {
1927 // Is it a toplevel post?
1928 if ($item['gravity'] == self::GRAVITY_PARENT) {
1929 self::addShadow($itemid);
1933 // Is this a shadow entry?
1934 if ($item['uid'] == 0) {
1938 // Is there a shadow parent?
1939 if (!Post::exists(['uri-id' => $item['parent-uri-id'], 'uid' => 0])) {
1943 // Is there already a shadow entry?
1944 if (Post::exists(['uri-id' => $item['uri-id'], 'uid' => 0])) {
1948 // Save "origin" and "parent" state
1949 $origin = $item['origin'];
1950 $parent = $item['parent'];
1952 // Preparing public shadow (removing user specific data)
1955 unset($item['parent']);
1956 unset($item['wall']);
1957 unset($item['mention']);
1958 unset($item['origin']);
1959 unset($item['starred']);
1960 unset($item['postopts']);
1961 unset($item['inform']);
1962 unset($item['post-reason']);
1963 $item['contact-id'] = Contact::getIdForURL($item['author-link']);
1965 $public_shadow = self::insert($item);
1967 Logger::info('Stored public shadow', ['uri-id' => $item['uri-id'], 'id' => $public_shadow]);
1969 // If this was a comment to a Diaspora post we don't get our comment back.
1970 // This means that we have to distribute the comment by ourselves.
1971 if ($origin && Post::exists(['id' => $parent, 'network' => Protocol::DIASPORA])) {
1972 self::distribute($public_shadow);
1977 * Adds a language specification in a "language" element of given $arr.
1978 * Expects "body" element to exist in $arr.
1980 * @param array $item
1981 * @return string detected language
1982 * @throws \Text_LanguageDetect_Exception
1984 private static function getLanguage(array $item): string
1986 if (!empty($item['language'])) {
1987 return $item['language'];
1990 if (!in_array($item['gravity'], [self::GRAVITY_PARENT, self::GRAVITY_COMMENT]) || empty($item['body'])) {
1994 $languages = self::getLanguageArray($item['title'] . ' ' . ($item['content-warning'] ?? '') . ' ' . $item['body'], 3, $item['uri-id'], $item['author-id']);
1995 if (empty($languages)) {
1999 return json_encode($languages);
2003 * Get a language array from a given text
2005 * @param string $body
2006 * @param integer $count
2007 * @param integer $uri_id
2008 * @param integer $author_id
2011 public static function getLanguageArray(string $body, int $count, int $uri_id = 0, int $author_id = 0): array
2013 $searchtext = BBCode::toSearchText($body, $uri_id);
2015 if ((count(explode(' ', $searchtext)) < 10) && (mb_strlen($searchtext) < 30) && $author_id) {
2016 $author = Contact::selectFirst(['about'], ['id' => $author_id]);
2017 if (!empty($author['about'])) {
2018 $about = BBCode::toSearchText($author['about'], 0);
2019 Logger::debug('About field added', ['author' => $author_id, 'body' => $searchtext, 'about' => $about]);
2020 $searchtext .= ' ' . $about;
2024 if (empty($searchtext)) {
2028 $availableLanguages = DI::l10n()->getAvailableLanguages(true);
2029 $availableLanguages = DI::l10n()->convertForLanguageDetection($availableLanguages);
2031 $ld = new Language(array_keys($availableLanguages));
2035 foreach (self::splitByBlocks($searchtext) as $block) {
2036 $languages = $ld->detect($block)->limit(0, $count)->close() ?: [];
2040 'detected' => $languages,
2041 'uri-id' => $uri_id,
2042 'author-id' => $author_id,
2044 Hook::callAll('detect_languages', $data);
2046 foreach ($data['detected'] as $language => $quality) {
2047 $result[$language] = max($result[$language] ?? 0, $quality * (strlen($block) / strlen($searchtext)));
2052 $result = array_slice($result, 0, $count);
2058 * Split a string into different unicode blocks
2059 * Currently the text is split into the latin and the non latin part.
2061 * @param string $body
2064 private static function splitByBlocks(string $body): array
2066 if (class_exists('IntlChar')) {
2071 $previous_block = 0;
2073 for ($i = 0; $i < mb_strlen($body); $i++) {
2074 $character = mb_substr($body, $i, 1);
2075 $previous = ($i > 0) ? mb_substr($body, $i - 1, 1) : '';
2076 $next = ($i < mb_strlen($body)) ? mb_substr($body, $i + 1, 1) : '';
2078 if (!\IntlChar::isalpha($character)) {
2079 if (($previous != '') && (\IntlChar::isalpha($previous))) {
2080 $previous_block = self::getBlockCode($previous);
2083 $block = (($next != '') && \IntlChar::isalpha($next)) ? self::getBlockCode($next) : $previous_block;
2084 $blocks[$block] = ($blocks[$block] ?? '') . $character;
2086 $block = self::getBlockCode($character);
2087 $blocks[$block] = ($blocks[$block] ?? '') . $character;
2091 foreach (array_keys($blocks) as $key) {
2092 $blocks[$key] = trim($blocks[$key]);
2093 if (empty($blocks[$key])) {
2094 unset($blocks[$key]);
2098 return array_values($blocks);
2102 * returns the block code for the given character
2104 * @param string $character
2105 * @return integer 0 = no alpha character (blank, signs, emojis, ...), 1 = latin character, 2 = character in every other language
2107 private static function getBlockCode(string $character): int
2109 if (!\IntlChar::isalpha($character)) {
2112 return self::isLatin($character) ? 1 : 2;
2116 * Checks if the given character is in one of the latin code blocks
2118 * @param string $character
2121 private static function isLatin(string $character): bool
2123 return in_array(\IntlChar::getBlockCode($character), [
2124 \IntlChar::BLOCK_CODE_BASIC_LATIN, \IntlChar::BLOCK_CODE_LATIN_1_SUPPLEMENT,
2125 \IntlChar::BLOCK_CODE_LATIN_EXTENDED_A, \IntlChar::BLOCK_CODE_LATIN_EXTENDED_B,
2126 \IntlChar::BLOCK_CODE_LATIN_EXTENDED_C, \IntlChar::BLOCK_CODE_LATIN_EXTENDED_D,
2127 \IntlChar::BLOCK_CODE_LATIN_EXTENDED_E, \IntlChar::BLOCK_CODE_LATIN_EXTENDED_ADDITIONAL
2131 public static function getLanguageMessage(array $item): string
2133 $iso639 = new \Matriphe\ISO639\ISO639;
2135 $used_languages = '';
2136 foreach (json_decode($item['language'], true) as $language => $reliability) {
2137 $used_languages .= $iso639->languageByCode1($language) . ' (' . $language . "): " . number_format($reliability, 5) . '\n';
2139 $used_languages = DI::l10n()->t('Detected languages in this post:\n%s', $used_languages);
2140 return $used_languages;
2144 * Creates an unique guid out of a given uri.
2145 * This function is used for messages outside the fediverse (Connector posts, feeds, Mails, ...)
2146 * Posts that are created on this system are using System::createUUID.
2147 * Received ActivityPub posts are using Processor::getGUIDByURL.
2149 * @param string $uri uri of an item entry
2150 * @param string|null $host hostname for the GUID prefix
2151 * @return string Unique guid
2152 * @throws \Exception
2154 public static function guidFromUri(string $uri, string $host = null): string
2156 // Our regular guid routine is using this kind of prefix as well
2157 // We have to avoid that different routines could accidentally create the same value
2158 $parsed = parse_url($uri);
2160 // Remove the scheme to make sure that "https" and "http" doesn't make a difference
2161 unset($parsed['scheme']);
2163 $hostPart = $host ?: $parsed['host'] ?? '';
2165 Logger::warning('Empty host GUID part', ['uri' => $uri, 'host' => $host, 'parsed' => $parsed, 'callstack' => System::callstack(10)]);
2168 // Glue it together to be able to make a hash from it
2169 if (!empty($parsed)) {
2170 $host_id = implode('/', $parsed);
2175 // Use a mixture of several hashes to provide some GUID like experience
2176 return hash('crc32', $hostPart) . '-' . hash('joaat', $host_id) . '-' . hash('fnv164', $host_id);
2180 * generate an unique URI
2182 * @param string $guid An existing GUID (Otherwise it will be generated)
2185 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2187 public static function newURI(string $guid = ''): string
2190 $guid = System::createUUID();
2193 return DI::baseUrl() . '/objects/' . $guid;
2197 * Set "success_update" and "last-item" to the date of the last time we heard from this contact
2199 * This can be used to filter for inactive contacts.
2200 * Only do this for public postings to avoid privacy problems, since poco data is public.
2201 * Don't set this value if it isn't from the owner (could be an author that we don't know)
2203 * @param array $arr Contains the just posted item record
2204 * @throws \Exception
2206 private static function updateContact(array $arr)
2208 // Unarchive the author
2209 $contact = DBA::selectFirst('contact', [], ['id' => $arr["author-id"]]);
2210 if (DBA::isResult($contact)) {
2211 Contact::unmarkForArchival($contact);
2214 // Unarchive the contact if it's not our own contact
2215 $contact = DBA::selectFirst('contact', [], ['id' => $arr["contact-id"], 'self' => false]);
2216 if (DBA::isResult($contact)) {
2217 Contact::unmarkForArchival($contact);
2220 /// @todo On private posts we could obfuscate the date
2221 $update = ($arr['private'] != self::PRIVATE) || in_array($arr['network'], Protocol::FEDERATED);
2223 // Is it a group? Then we don't care about the rules from above
2224 if (!$update && in_array($arr["network"], [Protocol::ACTIVITYPUB, Protocol::DFRN]) && ($arr["parent-uri-id"] === $arr["uri-id"])) {
2225 if (DBA::exists('contact', ['id' => $arr['contact-id'], 'forum' => true])) {
2231 // The "self" contact id is used (for example in the connectors) when the contact is unknown
2232 // So we have to ensure to only update the last item when it had been our own post,
2233 // or it had been done by a "regular" contact.
2234 if (!empty($arr['wall'])) {
2235 $condition = ['id' => $arr['contact-id']];
2237 $condition = ['id' => $arr['contact-id'], 'self' => false];
2239 Contact::update(['failed' => false, 'local-data' => true, 'success_update' => $arr['received'], 'last-item' => $arr['received']], $condition);
2241 // Now do the same for the system wide contacts with uid=0
2242 if ($arr['private'] != self::PRIVATE) {
2244 ['failed' => false, 'local-data' => true, 'success_update' => $arr['received'], 'last-item' => $arr['received']],
2245 ['id' => $arr['owner-id']]
2248 if ($arr['owner-id'] != $arr['author-id']) {
2250 ['failed' => false, 'local-data' => true, 'success_update' => $arr['received'], 'last-item' => $arr['received']],
2251 ['id' => $arr['author-id']]
2257 public static function setHashtags(string $body): string
2259 $body = BBCode::performWithEscapedTags($body, ['noparse', 'pre', 'code', 'img'], function ($body) {
2260 $tags = BBCode::getTags($body);
2263 if (!count($tags)) {
2267 // This sorting is important when there are hashtags that are part of other hashtags
2268 // Otherwise there could be problems with hashtags like #test and #test2
2269 // Because of this we are sorting from the longest to the shortest tag.
2270 usort($tags, function ($a, $b) {
2271 return strlen($b) <=> strlen($a);
2274 $URLSearchString = "^\[\]";
2276 // All hashtags should point to the home server if "local_tags" is activated
2277 if (DI::config()->get('system', 'local_tags')) {
2278 $body = preg_replace(
2279 "/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
2280 "#[url=" . DI::baseUrl() . "/search?tag=$2]$2[/url]",
2285 // mask hashtags inside of url, bookmarks and attachments to avoid urls in urls
2286 $body = preg_replace_callback(
2287 "/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
2289 return ("[url=" . str_replace("#", "#", $match[1]) . "]" . str_replace("#", "#", $match[2]) . "[/url]");
2294 $body = preg_replace_callback(
2295 "/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism",
2297 return ("[bookmark=" . str_replace("#", "#", $match[1]) . "]" . str_replace("#", "#", $match[2]) . "[/bookmark]");
2302 $body = preg_replace_callback(
2303 "/\[attachment (.*?)\](.*?)\[\/attachment\]/ism",
2305 return ("[attachment " . str_replace("#", "#", $match[1]) . "]" . $match[2] . "[/attachment]");
2310 // Repair recursive urls
2311 $body = preg_replace(
2312 "/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
2317 foreach ($tags as $tag) {
2318 if ((strpos($tag, '#') !== 0) || strpos($tag, '[url=') || strlen($tag) < 2 || $tag[1] == '#') {
2322 $basetag = str_replace('_', ' ', substr($tag, 1));
2323 $newtag = '#[url=' . DI::baseUrl() . '/search?tag=' . $basetag . ']' . $basetag . '[/url]';
2325 $body = str_replace($tag, $newtag, $body);
2328 // Convert back the masked hashtags
2329 $body = str_replace("#", "#", $body);
2338 * look for mention tags and setup a second delivery chain for group/community posts if appropriate
2341 * @param int $item_id
2342 * @return boolean true if item was deleted, else false
2343 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2344 * @throws \ImagickException
2346 private static function tagDeliver(int $uid, int $item_id): bool
2348 $owner = User::getOwnerDataById($uid);
2349 if (!DBA::isResult($owner)) {
2350 Logger::warning('User not found, quitting here.', ['uid' => $uid]);
2354 if ($owner['contact-type'] != User::ACCOUNT_TYPE_COMMUNITY) {
2355 Logger::debug('Owner is no community, quitting here.', ['uid' => $uid, 'id' => $item_id]);
2359 $item = Post::selectFirst(self::ITEM_FIELDLIST, ['id' => $item_id, 'gravity' => [self::GRAVITY_PARENT, self::GRAVITY_COMMENT], 'origin' => false]);
2360 if (!DBA::isResult($item)) {
2361 Logger::debug('Post is an activity or origin or not found at all, quitting here.', ['id' => $item_id]);
2365 if ($item['gravity'] == self::GRAVITY_PARENT) {
2366 if (Tag::isMentioned($item['uri-id'], $owner['url'])) {
2367 Logger::info('Mention found in tag.', ['uri' => $item['uri'], 'uid' => $uid, 'id' => $item_id, 'uri-id' => $item['uri-id'], 'guid' => $item['guid']]);
2369 Logger::info('Top-level post without mention is deleted.', ['uri' => $item['uri'], $uid, 'id' => $item_id, 'uri-id' => $item['uri-id'], 'guid' => $item['guid']]);
2370 Post\User::delete(['uri-id' => $item['uri-id'], 'uid' => $item['uid']]);
2374 $arr = ['item' => $item, 'user' => $owner];
2376 Hook::callAll('tagged', $arr);
2378 if (Tag::isMentioned($item['parent-uri-id'], $owner['url'])) {
2379 Logger::info('Mention found in parent tag.', ['uri' => $item['uri'], 'uid' => $uid, 'id' => $item_id, 'uri-id' => $item['uri-id'], 'guid' => $item['guid']]);
2381 Logger::debug('No mentions found in parent, quitting here.', ['id' => $item_id, 'uri-id' => $item['uri-id'], 'guid' => $item['guid']]);
2386 Logger::info('Community post will be distributed', ['uri' => $item['uri'], 'uid' => $uid, 'id' => $item_id, 'uri-id' => $item['uri-id'], 'guid' => $item['guid']]);
2388 if ($owner['page-flags'] == User::PAGE_FLAGS_PRVGROUP) {
2390 $allow_gid = '<' . Circle::FOLLOWERS . '>';
2393 self::performActivity($item['id'], 'announce', $uid, $allow_cid, $allow_gid, $deny_cid, $deny_gid);
2395 self::performActivity($item['id'], 'announce', $uid);
2398 Logger::info('Community post had been distributed', ['uri' => $item['uri'], 'uid' => $uid, 'id' => $item_id, 'uri-id' => $item['uri-id'], 'guid' => $item['guid']]);
2403 * Automatically reshare the item if the "remote_self" option is selected
2405 * @param array $item
2408 private static function autoReshare(array $item)
2410 if ($item['gravity'] != self::GRAVITY_PARENT) {
2414 $cdata = Contact::getPublicAndUserContactID($item['author-id'], $item['uid']);
2415 if (empty($cdata['user']) || ($cdata['user'] != $item['contact-id'])) {
2419 if (!DBA::exists('contact', ['id' => $cdata['user'], 'remote_self' => LocalRelationship::MIRROR_NATIVE_RESHARE])) {
2423 if (!in_array($item['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN])) {
2427 if (User::getById($item['uid'], ['blocked'])['blocked'] ?? false) {
2431 Logger::info('Automatically reshare item', ['uid' => $item['uid'], 'id' => $item['id'], 'guid' => $item['guid'], 'uri-id' => $item['uri-id']]);
2433 self::performActivity($item['id'], 'announce', $item['uid']);
2436 public static function isRemoteSelf(array $contact, array &$datarray): bool
2438 if ($contact['remote_self'] != LocalRelationship::MIRROR_OWN_POST) {
2442 // Prevent the forwarding of posts that are forwarded
2443 if (!empty($datarray['extid']) && ($datarray['extid'] == Protocol::DFRN)) {
2444 Logger::info('Already forwarded');
2448 // Prevent to forward already forwarded posts
2449 if ($datarray['app'] == DI::baseUrl()->getHost()) {
2450 Logger::info('Already forwarded (second test)');
2454 // Only forward posts
2455 if ($datarray['verb'] != Activity::POST) {
2456 Logger::info('No post');
2460 if (($contact['network'] != Protocol::FEED) && ($datarray['private'] == self::PRIVATE)) {
2461 Logger::info('Not public');
2465 if (User::getById($contact['uid'], ['blocked'])['blocked'] ?? false) {
2466 Logger::info('User is blocked', ['contact' => $contact]);
2470 $datarray2 = $datarray;
2471 Logger::info('remote-self start', ['contact' => $contact['url'], 'remote_self' => $contact['remote_self'], 'item' => $datarray]);
2473 $self = DBA::selectFirst(
2475 ['id', 'name', 'url', 'thumb'],
2476 ['uid' => $contact['uid'], 'self' => true]
2478 if (!DBA::isResult($self)) {
2479 Logger::error('Self contact not found', ['uid' => $contact['uid']]);
2483 $datarray['contact-id'] = $self['id'];
2485 $datarray['author-name'] = $datarray['owner-name'] = $self['name'];
2486 $datarray['author-link'] = $datarray['owner-link'] = $self['url'];
2487 $datarray['author-avatar'] = $datarray['owner-avatar'] = $self['thumb'];
2489 unset($datarray['edited']);
2491 unset($datarray['network']);
2492 unset($datarray['owner-id']);
2493 unset($datarray['author-id']);
2495 if ($contact['network'] != Protocol::FEED) {
2496 $old_uri_id = $datarray['uri-id'] ?? 0;
2497 $datarray['guid'] = System::createUUID();
2498 unset($datarray['plink']);
2499 $datarray['uri'] = self::newURI($datarray['guid']);
2500 $datarray['uri-id'] = ItemURI::getIdByURI($datarray['uri']);
2501 $datarray['extid'] = Protocol::DFRN;
2502 $urlpart = parse_url($datarray2['author-link']);
2503 $datarray['app'] = $urlpart['host'];
2504 if (!empty($old_uri_id)) {
2505 Post\Media::copy($old_uri_id, $datarray['uri-id']);
2508 unset($datarray['parent-uri']);
2509 unset($datarray['thr-parent']);
2511 // Store the original post
2512 $result = self::insert($datarray2);
2513 Logger::info('remote-self post original item', ['contact' => $contact['url'], 'result' => $result, 'item' => $datarray2]);
2515 $datarray['private'] = self::PUBLIC;
2516 $datarray['app'] = 'Feed';
2520 return (bool)$result;
2527 * @param array $item
2530 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2531 * @throws \ImagickException
2533 public static function fixPrivatePhotos(string $s, int $uid, array $item = null, int $cid = 0): string
2535 if (DI::config()->get('system', 'disable_embedded')) {
2539 Logger::info('check for photos');
2540 $site = substr(DI::baseUrl(), strpos(DI::baseUrl(), '://'));
2545 $img_start = strpos($orig_body, '[img');
2546 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
2547 $img_len = ($img_start !== false ? strpos(substr($orig_body, $img_start + $img_st_close + 1), '[/img]') : false);
2549 while (($img_st_close !== false) && ($img_len !== false)) {
2550 $img_st_close++; // make it point to AFTER the closing bracket
2551 $image = substr($orig_body, $img_start + $img_st_close, $img_len);
2553 Logger::info('found photo', ['image' => $image]);
2555 if (stristr($image, $site . '/photo/')) {
2556 // Only embed locally hosted photos
2558 $i = basename($image);
2559 $i = str_replace(['.jpg', '.png', '.gif'], ['', '', ''], $i);
2560 $x = strpos($i, '-');
2563 $res = substr($i, $x + 1);
2564 $i = substr($i, 0, $x);
2565 $photo = Photo::getPhotoForUser($uid, $i, $res);
2566 if (DBA::isResult($photo)) {
2568 * Check to see if we should replace this photo link with an embedded image
2569 * 1. No need to do so if the photo is public
2570 * 2. If there's a contact-id provided, see if they're in the access list
2571 * for the photo. If so, embed it.
2572 * 3. Otherwise, if we have an item, see if the item permissions match the photo
2573 * permissions, regardless of order but first check to see if they're an exact
2574 * match to save some processing overhead.
2576 if (self::hasPermissions($photo)) {
2578 $recips = self::enumeratePermissions($photo);
2579 if (in_array($cid, $recips)) {
2583 if (self::samePermissions($uid, $item, $photo)) {
2589 $photo_img = Photo::getImageForPhoto($photo);
2590 // If a custom width and height were specified, apply before embedding
2591 if (preg_match("/\[img\=([0-9]*)x([0-9]*)\]/is", substr($orig_body, $img_start, $img_st_close), $match)) {
2592 Logger::info('scaling photo');
2594 $width = intval($match[1]);
2595 $height = intval($match[2]);
2597 $photo_img->scaleDown(max($width, $height));
2600 $data = $photo_img->asString();
2601 $type = $photo_img->getType();
2603 Logger::info('replacing photo');
2604 $image = 'data:' . $type . ';base64,' . base64_encode($data);
2605 Logger::debug('replaced', ['image' => $image]);
2611 $new_body = $new_body . substr($orig_body, 0, $img_start + $img_st_close) . $image . '[/img]';
2612 $orig_body = substr($orig_body, $img_start + $img_st_close + $img_len + strlen('[/img]'));
2613 if ($orig_body === false) {
2617 $img_start = strpos($orig_body, '[img');
2618 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
2619 $img_len = ($img_start !== false ? strpos(substr($orig_body, $img_start + $img_st_close + 1), '[/img]') : false);
2622 $new_body = $new_body . $orig_body;
2627 private static function hasPermissions(array $obj)
2629 return !empty($obj['allow_cid']) || !empty($obj['allow_gid']) ||
2630 !empty($obj['deny_cid']) || !empty($obj['deny_gid']);
2633 // @TODO $uid is unused parameter
2634 private static function samePermissions($uid, array $obj1, array $obj2): bool
2636 // first part is easy. Check that these are exactly the same.
2637 if (($obj1['allow_cid'] == $obj2['allow_cid'])
2638 && ($obj1['allow_gid'] == $obj2['allow_gid'])
2639 && ($obj1['deny_cid'] == $obj2['deny_cid'])
2640 && ($obj1['deny_gid'] == $obj2['deny_gid'])
2645 // This is harder. Parse all the permissions and compare the resulting set.
2646 $recipients1 = self::enumeratePermissions($obj1);
2647 $recipients2 = self::enumeratePermissions($obj2);
2651 /// @TODO Comparison of arrays, maybe use array_diff_assoc() here?
2652 return ($recipients1 == $recipients2);
2656 * Returns an array of contact-ids that are allowed to see this object
2658 * @param array $obj Item array with at least uid, allow_cid, allow_gid, deny_cid and deny_gid
2659 * @param bool $check_dead Prunes unavailable contacts from the result
2660 * @param bool $expand_followers Expand the list of followers
2662 * @throws \Exception
2664 public static function enumeratePermissions(array $obj, bool $check_dead = false, bool $expand_followers = true): array
2666 $aclFormatter = DI::aclFormatter();
2668 if (!$expand_followers && (!empty($obj['deny_cid']) || !empty($obj['deny_gid']))) {
2669 $expand_followers = true;
2672 $allow_people = $aclFormatter->expand($obj['allow_cid']);
2673 $allow_circles = Circle::expand($obj['uid'], $aclFormatter->expand($obj['allow_gid']), $check_dead, $expand_followers);
2674 $deny_people = $aclFormatter->expand($obj['deny_cid']);
2675 $deny_circles = Circle::expand($obj['uid'], $aclFormatter->expand($obj['deny_gid']), $check_dead);
2676 $recipients = array_unique(array_merge($allow_people, $allow_circles));
2677 $deny = array_unique(array_merge($deny_people, $deny_circles));
2678 $recipients = array_diff($recipients, $deny);
2682 public static function expire(int $uid, int $days, string $network = "", bool $force = false)
2684 if (!$uid || ($days < 1)) {
2689 "`uid` = ? AND NOT `deleted` AND `gravity` = ?",
2690 $uid, self::GRAVITY_PARENT
2694 * $expire_network_only = save your own wall posts
2695 * and just expire conversations started by others
2697 $expire_network_only = DI::pConfig()->get($uid, 'expire', 'network_only', false);
2699 if ($expire_network_only) {
2700 $condition[0] .= " AND NOT `wall`";
2703 if ($network != "") {
2704 $condition[0] .= " AND `network` = ?";
2705 $condition[] = $network;
2708 $condition[0] .= " AND `received` < ?";
2709 $condition[] = DateTimeFormat::utc('now - ' . $days . ' day');
2711 $items = Post::select(['resource-id', 'starred', 'id', 'post-type', 'uid', 'uri-id'], $condition);
2713 if (!DBA::isResult($items)) {
2717 $expire_items = (bool)DI::pConfig()->get($uid, 'expire', 'items', true);
2719 // Forcing expiring of items - but not notes and marked items
2721 $expire_items = true;
2724 $expire_notes = (bool)DI::pConfig()->get($uid, 'expire', 'notes', true);
2725 $expire_starred = (bool)DI::pConfig()->get($uid, 'expire', 'starred', true);
2726 $expire_photos = (bool)DI::pConfig()->get($uid, 'expire', 'photos', false);
2730 $priority = DI::config()->get('system', 'expire-notify-priority');
2732 while ($item = Post::fetch($items)) {
2733 // don't expire filed items
2734 if (DBA::exists('post-category', ['uri-id' => $item['uri-id'], 'uid' => $item['uid'], 'type' => Post\Category::FILE])) {
2738 // Only expire posts, not photos and photo comments
2740 if (!$expire_photos && !empty($item['resource-id'])) {
2742 } elseif (!$expire_starred && intval($item['starred'])) {
2744 } elseif (!$expire_notes && ($item['post-type'] == self::PT_PERSONAL_NOTE)) {
2746 } elseif (!$expire_items && ($item['post-type'] != self::PT_PERSONAL_NOTE)) {
2750 self::markForDeletionById($item['id'], $priority);
2755 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]);
2758 public static function firstPostDate(int $uid, bool $wall = false)
2760 $user = User::getById($uid, ['register_date']);
2766 "`uid` = ? AND `wall` = ? AND NOT `deleted` AND `visible` AND `received` >= ?",
2767 $uid, $wall, $user['register_date']
2769 $params = ['order' => ['received' => false]];
2770 $thread = Post::selectFirstThread(['received'], $condition, $params);
2771 if (DBA::isResult($thread)) {
2772 $postdate = substr(DateTimeFormat::local($thread['received']), 0, 10);
2779 * add/remove activity to an item
2781 * Toggle activities as like,dislike,attend of an item
2783 * @param int $item_id
2784 * @param string $verb
2785 * Activity verb. One of
2786 * like, unlike, dislike, undislike, attendyes, unattendyes,
2787 * attendno, unattendno, attendmaybe, unattendmaybe,
2788 * announce, unannounce
2790 * @param string $allow_cid
2791 * @param string $allow_gid
2792 * @param string $deny_cid
2793 * @param string $deny_gid
2795 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2796 * @throws \ImagickException
2797 * @hook 'post_local_end'
2799 * 'post_id' => ID of posted item
2801 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
2807 Logger::notice('Start create activity', ['verb' => $verb, 'item' => $item_id, 'user' => $uid]);
2809 $item = Post::selectFirst(self::ITEM_FIELDLIST, ['id' => $item_id]);
2810 if (!DBA::isResult($item)) {
2811 Logger::warning('Post had not been fetched', ['id' => $item_id]);
2815 $uri_id = $item['uri-id'];
2817 if (!in_array($item['uid'], [0, $uid])) {
2821 if (!Post::exists(['uri-id' => $item['parent-uri-id'], 'uid' => $uid])) {
2822 $stored = self::storeForUserByUriId($item['parent-uri-id'], $uid, ['post-reason' => Item::PR_ACTIVITY]);
2823 if (($item['parent-uri-id'] == $item['uri-id']) && !empty($stored)) {
2824 $item = Post::selectFirst(self::ITEM_FIELDLIST, ['id' => $stored]);
2825 if (!DBA::isResult($item)) {
2826 Logger::info('Could not fetch just created item - should not happen', ['stored' => $stored, 'uid' => $uid, 'uri-id' => $uri_id]);
2832 // Retrieves the local post owner
2833 $owner = User::getOwnerDataById($uid);
2834 if (empty($owner)) {
2835 Logger::info('Empty owner for user', ['uid' => $uid]);
2839 // Retrieve the current logged in user's public contact
2840 $author_id = Contact::getPublicIdByUserId($uid);
2841 if (empty($author_id)) {
2842 Logger::info('Empty public contact');
2850 $activity = Activity::LIKE;
2854 $activity = Activity::DISLIKE;
2858 $activity = Activity::ATTEND;
2862 $activity = Activity::ATTENDNO;
2865 case 'unattendmaybe':
2866 $activity = Activity::ATTENDMAYBE;
2870 $activity = Activity::FOLLOW;
2874 $activity = Activity::ANNOUNCE;
2877 Logger::warning('unknown verb', ['verb' => $verb, 'item' => $item_id]);
2881 $mode = Strings::startsWith($verb, 'un') ? 'delete' : 'create';
2883 // Enable activity toggling instead of on/off
2884 $event_verb_flag = $activity === Activity::ATTEND || $activity === Activity::ATTENDNO || $activity === Activity::ATTENDMAYBE;
2886 // Look for an existing verb row
2887 // Event participation activities are mutually exclusive, only one of them can exist at all times.
2888 if ($event_verb_flag) {
2889 $verbs = [Activity::ATTEND, Activity::ATTENDNO, Activity::ATTENDMAYBE];
2891 // Translate to the index based activity index
2893 foreach ($verbs as $verb) {
2894 $vids[] = Verb::getID($verb);
2897 $vids = Verb::getID($activity);
2901 'vid' => $vids, 'deleted' => false, 'gravity' => self::GRAVITY_ACTIVITY,
2902 'author-id' => $author_id, 'uid' => $uid, 'thr-parent-id' => $uri_id
2904 $like_item = Post::selectFirst(['id', 'guid', 'verb'], $condition);
2906 if (DBA::isResult($like_item)) {
2908 * Truth table for existing activities
2910 * | Inputs || Outputs |
2911 * |----------------------------||-------------------|
2912 * | Mode | Event | Same verb || Delete? | Return? |
2913 * |--------|-------|-----------||---------|---------|
2914 * | create | Yes | Yes || No | Yes |
2915 * | create | Yes | No || Yes | No |
2916 * | create | No | Yes || No | Yes |
2917 * | create | No | No || N/A†|
2918 * | delete | Yes | Yes || Yes | N/A‡ |
2919 * | delete | Yes | No || No | N/A‡ |
2920 * | delete | No | Yes || Yes | N/A‡ |
2921 * | delete | No | No || N/A†|
2922 * |--------|-------|-----------||---------|---------|
2923 * | A | B | C || A xor C | !B or C |
2925 * †Can't happen: It's impossible to find an existing non-event activity without
2926 * the same verb because we are only looking for this single verb.
2928 * ‡ The "mode = delete" is returning early whether an existing activity was found or not.
2930 if ($mode == 'create' xor $like_item['verb'] == $activity) {
2931 self::markForDeletionById($like_item['id']);
2934 if (!$event_verb_flag || $like_item['verb'] == $activity) {
2939 // No need to go further if we aren't creating anything
2940 if ($mode == 'delete') {
2944 $objtype = $item['resource-id'] ? Activity\ObjectType::IMAGE : Activity\ObjectType::NOTE;
2947 'guid' => System::createUUID(),
2948 'uri' => self::newURI(),
2950 'contact-id' => $owner['id'],
2951 'wall' => $item['wall'],
2953 'network' => Protocol::DFRN,
2954 'protocol' => Conversation::PARCEL_DIRECT,
2955 'direction' => Conversation::PUSH,
2956 'gravity' => self::GRAVITY_ACTIVITY,
2957 'parent' => $item['id'],
2958 'thr-parent' => $item['uri'],
2959 'owner-id' => $author_id,
2960 'author-id' => $author_id,
2961 'body' => $activity,
2962 'verb' => $activity,
2963 'object-type' => $objtype,
2964 'allow_cid' => $allow_cid ?? $item['allow_cid'],
2965 'allow_gid' => $allow_gid ?? $item['allow_gid'],
2966 'deny_cid' => $deny_cid ?? $item['deny_cid'],
2967 'deny_gid' => $deny_gid ?? $item['deny_gid'],
2972 if (in_array($activity, [Activity::LIKE, Activity::DISLIKE])) {
2973 $signed = Diaspora::createLikeSignature($uid, $new_item);
2974 if (!empty($signed)) {
2975 $new_item['diaspora_signed_text'] = json_encode($signed);
2979 self::insert($new_item, true);
2981 // If the parent item isn't visible then set it to visible
2982 // @todo Check if this is still needed
2983 if (!$item['visible']) {
2984 self::update(['visible' => true], ['id' => $item['id']]);
2990 * Fetch the SQL condition for the given user id
2992 * @param integer $owner_id User ID for which the permissions should be fetched
2993 * @return array condition
2995 public static function getPermissionsConditionArrayByUserId(int $owner_id): array
2997 $local_user = DI::userSession()->getLocalUserId();
2998 $remote_user = DI::userSession()->getRemoteContactID($owner_id);
3000 // default permissions - anonymous user
3001 $condition = ["`private` != ?", self::PRIVATE];
3003 if ($local_user && ($local_user == $owner_id)) {
3004 // Profile owner - everything is visible
3006 } elseif ($remote_user) {
3007 // Authenticated visitor - fetch the matching permissionsets
3008 $permissionSets = DI::permissionSet()->selectByContactId($remote_user, $owner_id);
3011 "(`private` != ? OR (`private` = ? AND `wall`
3012 AND `psid` IN (" . implode(', ', array_fill(0, count($set), '?')) . ")))",
3013 self::PRIVATE, self::PRIVATE
3015 $condition = array_merge($condition, $permissionSets->column('id'));
3023 * Get a permission SQL string for the given user
3025 * @param int $owner_id
3026 * @param string $table
3029 public static function getPermissionsSQLByUserId(int $owner_id, string $table = ''): string
3031 $local_user = DI::userSession()->getLocalUserId();
3032 $remote_user = DI::userSession()->getRemoteContactID($owner_id);
3034 if (!empty($table)) {
3035 $table = DBA::quoteIdentifier($table) . '.';
3039 * Construct permissions
3041 * default permissions - anonymous user
3043 $sql = sprintf(" AND " . $table . "`private` != %d", self::PRIVATE);
3045 // Profile owner - everything is visible
3046 if ($local_user && ($local_user == $owner_id)) {
3048 } elseif ($remote_user) {
3050 * Authenticated visitor. Unless pre-verified,
3051 * check that the contact belongs to this $owner_id
3052 * and load the circles the visitor belongs to.
3053 * If pre-verified, the caller is expected to have already
3054 * done this and passed the circles into this function.
3056 $permissionSets = DI::permissionSet()->selectByContactId($remote_user, $owner_id);
3059 $sql_set = sprintf(" OR (" . $table . "`private` = %d AND " . $table . "`wall` AND " . $table . "`psid` IN (", self::PRIVATE) . implode(',', $permissionSets->column('id')) . "))";
3064 $sql = sprintf(" AND (" . $table . "`private` != %d", self::PRIVATE) . $sql_set . ")";
3071 * get translated item type
3073 * @param array $item
3074 * @param \Friendica\Core\L10n $l10n
3077 public static function postType(array $item, \Friendica\Core\L10n $l10n): string
3079 if (!empty($item['event-id'])) {
3080 return $l10n->t('event');
3081 } elseif (!empty($item['resource-id'])) {
3082 return $l10n->t('photo');
3083 } elseif ($item['gravity'] == self::GRAVITY_ACTIVITY) {
3084 return $l10n->t('activity');
3085 } elseif ($item['gravity'] == self::GRAVITY_COMMENT) {
3086 return $l10n->t('comment');
3089 return $l10n->t('post');
3093 * Sets the "rendered-html" field of the provided item
3095 * Body is preserved to avoid side-effects as we modify it just-in-time for spoilers and private image links
3097 * @param array $item
3099 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3100 * @todo Remove reference, simply return "rendered-html" and "rendered-hash"
3102 private static function putInCache(&$item)
3104 // Save original body to prevent addons to modify it
3105 $body = $item['body'];
3107 $rendered_hash = $item['rendered-hash'] ?? '';
3108 $rendered_html = $item['rendered-html'] ?? '';
3111 $rendered_hash == ''
3112 || $rendered_html == ''
3113 || $rendered_hash != hash('md5', BBCode::VERSION . '::' . $body)
3114 || DI::config()->get('system', 'ignore_cache')
3116 $item['rendered-html'] = BBCode::convertForUriId($item['uri-id'], $item['body']);
3117 $item['rendered-hash'] = hash('md5', BBCode::VERSION . '::' . $body);
3119 $hook_data = ['item' => $item, 'rendered-html' => $item['rendered-html'], 'rendered-hash' => $item['rendered-hash']];
3120 Hook::callAll('put_item_in_cache', $hook_data);
3121 $item['rendered-html'] = $hook_data['rendered-html'];
3122 $item['rendered-hash'] = $hook_data['rendered-hash'];
3125 // Update if the generated values differ from the existing ones
3126 if ((($rendered_hash != $item['rendered-hash']) || ($rendered_html != $item['rendered-html'])) && !empty($item['id'])) {
3129 'rendered-html' => $item['rendered-html'],
3130 'rendered-hash' => $item['rendered-hash']
3132 ['id' => $item['id']]
3137 $item['body'] = $body;
3141 * Given an item array, convert the body element from bbcode to html and add smilie icons.
3142 * If attach is true, also add icons for item attachments.
3144 * @param array $item Record from item table
3145 * @param boolean $attach If true, add icons for item attachments as well
3146 * @param boolean $is_preview Whether this is a preview
3147 * @param boolean $only_cache Whether only cached HTML should be updated
3148 * @return string item body html
3149 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3150 * @throws \ImagickException
3151 * @hook prepare_body_init item array before any work
3152 * @hook prepare_body_content_filter ('item'=>item array, 'filter_reasons'=>string array) before first bbcode to html
3153 * @hook prepare_body ('item'=>item array, 'html'=>body string, 'is_preview'=>boolean, 'filter_reasons'=>string array) after first bbcode to html
3154 * @hook prepare_body_final ('item'=>item array, 'html'=>body string) after attach icons and blockquote special case handling (spoiler, author)
3156 public static function prepareBody(array &$item, bool $attach = false, bool $is_preview = false, bool $only_cache = false): string
3159 Hook::callAll('prepare_body_init', $item);
3162 // In order to provide theme developers more possibilities, event items
3163 // are treated differently.
3164 if ($item['object-type'] === Activity\ObjectType::EVENT && isset($item['event-id'])) {
3165 $ev = Event::getItemHTML($item);
3169 $tags = Tag::populateFromItem($item);
3171 $item['tags'] = $tags['tags'];
3172 $item['hashtags'] = $tags['hashtags'];
3173 $item['mentions'] = $tags['mentions'];
3176 $item['body'] = preg_replace("#\s*\[attachment .*?].*?\[/attachment]\s*#ism", "\n", $item['body']);
3177 $item['body'] = Post\Media::removeFromEndOfBody($item['body'] ?? '');
3178 $item['body'] = Post\Media::replaceImage($item['body']);
3181 $body = $item['body'];
3183 $item['body'] = preg_replace("#\s*\[attachment .*?].*?\[/attachment]\s*#ism", "\n", $item['body']);
3186 $fields = ['uri-id', 'uri', 'body', 'title', 'author-name', 'author-link', 'author-avatar', 'guid', 'created', 'plink', 'network', 'has-media', 'quote-uri-id', 'post-type'];
3190 $quote_shared_links = [];
3192 $shared = DI::contentItem()->getSharedPost($item, $fields);
3193 if (!empty($shared['post'])) {
3194 $shared_item = $shared['post'];
3195 $shared_item['body'] = Post\Media::removeFromEndOfBody($shared_item['body']);
3196 $shared_item['body'] = Post\Media::replaceImage($shared_item['body']);
3197 $quote_uri_id = $shared['post']['uri-id'];
3198 $shared_links[] = strtolower($shared['post']['uri']);
3199 $item['body'] = BBCode::removeSharedData($item['body']);
3200 } elseif (empty($shared_item['uri-id']) && empty($item['quote-uri-id']) && ($item['network'] != Protocol::DIASPORA)) {
3201 $media = Post\Media::getByURIId($item['uri-id'], [Post\Media::ACTIVITY]);
3202 if (!empty($media) && ($media[0]['media-uri-id'] != $item['uri-id'])) {
3203 $shared_item = Post::selectFirst($fields, ['uri-id' => $media[0]['media-uri-id'], 'uid' => [$item['uid'], 0]]);
3204 if (empty($shared_item['uri-id'])) {
3205 $shared_item = Post::selectFirst($fields, ['plink' => $media[0]['url'], 'uid' => [$item['uid'], 0]]);
3206 } elseif (!in_array(strtolower($media[0]['url']), $shared_links)) {
3207 $shared_links[] = strtolower($media[0]['url']);
3210 if (empty($shared_item['uri-id'])) {
3211 $shared_item = Post::selectFirst($fields, ['uri' => $media[0]['url'], 'uid' => [$item['uid'], 0]]);
3212 $shared_links[] = strtolower($media[0]['url']);
3215 if (!empty($shared_item['uri-id'])) {
3216 $data = BBCode::getAttachmentData($shared_item['body']);
3217 if (!empty($data['url'])) {
3218 $quote_shared_links[] = $data['url'];
3221 $quote_uri_id = $shared_item['uri-id'];
3226 if (!empty($quote_uri_id)) {
3227 if (isset($shared_item['plink'])) {
3228 $item['body'] .= "\n" . DI::contentItem()->createSharedBlockByArray($shared_item, false, true);
3230 DI::logger()->warning('Missing plink in shared item', ['item' => $item, 'shared' => $shared, 'quote_uri_id' => $quote_uri_id, 'shared_item' => $shared_item]);
3234 if (!empty($shared_item['uri-id'])) {
3235 $shared_uri_id = $shared_item['uri-id'];
3236 $shared_links[] = strtolower($shared_item['plink']);
3237 $sharedSplitAttachments = DI::postMediaRepository()->splitAttachments($shared_uri_id, [], $shared_item['has-media']);
3238 $shared_links = array_merge($shared_links, $sharedSplitAttachments['visual']->column('url'));
3239 $shared_links = array_merge($shared_links, $sharedSplitAttachments['link']->column('url'));
3240 $shared_links = array_merge($shared_links, $sharedSplitAttachments['additional']->column('url'));
3241 $item['body'] = self::replaceVisualAttachments($sharedSplitAttachments['visual'], $item['body']);
3244 $itemSplitAttachments = DI::postMediaRepository()->splitAttachments($item['uri-id'], $shared_links, $item['has-media'] ?? false);
3245 $item['body'] = self::replaceVisualAttachments($itemSplitAttachments['visual'], $item['body'] ?? '');
3247 self::putInCache($item);
3248 $item['body'] = $body;
3249 $s = $item["rendered-html"];
3255 // Compile eventual content filter reasons
3256 $filter_reasons = [];
3257 if (!$is_preview && DI::userSession()->getPublicContactId() != $item['author-id']) {
3258 if (!empty($item['user-blocked-author']) || !empty($item['user-blocked-owner'])) {
3259 $filter_reasons[] = DI::l10n()->t('%s is blocked', $item['author-name']);
3260 } elseif (!empty($item['user-ignored-author']) || !empty($item['user-ignored-owner'])) {
3261 $filter_reasons[] = DI::l10n()->t('%s is ignored', $item['author-name']);
3262 } elseif (!empty($item['user-collapsed-author']) || !empty($item['user-collapsed-owner'])) {
3263 $filter_reasons[] = DI::l10n()->t('Content from %s is collapsed', $item['author-name']);
3266 if (!empty($item['content-warning']) && (!DI::userSession()->getLocalUserId() || !DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'system', 'disable_cw', false))) {
3267 $filter_reasons[] = DI::l10n()->t('Content warning: %s', $item['content-warning']);
3270 $item['attachments'] = $itemSplitAttachments;
3274 'filter_reasons' => $filter_reasons
3276 Hook::callAll('prepare_body_content_filter', $hook_data);
3277 $filter_reasons = $hook_data['filter_reasons'];
3284 'preview' => $is_preview,
3285 'filter_reasons' => $filter_reasons
3287 Hook::callAll('prepare_body', $hook_data);
3288 $s = $hook_data['html'];
3293 // Replace the blockquotes with quotes that are used in mails.
3294 $mailquote = '<blockquote type="cite" class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex;">';
3295 $s = str_replace(['<blockquote>', '<blockquote class="spoiler">', '<blockquote class="author">'], [$mailquote, $mailquote, $mailquote], $s);
3299 if (!empty($sharedSplitAttachments)) {
3300 $s = self::addGallery($s, $sharedSplitAttachments['visual']);
3301 $s = self::addVisualAttachments($sharedSplitAttachments['visual'], $shared_item, $s, true);
3302 $s = self::addLinkAttachment($shared_uri_id ?: $item['uri-id'], $sharedSplitAttachments, $body, $s, true, $quote_shared_links);
3303 $s = self::addNonVisualAttachments($sharedSplitAttachments['additional'], $item, $s, true);
3304 $body = BBCode::removeSharedData($body);
3307 $pos = strpos($s, BBCode::SHARED_ANCHOR);
3309 $shared_html = substr($s, $pos + strlen(BBCode::SHARED_ANCHOR));
3310 $s = substr($s, 0, $pos);
3313 $s = self::addGallery($s, $itemSplitAttachments['visual']);
3314 $s = self::addVisualAttachments($itemSplitAttachments['visual'], $item, $s, false);
3315 $s = self::addLinkAttachment($item['uri-id'], $itemSplitAttachments, $body, $s, false, $shared_links);
3316 $s = self::addNonVisualAttachments($itemSplitAttachments['additional'], $item, $s, false);
3317 $s = self::addQuestions($item, $s);
3320 if (strpos($s, '<div class="map">') !== false && !empty($item['coord'])) {
3321 $x = Map::byCoordinates(trim($item['coord']));
3323 $s = preg_replace('/\<div class\=\"map\"\>/', '$0' . $x, $s);
3327 // Replace friendica image url size with theme preference.
3328 if (!empty($a->getThemeInfoValue('item_image_size'))) {
3329 $ps = $a->getThemeInfoValue('item_image_size');
3330 $s = preg_replace('|(<img[^>]+src="[^"]+/photo/[0-9a-f]+)-[0-9]|', "$1-" . $ps, $s);
3333 if (!empty($shared_html)) {
3337 $s = HTML::applyContentFilter($s, $filter_reasons);
3339 $hook_data = ['item' => $item, 'html' => $s];
3340 Hook::callAll('prepare_body_final', $hook_data);
3341 return $hook_data['html'];
3345 * Modify links to pictures to links for the "Fancybox" gallery
3348 * @param PostMedias $PostMedias
3351 private static function addGallery(string $s, PostMedias $PostMedias): string
3353 foreach ($PostMedias as $PostMedia) {
3354 if (!$PostMedia->preview || ($PostMedia->type !== Post\Media::IMAGE)) {
3358 if ($PostMedia->hasDimensions()) {
3359 $pattern = '#<a href="' . preg_quote($PostMedia->url) . '">(.*?)"></a>#';
3361 $s = preg_replace_callback($pattern, function () use ($PostMedia) {
3362 return Renderer::replaceMacros(Renderer::getMarkupTemplate('content/image/single_with_height_allocation.tpl'), [
3363 '$image' => $PostMedia,
3364 '$allocated_height' => $PostMedia->getAllocatedHeight(),
3365 '$allocated_max_width' => ($PostMedia->previewWidth ?? $PostMedia->width) . 'px',
3369 $s = str_replace('<a href="' . $PostMedia->url . '"', '<a data-fancybox="uri-id-' . $PostMedia->uriId . '" href="' . $PostMedia->url . '"', $s);
3377 * Check if the body contains a link
3379 * @param string $body
3380 * @param string $url
3384 public static function containsLink(string $body, string $url, int $type = 0): bool
3386 // Make sure that for example site parameters aren't used when testing if the link is contained in the body
3387 $urlparts = parse_url($url);
3388 if (empty($urlparts)) {
3392 unset($urlparts['query']);
3393 unset($urlparts['fragment']);
3396 $url = (string)Uri::fromParts($urlparts);
3397 } catch (\InvalidArgumentException $e) {
3398 DI::logger()->notice('Invalid URL', ['$url' => $url, '$urlparts' => $urlparts]);
3399 /* See https://github.com/friendica/friendica/issues/12113
3400 * Malformed URLs will result in a Fatal Error
3405 // Remove media links to only search in embedded content
3406 // @todo Check images for image link, audio for audio links, ...
3407 if (in_array($type, [Post\Media::AUDIO, Post\Media::VIDEO, Post\Media::IMAGE])) {
3408 $body = preg_replace("/\[url=[^\[\]]*\](.*)\[\/url\]/Usi", ' $1 ', $body);
3411 if (strpos($body, $url)) {
3415 foreach ([0, 1, 2] as $size) {
3417 preg_match('#/photo/.*-' . $size . '\.#ism', $url) &&
3418 strpos(preg_replace('#(/photo/.*)-[012]\.#ism', '$1-' . $size . '.', $body), $url)
3428 * Replace visual attachments in the body
3430 * @param PostMedias $PostMedias
3431 * @param string $body
3432 * @return string modified body
3434 private static function replaceVisualAttachments(PostMedias $PostMedias, string $body): string
3436 DI::profiler()->startRecording('rendering');
3438 foreach ($PostMedias as $PostMedia) {
3439 if ($PostMedia->preview) {
3440 if (DI::baseUrl()->isLocalUri($PostMedia->preview)) {
3443 $proxy = DI::baseUrl() . $PostMedia->getPreviewPath(Proxy::SIZE_LARGE);
3444 $search = ['[img=' . $PostMedia->preview . ']', ']' . $PostMedia->preview . '[/img]'];
3445 $replace = ['[img=' . $proxy . ']', ']' . $proxy . '[/img]'];
3447 $body = str_replace($search, $replace, $body);
3448 } elseif ($PostMedia->mimetype->type == 'image') {
3449 if (DI::baseUrl()->isLocalUri($PostMedia->url)) {
3452 $proxy = DI::baseUrl() . $PostMedia->getPreviewPath(Proxy::SIZE_LARGE);
3453 $search = ['[img=' . $PostMedia->url . ']', ']' . $PostMedia->url . '[/img]'];
3454 $replace = ['[img=' . $proxy . ']', ']' . $proxy . '[/img]'];
3456 $body = str_replace($search, $replace, $body);
3459 DI::profiler()->stopRecording();
3464 * Add visual attachments to the content
3466 * @param PostMedias $PostMedias
3467 * @param array $item
3468 * @param string $content
3469 * @param bool $shared
3470 * @return string modified content
3471 * @throws ServiceUnavailableException
3473 private static function addVisualAttachments(PostMedias $PostMedias, array $item, string $content, bool $shared): string
3475 DI::profiler()->startRecording('rendering');
3478 $images = new PostMedias();
3480 // @todo In the future we should make a single for the template engine with all media in it. This allows more flexibilty.
3481 foreach ($PostMedias as $PostMedia) {
3482 if (self::containsLink($item['body'], $PostMedia->preview ?? $PostMedia->url, $PostMedia->type)) {
3486 if ($PostMedia->mimetype->type == 'image') {
3487 $preview_size = $PostMedia->width > $PostMedia->height ? Proxy::SIZE_MEDIUM : Proxy::SIZE_LARGE;
3488 $preview_url = DI::baseUrl() . $PostMedia->getPreviewPath($preview_size);
3489 } elseif ($PostMedia->preview) {
3490 $preview_size = Proxy::SIZE_LARGE;
3491 $preview_url = DI::baseUrl() . $PostMedia->getPreviewPath($preview_size);
3497 if ($preview_url && self::containsLink($item['body'], $preview_url)) {
3501 if ($PostMedia->mimetype->type == 'video') {
3502 /// @todo Move the template to /content as well
3503 $media = Renderer::replaceMacros(Renderer::getMarkupTemplate('video_top.tpl'), [
3505 'id' => $PostMedia->id,
3506 'src' => (string)$PostMedia->url,
3507 'name' => $PostMedia->name ?: $PostMedia->url,
3508 'preview' => $preview_url,
3509 'mime' => (string)$PostMedia->mimetype,
3512 if (($item['post-type'] ?? null) == Item::PT_VIDEO) {
3515 $trailing .= $media;
3517 } elseif ($PostMedia->mimetype->type == 'audio') {
3518 $media = Renderer::replaceMacros(Renderer::getMarkupTemplate('content/audio.tpl'), [
3520 'id' => $PostMedia->id,
3521 'src' => (string)$PostMedia->url,
3522 'name' => $PostMedia->name ?: $PostMedia->url,
3523 'mime' => (string)$PostMedia->mimetype,
3526 if (($item['post-type'] ?? null) == Item::PT_AUDIO) {
3529 $trailing .= $media;
3531 } elseif ($PostMedia->mimetype->type == 'image') {
3532 $src_url = DI::baseUrl() . $PostMedia->getPhotoPath();
3533 if (self::containsLink($item['body'], $src_url)) {
3537 $images[] = $PostMedia->withUrl(new Uri($src_url))->withPreview(new Uri($preview_url), $preview_size);
3541 $media = Image::getBodyAttachHtml($images);
3543 // On Diaspora posts the attached pictures are leading
3544 if ($item['network'] == Protocol::DIASPORA) {
3547 $trailing .= $media;
3551 $content = str_replace(BBCode::TOP_ANCHOR, '<div class="body-attach">' . $leading . '</div>' . BBCode::TOP_ANCHOR, $content);
3552 $content = str_replace(BBCode::BOTTOM_ANCHOR, '<div class="body-attach">' . $trailing . '</div>' . BBCode::BOTTOM_ANCHOR, $content);
3554 if ($leading != '') {
3555 $content = '<div class="body-attach">' . $leading . '</div>' . $content;
3558 if ($trailing != '') {
3559 $content .= '<div class="body-attach">' . $trailing . '</div>';
3563 DI::profiler()->stopRecording();
3568 * Add link attachment to the content
3571 * @param PostMedias[] $attachments
3572 * @param string $body
3573 * @param string $content
3574 * @param bool $shared
3575 * @param array $ignore_links A list of URLs to ignore
3576 * @return string modified content
3577 * @throws InternalServerErrorException
3578 * @throws ServiceUnavailableException
3580 private static function addLinkAttachment(int $uriid, array $attachments, string $body, string $content, bool $shared, array $ignore_links): string
3582 DI::profiler()->startRecording('rendering');
3583 // Don't show a preview when there is a visual attachment (audio or video)
3584 $types = $attachments['visual']->column('type');
3585 $preview = !in_array(PostMedia::TYPE_IMAGE, $types) && !in_array(PostMedia::TYPE_VIDEO, $types);
3587 /** @var ?PostMedia $attachment */
3589 foreach ($attachments['link'] as $PostMedia) {
3591 foreach ($ignore_links as $ignore_link) {
3592 if (Strings::compareLink($PostMedia->url, $ignore_link)) {
3596 // @todo Judge between the links to use the one with most information
3597 if (!$found && (empty($attachment) || $PostMedia->authorName ||
3598 (!$attachment->name && $PostMedia->name) ||
3599 (!$attachment->description && $PostMedia->description) ||
3600 (!$attachment->preview && $PostMedia->preview))) {
3601 $attachment = $PostMedia;
3605 if (!empty($attachment)) {
3608 'author_name' => $attachment->authorName ?? '',
3609 'author_url' => (string)($attachment->authorUrl ?? ''),
3610 'description' => $attachment->description ?? '',
3613 'provider_name' => $attachment->publisherName ?? '',
3614 'provider_url' => (string)($attachment->publisherUrl ?? ''),
3616 'title' => $attachment->name ?? '',
3618 'url' => (string)$attachment->url,
3621 if ($preview && $attachment->preview) {
3622 if ($attachment->previewWidth >= 500) {
3623 $data['image'] = DI::baseUrl() . $attachment->getPreviewPath(Proxy::SIZE_MEDIUM);
3625 $data['preview'] = DI::baseUrl() . $attachment->getPreviewPath(Proxy::SIZE_MEDIUM);
3629 if (!empty($data['description']) && !empty($content)) {
3630 similar_text($data['description'], $content, $percent);
3635 if (!empty($data['description']) && (($data['title'] == $data['description']) || ($percent > 95) || (strpos($content, $data['description']) !== false))) {
3636 $data['description'] = '';
3639 if (($data['author_name'] ?? '') == ($data['provider_name'] ?? '')) {
3640 $data['author_name'] = '';
3643 if (($data['author_url'] ?? '') == ($data['provider_url'] ?? '')) {
3644 $data['author_url'] = '';
3646 } elseif (preg_match("/.*(\[attachment.*?\].*?\[\/attachment\]).*/ism", $body, $match)) {
3647 $data = BBCode::getAttachmentData($match[1]);
3649 DI::profiler()->stopRecording();
3651 if (isset($data['url']) && !in_array(strtolower($data['url']), $ignore_links)) {
3652 if (!empty($data['description']) || !empty($data['image']) || !empty($data['preview']) || (!empty($data['title']) && !Strings::compareLink($data['title'], $data['url']))) {
3653 $parts = parse_url($data['url']);
3654 if (!empty($parts['scheme']) && !empty($parts['host'])) {
3655 if (empty($data['provider_name'])) {
3656 $data['provider_name'] = $parts['host'];
3658 if (empty($data['provider_url']) || empty(parse_url($data['provider_url'], PHP_URL_SCHEME))) {
3659 $data['provider_url'] = $parts['scheme'] . '://' . $parts['host'];
3661 if (!empty($parts['port'])) {
3662 $data['provider_url'] .= ':' . $parts['port'];
3667 // @todo Use a template
3668 $preview_mode = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'system', 'preview_mode', BBCode::PREVIEW_LARGE);
3669 if ($preview_mode != BBCode::PREVIEW_NONE) {
3670 $rendered = BBCode::convertAttachment('', BBCode::INTERNAL, false, $data, $uriid, $preview_mode);
3674 } elseif (!self::containsLink($content, $data['url'], Post\Media::HTML)) {
3675 $rendered = Renderer::replaceMacros(Renderer::getMarkupTemplate('content/link.tpl'), [
3676 '$url' => $data['url'],
3677 '$title' => $data['title'],
3684 return str_replace(BBCode::BOTTOM_ANCHOR, BBCode::BOTTOM_ANCHOR . $rendered, $content);
3686 return $content . $rendered;
3693 * Add non-visual attachments to the content
3695 * @param PostMedias $PostMedias
3696 * @param array $item
3697 * @param string $content
3698 * @return string modified content
3699 * @throws InternalServerErrorException
3700 * @throws \ImagickException
3702 private static function addNonVisualAttachments(PostMedias $PostMedias, array $item, string $content): string
3704 DI::profiler()->startRecording('rendering');
3706 foreach ($PostMedias as $PostMedia) {
3707 if (strpos($item['body'], $PostMedia->url)) {
3713 'id' => $item['author-id'],
3714 'network' => $item['author-network'],
3715 'url' => $item['author-link'],
3716 'alias' => $item['author-alias']
3718 $the_url = Contact::magicLinkByContact($author, $PostMedia->url);
3720 $title = Strings::escapeHtml(trim($PostMedia->description ?? '' ?: $PostMedia->url));
3722 if ($PostMedia->size) {
3723 $title .= ' ' . $PostMedia->size . ' ' . DI::l10n()->t('bytes');
3726 /// @todo Use a template
3727 $icon = '<div class="attachtype icon s22 type-' . $PostMedia->mimetype->type . ' subtype-' . $PostMedia->mimetype->subtype . '"></div>';
3728 $trailing .= '<a href="' . strip_tags($the_url) . '" title="' . $title . '" class="attachlink" target="_blank" rel="noopener noreferrer" >' . $icon . '</a>';
3731 if ($trailing != '') {
3732 $content .= '<div class="body-attach">' . $trailing . '</div>';
3735 DI::profiler()->stopRecording();
3739 private static function addQuestions(array $item, string $content): string
3741 DI::profiler()->startRecording('rendering');
3742 if (!empty($item['question-id'])) {
3744 'id' => $item['question-id'],
3745 'multiple' => $item['question-multiple'],
3746 'voters' => $item['question-voters'],
3747 'endtime' => $item['question-end-time']
3750 $options = Post\QuestionOption::getByURIId($item['uri-id']);
3751 foreach ($options as $key => $option) {
3752 if ($question['voters'] > 0) {
3753 $percent = $option['replies'] / $question['voters'] * 100;
3754 $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));
3756 $options[$key]['vote'] = DI::l10n()->tt('%2$s (%1$d vote)', '%2$s (%1$d votes)', $option['replies'], $option['name']);
3760 if (!empty($question['voters']) && !empty($question['endtime'])) {
3761 $summary = DI::l10n()->tt('%d voter. Poll end: %s', '%d voters. Poll end: %s', $question['voters'], Temporal::getRelativeDate($question['endtime']));
3762 } elseif (!empty($question['voters'])) {
3763 $summary = DI::l10n()->tt('%d voter.', '%d voters.', $question['voters']);
3764 } elseif (!empty($question['endtime'])) {
3765 $summary = DI::l10n()->t('Poll end: %s', Temporal::getRelativeDate($question['endtime']));
3770 $content .= Renderer::replaceMacros(Renderer::getMarkupTemplate('content/question.tpl'), [
3771 '$question' => $question,
3772 '$options' => $options,
3773 '$summary' => $summary,
3776 DI::profiler()->stopRecording();
3781 * get private link for item
3783 * @param array $item
3784 * @return boolean|array False if item has not plink, otherwise array('href'=>plink url, 'title'=>translated title)
3785 * @throws \Exception
3787 public static function getPlink(array $item)
3789 if (!empty($item['plink']) && Network::isValidHttpUrl($item['plink'])) {
3790 $plink = $item['plink'];
3791 } elseif (!empty($item['uri']) && Network::isValidHttpUrl($item['uri']) && !Network::isLocalLink($item['uri'])) {
3792 $plink = $item['uri'];
3795 if (DI::userSession()->getLocalUserId()) {
3797 'href' => "display/" . $item['guid'],
3798 'orig' => "display/" . $item['guid'],
3799 'title' => DI::l10n()->t('View on separate page'),
3800 'orig_title' => DI::l10n()->t('View on separate page'),
3803 if (!empty($plink) && ($item['private'] == self::PRIVATE)) {
3806 'id' => $item['author-id'],
3807 'network' => $item['author-network'],
3808 'url' => $item['author-link'],
3809 'alias' => $item['author-alias'],
3811 $plink = Contact::magicLinkByContact($author, $plink);
3814 if (!empty($plink)) {
3815 $ret['href'] = DI::baseUrl()->remove($plink);
3816 $ret['title'] = DI::l10n()->t('Link to source');
3818 } elseif (!empty($plink) && ($item['private'] != self::PRIVATE)) {
3822 'title' => DI::l10n()->t('Link to source'),
3823 'orig_title' => DI::l10n()->t('Link to source'),
3833 * Does the given uri-id belongs to a post that is sent as starting post to a group?
3834 * This does apply to posts that are sent via ! and not in parallel to a group via @
3836 * @param int $uri_id
3838 * @return boolean "true" when it is a group post
3840 public static function isGroupPost(int $uri_id): bool
3842 if (Post::exists(['private' => Item::PUBLIC, 'uri-id' => $uri_id])) {
3846 foreach (Tag::getByURIId($uri_id, [Tag::EXCLUSIVE_MENTION, Tag::AUDIENCE]) as $tag) {
3847 // @todo Possibly check for a public audience in the future, see https://socialhub.activitypub.rocks/t/fep-1b12-group-federation/2724
3848 // and https://codeberg.org/fediverse/fep/src/branch/main/feps/fep-1b12.md
3849 if (DBA::exists('contact', ['uid' => 0, 'nurl' => Strings::normaliseLink($tag['url']), 'contact-type' => Contact::TYPE_COMMUNITY])) {
3857 * Search item id for given URI or plink
3859 * @param string $uri
3860 * @param integer $uid
3862 * @return integer item id
3864 public static function searchByLink(string $uri, int $uid = 0): int
3866 $ssl_uri = str_replace('http://', 'https://', $uri);
3867 $uris = [$uri, $ssl_uri, Strings::normaliseLink($uri)];
3869 $item = Post::selectFirst(['id'], ['uri' => $uris, 'uid' => $uid]);
3870 if (DBA::isResult($item)) {
3874 $item = Post::selectFirst(['id'], ['plink' => $uris, 'uid' => $uid]);
3875 if (DBA::isResult($item)) {
3883 * Return the URI for a link to the post
3885 * @param string $uri URI or link to post
3887 * @return string URI
3889 public static function getURIByLink(string $uri): string
3891 $ssl_uri = str_replace('http://', 'https://', $uri);
3892 $uris = [$uri, $ssl_uri, Strings::normaliseLink($uri)];
3894 $item = Post::selectFirst(['uri'], ['uri' => $uris]);
3895 if (DBA::isResult($item)) {
3896 return $item['uri'];
3899 $item = Post::selectFirst(['uri'], ['plink' => $uris]);
3900 if (DBA::isResult($item)) {
3901 return $item['uri'];
3908 * Fetches item for given URI or plink
3910 * @param string $uri
3911 * @param integer $uid
3913 * @return integer item id
3915 public static function fetchByLink(string $uri, int $uid = 0): int
3917 Logger::info('Trying to fetch link', ['uid' => $uid, 'uri' => $uri]);
3918 $item_id = self::searchByLink($uri, $uid);
3919 if (!empty($item_id)) {
3920 Logger::info('Link found', ['uid' => $uid, 'uri' => $uri, 'id' => $item_id]);
3930 Hook::callAll('item_by_link', $hookData);
3932 if (isset($hookData['item_id'])) {
3933 return is_numeric($hookData['item_id']) ? $hookData['item_id'] : 0;
3936 $fetched_uri = ActivityPub\Processor::fetchMissingActivity($uri, [], '', ActivityPub\Receiver::COMPLETION_MANUAL, $uid);
3939 $item_id = self::searchByLink($fetched_uri, $uid);
3941 $item_id = Diaspora::fetchByURL($uri);
3944 if (!empty($item_id)) {
3945 Logger::info('Link fetched', ['uid' => $uid, 'uri' => $uri, 'id' => $item_id]);
3949 Logger::info('Link not found', ['uid' => $uid, 'uri' => $uri]);
3954 * Fetch the uri-id of a quote
3956 * @param string $body
3959 public static function getQuoteUriId(string $body, int $uid = 0): int
3961 $shared = BBCode::fetchShareAttributes($body);
3962 if (empty($shared['guid']) && empty($shared['message_id'])) {
3966 if (empty($shared['link']) && empty($shared['message_id'])) {
3967 Logger::notice('Invalid share block.', ['share' => $shared]);
3971 if (!empty($shared['guid'])) {
3972 $shared_item = Post::selectFirst(['uri-id'], ['guid' => $shared['guid'], 'uid' => [0, $uid]]);
3973 if (!empty($shared_item['uri-id'])) {
3974 Logger::debug('Found post by guid', ['guid' => $shared['guid'], 'uid' => $uid]);
3975 return $shared_item['uri-id'];
3979 if (!empty($shared['message_id'])) {
3980 $shared_item = Post::selectFirst(['uri-id'], ['uri' => $shared['message_id'], 'uid' => [0, $uid]]);
3981 if (!empty($shared_item['uri-id'])) {
3982 Logger::debug('Found post by message_id', ['message_id' => $shared['message_id'], 'uid' => $uid]);
3983 return $shared_item['uri-id'];
3987 if (!empty($shared['link'])) {
3988 $shared_item = Post::selectFirst(['uri-id'], ['plink' => $shared['link'], 'uid' => [0, $uid]]);
3989 if (!empty($shared_item['uri-id'])) {
3990 Logger::debug('Found post by link', ['link' => $shared['link'], 'uid' => $uid]);
3991 return $shared_item['uri-id'];
3995 $url = $shared['message_id'] ?: $shared['link'];
3996 $id = self::fetchByLink($url);
3998 Logger::notice('Post could not be fetched.', ['url' => $url, 'uid' => $uid]);
4002 $shared_item = Post::selectFirst(['uri-id'], ['id' => $id]);
4003 if (!empty($shared_item['uri-id'])) {
4004 Logger::debug('Fetched shared post', ['id' => $id, 'url' => $url, 'uid' => $uid]);
4005 return $shared_item['uri-id'];
4008 Logger::warning('Post does not exist although it was supposed to had been fetched.', ['id' => $id, 'url' => $url, 'uid' => $uid]);