3 * @copyright Copyright (C) 2010-2022, the Friendica project
5 * @license GNU AGPL version 3 or any later version
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU Affero General Public License as
9 * published by the Free Software Foundation, either version 3 of the
10 * License, or (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU Affero General Public License for more details.
17 * You should have received a copy of the GNU Affero General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
22 namespace Friendica\Model;
24 use Friendica\Content\Text\BBCode;
25 use Friendica\Content\Text\HTML;
26 use Friendica\Core\Hook;
27 use Friendica\Core\Logger;
28 use Friendica\Core\Protocol;
29 use Friendica\Core\Renderer;
30 use Friendica\Core\Session;
31 use Friendica\Core\System;
32 use Friendica\Model\Tag;
33 use Friendica\Core\Worker;
34 use Friendica\Database\DBA;
36 use Friendica\Protocol\Activity;
37 use Friendica\Protocol\ActivityPub;
38 use Friendica\Protocol\Diaspora;
39 use Friendica\Util\DateTimeFormat;
40 use Friendica\Util\Map;
41 use Friendica\Util\Network;
42 use Friendica\Util\Proxy;
43 use Friendica\Util\Strings;
44 use Friendica\Util\Temporal;
45 use Friendica\Worker\Delivery;
46 use GuzzleHttp\Psr7\Uri;
47 use LanguageDetection\Language;
51 // Posting types, inspired by https://www.w3.org/TR/activitystreams-vocabulary/#object-types
58 const PT_DOCUMENT = 19;
61 const PT_PERSONAL_NOTE = 128;
63 // Posting reasons (Why had a post been stored for a user?)
70 const PR_FOLLOWER = 69;
71 const PR_ANNOUNCEMENT = 70;
72 const PR_COMMENT = 71;
76 const PR_FETCHED = 75;
77 const PR_COMPLETION = 76;
79 const PR_ACTIVITY = 78;
80 const PR_DISTRIBUTE = 79;
84 // system.accept_only_sharer setting values
85 const COMPLETION_NONE = 1;
86 const COMPLETION_COMMENT = 0;
87 const COMPLETION_LIKE = 2;
89 // Field list that is used to display the items
90 const DISPLAY_FIELDLIST = [
91 'uid', 'id', 'parent', 'guid', 'network', 'gravity',
92 'uri-id', 'uri', 'thr-parent-id', 'thr-parent', 'parent-uri-id', 'parent-uri', 'conversation',
93 'commented', 'created', 'edited', 'received', 'verb', 'object-type', 'postopts', 'plink',
94 'wall', 'private', 'starred', 'origin', 'parent-origin', 'title', 'body', 'language',
95 'content-warning', 'location', 'coord', 'app', 'rendered-hash', 'rendered-html', 'object',
96 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid', 'mention', 'global',
97 'author-id', 'author-link', 'author-name', 'author-avatar', 'author-network', 'author-updated', 'author-gsid', 'author-addr', 'author-uri-id',
98 'owner-id', 'owner-link', 'owner-name', 'owner-avatar', 'owner-network', 'owner-contact-type', 'owner-updated',
99 'causer-id', 'causer-link', 'causer-name', 'causer-avatar', 'causer-contact-type', 'causer-network',
100 'contact-id', 'contact-uid', 'contact-link', 'contact-name', 'contact-avatar',
101 'writable', 'self', 'cid', 'alias',
102 'event-created', 'event-edited', 'event-start', 'event-finish',
103 'event-summary', 'event-desc', 'event-location', 'event-type',
104 'event-nofinish', 'event-ignore', 'event-id',
105 'question-id', 'question-multiple', 'question-voters', 'question-end-time',
106 'has-categories', 'has-media',
107 'delivery_queue_count', 'delivery_queue_done', 'delivery_queue_failed'
110 // Field list that is used to deliver items via the protocols
111 const DELIVER_FIELDLIST = ['uid', 'id', 'parent', 'uri-id', 'uri', 'thr-parent', 'parent-uri', 'guid',
112 'parent-guid', 'conversation', 'received', 'created', 'edited', 'verb', 'object-type', 'object', 'target',
113 'private', 'title', 'body', 'raw-body', 'location', 'coord', 'app',
114 'inform', 'deleted', 'extid', 'post-type', 'post-reason', 'gravity',
115 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid',
116 'author-id', 'author-link', 'author-name', 'author-avatar', 'owner-id', 'owner-link', 'contact-uid',
117 'signed_text', 'network', 'wall', 'contact-id', 'plink', 'origin',
118 'thr-parent-id', 'parent-uri-id', 'postopts', 'pubmail',
119 'event-created', 'event-edited', 'event-start', 'event-finish',
120 'event-summary', 'event-desc', 'event-location', 'event-type',
121 'event-nofinish', 'event-ignore', 'event-id'];
123 // All fields in the item table
124 const ITEM_FIELDLIST = ['id', 'uid', 'parent', 'uri', 'parent-uri', 'thr-parent',
125 'guid', 'uri-id', 'parent-uri-id', 'thr-parent-id', 'conversation', 'vid',
126 'contact-id', 'wall', 'gravity', 'extid', 'psid',
127 'created', 'edited', 'commented', 'received', 'changed', 'verb',
128 'postopts', 'plink', 'resource-id', 'event-id', 'inform',
129 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid', 'post-type', 'post-reason',
130 'private', 'pubmail', 'visible', 'starred',
131 'unseen', 'deleted', 'origin', 'mention', 'global', 'network',
132 'title', 'content-warning', 'body', 'location', 'coord', 'app',
133 'rendered-hash', 'rendered-html', 'object-type', 'object', 'target-type', 'target',
134 'author-id', 'author-link', 'author-name', 'author-avatar', 'author-network',
135 'owner-id', 'owner-link', 'owner-name', 'owner-avatar', 'causer-id'];
137 // List of all verbs that don't need additional content data.
138 // Never reorder or remove entries from this list. Just add new ones at the end, if needed.
140 Activity::LIKE, Activity::DISLIKE,
141 Activity::ATTEND, Activity::ATTENDNO, Activity::ATTENDMAYBE,
150 * Update existing item entries
152 * @param array $fields The fields that are to be changed
153 * @param array $condition The condition for finding the item entries
155 * In the future we may have to change permissions as well.
156 * Then we had to add the user id as third parameter.
158 * A return value of "0" doesn't mean an error - but that 0 rows had been changed.
160 * @return integer|boolean number of affected rows - or "false" if there was an error
161 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
163 public static function update(array $fields, array $condition)
165 if (empty($condition) || empty($fields)) {
169 if (isset($fields['extid'])) {
170 $fields['external-id'] = ItemURI::getIdByURI($fields['extid']);
173 if (!empty($fields['verb'])) {
174 $fields['vid'] = Verb::getID($fields['verb']);
177 if (!empty($fields['edited'])) {
178 $previous = Post::selectFirst(['edited'], $condition);
181 $rows = Post::update($fields, $condition);
182 if (is_bool($rows)) {
186 // We only need to call the line by line update for specific fields
187 if (empty($fields['body']) && empty($fields['file']) &&
188 empty($fields['attach']) && empty($fields['edited'])) {
192 Logger::info('Updating per single row method', ['fields' => $fields, 'condition' => $condition]);
194 $items = Post::select(['id', 'origin', 'uri-id', 'uid', 'author-network'], $condition);
198 while ($item = DBA::fetch($items)) {
199 ActivityPub\PageCache::deleteByUriId($item['uri-id']);
201 if (!empty($fields['body'])) {
202 Post\Media::insertFromAttachmentData($item['uri-id'], $fields['body']);
204 $content_fields = ['raw-body' => trim($fields['raw-body'] ?? $fields['body'])];
206 // Remove all media attachments from the body and store them in the post-media table
207 // @todo On shared postings (Diaspora style and commented reshare) don't fetch content from the shared part
208 $content_fields['raw-body'] = Post\Media::insertFromBody($item['uri-id'], $content_fields['raw-body']);
209 $content_fields['raw-body'] = self::setHashtags($content_fields['raw-body']);
211 if ($item['author-network'] != Protocol::DFRN) {
212 Post\Media::insertFromRelevantUrl($item['uri-id'], $content_fields['raw-body']);
215 Post\Content::update($item['uri-id'], $content_fields);
218 if (!empty($fields['file'])) {
219 Post\Category::storeTextByURIId($item['uri-id'], $item['uid'], $fields['file']);
222 if (!empty($fields['attach'])) {
223 Post\Media::insertFromAttachment($item['uri-id'], $fields['attach']);
226 // We only need to notfiy others when it is an original entry from us.
227 // Only call the notifier when the item had been edited and records had been changed.
228 if ($item['origin'] && !empty($fields['edited']) && ($previous['edited'] != $fields['edited'])) {
229 $notify_items[] = $item['id'];
235 foreach ($notify_items as $notify_item) {
236 $post = Post::selectFirst(['uri-id', 'uid'], ['id' => $notify_item]);
237 Worker::add(PRIORITY_HIGH, 'Notifier', Delivery::POST, (int)$post['uri-id'], (int)$post['uid']);
244 * Delete an item and notify others about it - if it was ours
246 * @param array $condition The condition for finding the item entries
247 * @param integer $priority Priority for the notification
249 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
251 public static function markForDeletion(array $condition, int $priority = PRIORITY_HIGH)
253 $items = Post::select(['id'], $condition);
254 while ($item = Post::fetch($items)) {
255 self::markForDeletionById($item['id'], $priority);
261 * Delete an item for an user and notify others about it - if it was ours
263 * @param array $condition The condition for finding the item entries
264 * @param integer $uid User who wants to delete this item
266 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
268 public static function deleteForUser(array $condition, int $uid)
274 $items = Post::select(['id', 'uid', 'uri-id'], $condition);
275 while ($item = Post::fetch($items)) {
276 if (in_array($item['uid'], [$uid, 0])) {
277 Post\User::update($item['uri-id'], $uid, ['hidden' => true], true);
278 Post\ThreadUser::update($item['uri-id'], $uid, ['hidden' => true], true);
281 if ($item['uid'] == $uid) {
282 self::markForDeletionById($item['id'], PRIORITY_HIGH);
283 } elseif ($item['uid'] != 0) {
284 Logger::warning('Wrong ownership. Not deleting item', ['id' => $item['id']]);
291 * Mark an item for deletion, delete related data and notify others about it - if it was ours
293 * @param integer $item_id
294 * @param integer $priority Priority for the notification
295 * @return boolean success
296 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
298 public static function markForDeletionById(int $item_id, int $priority = PRIORITY_HIGH): bool
300 Logger::info('Mark item for deletion by id', ['id' => $item_id, 'callstack' => System::callstack()]);
301 // locate item to be deleted
302 $fields = ['id', 'uri', 'uri-id', 'uid', 'parent', 'parent-uri-id', 'origin',
303 'deleted', 'resource-id', 'event-id',
304 'verb', 'object-type', 'object', 'target', 'contact-id', 'psid', 'gravity'];
305 $item = Post::selectFirst($fields, ['id' => $item_id]);
306 if (!DBA::isResult($item)) {
307 Logger::info('Item not found.', ['id' => $item_id]);
311 if ($item['deleted']) {
312 Logger::info('Item has already been marked for deletion.', ['id' => $item_id]);
316 $parent = Post::selectFirst(['origin'], ['id' => $item['parent']]);
317 if (!DBA::isResult($parent)) {
318 $parent = ['origin' => false];
321 // clean up categories and tags so they don't end up as orphans
322 Post\Category::deleteByURIId($item['uri-id'], $item['uid']);
324 ActivityPub\PageCache::deleteByUriId($item['uri-id']);
327 * If item is a link to a photo resource, nuke all the associated photos
328 * (visitors will not have photo resources)
329 * This only applies to photos uploaded from the photos page. Photos inserted into a post do not
330 * generate a resource-id and therefore aren't intimately linked to the item.
332 /// @TODO: this should first check if photo is used elsewhere
333 if (strlen($item['resource-id'])) {
334 Photo::delete(['resource-id' => $item['resource-id'], 'uid' => $item['uid']]);
337 // If item is a link to an event, delete the event.
338 if (intval($item['event-id'])) {
339 Event::delete($item['event-id']);
342 // If item has attachments, drop them
343 $attachments = Post\Media::getByURIId($item['uri-id'], [Post\Media::DOCUMENT]);
344 foreach($attachments as $attachment) {
345 if (preg_match('|attach/(\d+)|', $attachment['url'], $matches)) {
346 Attach::delete(['id' => $matches[1], 'uid' => $item['uid']]);
350 // Set the item to "deleted"
351 $item_fields = ['deleted' => true, 'edited' => DateTimeFormat::utcNow(), 'changed' => DateTimeFormat::utcNow()];
352 Post::update($item_fields, ['id' => $item['id']]);
354 Post\Category::storeTextByURIId($item['uri-id'], $item['uid'], '');
356 if (!Post::exists(["`uri-id` = ? AND `uid` != 0 AND NOT `deleted`", $item['uri-id']])) {
357 self::markForDeletion(['uri-id' => $item['uri-id'], 'uid' => 0, 'deleted' => false], $priority);
360 Post\DeliveryData::delete($item['uri-id']);
362 // If it's the parent of a comment thread, kill all the kids
363 if ($item['gravity'] == GRAVITY_PARENT) {
364 self::markForDeletion(['parent' => $item['parent'], 'deleted' => false], $priority);
367 // Is it our comment and/or our thread?
368 if (($item['origin'] || $parent['origin']) && ($item['uid'] != 0)) {
369 // When we delete the original post we will delete all existing copies on the server as well
370 self::markForDeletion(['uri-id' => $item['uri-id'], 'deleted' => false], $priority);
372 // send the notification upstream/downstream
374 Worker::add(['priority' => $priority, 'dont_fork' => true], 'Notifier', Delivery::DELETION, (int)$item['uri-id'], (int)$item['uid']);
376 } elseif ($item['uid'] != 0) {
377 Post\User::update($item['uri-id'], $item['uid'], ['hidden' => true]);
378 Post\ThreadUser::update($item['uri-id'], $item['uid'], ['hidden' => true]);
381 Logger::info('Item has been marked for deletion.', ['id' => $item_id]);
387 * Get guid from given item record
389 * @param array $item Item record
390 * @param bool Whether to notify (?)
391 * @return string Guid
393 public static function guid(array $item, bool $notify): string
395 if (!empty($item['guid'])) {
396 return trim($item['guid']);
400 // We have to avoid duplicates. So we create the GUID in form of a hash of the plink or uri.
401 // We add the hash of our own host because our host is the original creator of the post.
402 $prefix_host = DI::baseUrl()->getHostname();
406 // We are only storing the post so we create a GUID from the original hostname.
407 if (!empty($item['author-link'])) {
408 $parsed = parse_url($item['author-link']);
409 if (!empty($parsed['host'])) {
410 $prefix_host = $parsed['host'];
414 if (empty($prefix_host) && !empty($item['plink'])) {
415 $parsed = parse_url($item['plink']);
416 if (!empty($parsed['host'])) {
417 $prefix_host = $parsed['host'];
421 if (empty($prefix_host) && !empty($item['uri'])) {
422 $parsed = parse_url($item['uri']);
423 if (!empty($parsed['host'])) {
424 $prefix_host = $parsed['host'];
428 // Is it in the format data@host.tld? - Used for mail contacts
429 if (empty($prefix_host) && !empty($item['author-link']) && strstr($item['author-link'], '@')) {
430 $mailparts = explode('@', $item['author-link']);
431 $prefix_host = array_pop($mailparts);
435 if (!empty($item['plink'])) {
436 $guid = self::guidFromUri($item['plink'], $prefix_host);
437 } elseif (!empty($item['uri'])) {
438 $guid = self::guidFromUri($item['uri'], $prefix_host);
440 $guid = System::createUUID(hash('crc32', $prefix_host));
447 * Returns contact id from given item record
449 * @param array $item Item record
450 * @return int Contact id
452 private static function contactId(array $item): int
454 if ($item['uid'] == 0) {
455 return $item['author-id'];
458 if ($item['origin']) {
459 $owner = User::getOwnerDataById($item['uid']);
463 if (!empty($item['causer-id']) && Contact::isSharing($item['causer-id'], $item['uid'], true)) {
464 $cdata = Contact::getPublicAndUserContactID($item['causer-id'], $item['uid']);
465 if (!empty($cdata['user'])) {
466 return $cdata['user'];
470 if ($item['gravity'] == GRAVITY_PARENT) {
471 if (Contact::isSharingByURL($item['owner-link'], $item['uid'], true)) {
472 $contact_id = Contact::getIdForURL($item['owner-link'], $item['uid']);
474 $contact_id = Contact::getIdForURL($item['owner-link']);
476 if (!empty($contact_id)) {
481 if (Contact::isSharingByURL($item['author-link'], $item['uid'], true)) {
482 $contact_id = Contact::getIdForURL($item['author-link'], $item['uid']);
484 $contact_id = Contact::getIdForURL($item['author-link']);
487 if (!empty($contact_id)) {
491 Logger::warning('contact-id could not be fetched, using self contact instead.', ['uid' => $item['uid'], 'item' => $item]);
492 $self = Contact::selectFirst(['id'], ['self' => true, 'uid' => $item['uid']]);
497 * Write an item array into a spool file to be inserted later.
498 * This command is called whenever there are issues storing an item.
500 * @param array $item The item fields that are to be inserted
503 private static function spool(array $item)
505 // Now we store the data in the spool directory
506 // We use "microtime" to keep the arrival order and "mt_rand" to avoid duplicates
507 $file = 'item-' . round(microtime(true) * 10000) . '-' . mt_rand() . '.msg';
509 $spoolpath = System::getSpoolPath();
510 if ($spoolpath != '') {
511 $spool = $spoolpath . '/' . $file;
513 file_put_contents($spool, json_encode($item));
514 Logger::warning("Item wasn't stored - Item was spooled into file", ['file' => $file]);
519 * Check if the item array is a duplicate
521 * @param array $item Item record
522 * @return boolean is it a duplicate?
524 private static function isDuplicate(array $item): bool
526 // Checking if there is already an item with the same guid
527 $condition = ['guid' => $item['guid'], 'network' => $item['network'], 'uid' => $item['uid']];
528 if (Post::exists($condition)) {
529 Logger::notice('Found already existing item', $condition);
533 $condition = ['uri-id' => $item['uri-id'], 'uid' => $item['uid'],
534 'network' => [$item['network'], Protocol::DFRN]];
535 if (Post::exists($condition)) {
536 Logger::notice('duplicated item with the same uri found.', $condition);
540 // On Friendica and Diaspora the GUID is unique
541 if (in_array($item['network'], [Protocol::DFRN, Protocol::DIASPORA])) {
542 $condition = ['guid' => $item['guid'], 'uid' => $item['uid']];
543 if (Post::exists($condition)) {
544 Logger::notice('duplicated item with the same guid found.', $condition);
547 } elseif ($item['network'] == Protocol::OSTATUS) {
548 // Check for an existing post with the same content. There seems to be a problem with OStatus.
549 $condition = ["`body` = ? AND `network` = ? AND `created` = ? AND `contact-id` = ? AND `uid` = ?",
550 $item['body'], $item['network'], $item['created'], $item['contact-id'], $item['uid']];
551 if (Post::exists($condition)) {
552 Logger::notice('duplicated item with the same body found.', $item);
558 * Check for already added items.
559 * There is a timing issue here that sometimes creates double postings.
560 * An unique index would help - but the limitations of MySQL (maximum size of index values) prevent this.
562 if (($item['uid'] == 0) && Post::exists(['uri-id' => $item['uri-id'], 'uid' => 0])) {
563 Logger::notice('Global item already stored.', ['uri-id' => $item['uri-id'], 'network' => $item['network']]);
571 * Check if the item array is valid
573 * @param array $item Item record
574 * @return boolean item is valid
576 public static function isValid(array $item): bool
578 // When there is no content then we don't post it
579 if (($item['body'] . $item['title'] == '') && (empty($item['uri-id']) || !Post\Media::existsByURIId($item['uri-id']))) {
580 Logger::notice('No body, no title.');
584 if (!empty($item['uid'])) {
585 $owner = User::getOwnerDataById($item['uid'], false);
587 Logger::warning('Missing item user owner data', ['uid' => $item['uid']]);
591 if ($owner['account_expired'] || $owner['account_removed']) {
592 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']]);
597 if (!empty($item['author-id']) && Contact::isBlocked($item['author-id'])) {
598 Logger::notice('Author is blocked node-wide', ['author-link' => $item['author-link'], 'item-uri' => $item['uri']]);
602 if (!empty($item['author-link']) && Network::isUrlBlocked($item['author-link'])) {
603 Logger::notice('Author server is blocked', ['author-link' => $item['author-link'], 'item-uri' => $item['uri']]);
607 if (!empty($item['owner-id']) && Contact::isBlocked($item['owner-id'])) {
608 Logger::notice('Owner is blocked node-wide', ['owner-link' => $item['owner-link'], 'item-uri' => $item['uri']]);
612 if (!empty($item['owner-link']) && Network::isUrlBlocked($item['owner-link'])) {
613 Logger::notice('Owner server is blocked', ['owner-link' => $item['owner-link'], 'item-uri' => $item['uri']]);
617 if (!empty($item['uid']) && !self::isAllowedByUser($item, $item['uid'])) {
621 if ($item['verb'] == Activity::FOLLOW) {
622 if (!$item['origin'] && ($item['author-id'] == Contact::getPublicIdByUserId($item['uid']))) {
623 // Our own follow request can be relayed to us. We don't store it to avoid notification chaos.
624 Logger::info("Follow: Don't store not origin follow request", ['parent-uri' => $item['parent-uri']]);
628 $condition = ['verb' => Activity::FOLLOW, 'uid' => $item['uid'],
629 'parent-uri' => $item['parent-uri'], 'author-id' => $item['author-id']];
630 if (Post::exists($condition)) {
631 // It happens that we receive multiple follow requests by the same author - we only store one.
632 Logger::info('Follow: Found existing follow request from author', ['author-id' => $item['author-id'], 'parent-uri' => $item['parent-uri']]);
641 * Check if the item array is too old
643 * @param array $item Item record
644 * @return boolean item is too old
646 public static function isTooOld(array $item): bool
648 // check for create date and expire time
649 $expire_interval = DI::config()->get('system', 'dbclean-expire-days', 0);
651 $user = DBA::selectFirst('user', ['expire'], ['uid' => $item['uid']]);
652 if (DBA::isResult($user) && ($user['expire'] > 0) && (($user['expire'] < $expire_interval) || ($expire_interval == 0))) {
653 $expire_interval = $user['expire'];
656 if (($expire_interval > 0) && !empty($item['created'])) {
657 $expire_date = time() - ($expire_interval * 86400);
658 $created_date = strtotime($item['created']);
659 if ($created_date < $expire_date) {
660 Logger::notice('Item created before expiration interval.', [
661 'created' => date('c', $created_date),
662 'expired' => date('c', $expire_date),
673 * Return the id of the given item array if it has been stored before
675 * @param array $item Item record
676 * @return integer Item id or zero on error
678 private static function getDuplicateID(array $item): int
680 if (empty($item['network']) || in_array($item['network'], Protocol::FEDERATED)) {
681 $condition = ['`uri-id` = ? AND `uid` = ? AND `network` IN (?, ?, ?, ?)',
684 Protocol::ACTIVITYPUB,
689 $existing = Post::selectFirst(['id', 'network'], $condition);
690 if (DBA::isResult($existing)) {
691 // We only log the entries with a different user id than 0. Otherwise we would have too many false positives
692 if ($item['uid'] != 0) {
693 Logger::notice('Item already existed for user', [
694 'uri-id' => $item['uri-id'],
695 'uid' => $item['uid'],
696 'network' => $item['network'],
697 'existing_id' => $existing['id'],
698 'existing_network' => $existing['network']
702 return $existing['id'];
709 * Fetch top-level parent data for the given item array
712 * @return array item array with parent data
715 private static function getTopLevelParent(array $item): array
717 $fields = ['uid', 'uri', 'parent-uri', 'id', 'deleted',
718 'uri-id', 'parent-uri-id',
719 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid',
720 'wall', 'private', 'origin', 'author-id'];
721 $condition = ['uri-id' => [$item['thr-parent-id'], $item['parent-uri-id']], 'uid' => $item['uid']];
722 $params = ['order' => ['id' => false]];
723 $parent = Post::selectFirst($fields, $condition, $params);
725 if (!DBA::isResult($parent) && Post::exists(['uri-id' => [$item['thr-parent-id'], $item['parent-uri-id']], 'uid' => 0])) {
726 $stored = Item::storeForUserByUriId($item['thr-parent-id'], $item['uid'], ['post-reason' => Item::PR_COMPLETION]);
727 if (!$stored && ($item['thr-parent-id'] != $item['parent-uri-id'])) {
728 $stored = Item::storeForUserByUriId($item['parent-uri-id'], $item['uid'], ['post-reason' => Item::PR_COMPLETION]);
731 Logger::info('Stored thread parent item for user', ['uri-id' => $item['thr-parent-id'], 'uid' => $item['uid'], 'stored' => $stored]);
732 $parent = Post::selectFirst($fields, $condition, $params);
736 if (!DBA::isResult($parent)) {
737 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)]);
741 if ($parent['uri-id'] == $parent['parent-uri-id']) {
745 $condition = ['uri-id' => $parent['parent-uri-id'],
746 'parent-uri-id' => $parent['parent-uri-id'],
747 'uid' => $parent['uid']];
748 $params = ['order' => ['id' => false]];
749 $toplevel_parent = Post::selectFirst($fields, $condition, $params);
751 if (!DBA::isResult($toplevel_parent) && $item['origin']) {
752 $stored = Item::storeForUserByUriId($item['parent-uri-id'], $item['uid'], ['post-reason' => Item::PR_COMPLETION]);
753 Logger::info('Stored parent item for user', ['uri-id' => $item['parent-uri-id'], 'uid' => $item['uid'], 'stored' => $stored]);
754 $toplevel_parent = Post::selectFirst($fields, $condition, $params);
757 if (!DBA::isResult($toplevel_parent)) {
758 Logger::notice('item top level parent was not found - ignoring item', ['parent-uri-id' => $parent['parent-uri-id'], 'uid' => $parent['uid']]);
762 return $toplevel_parent;
766 * Get the gravity for the given item array
769 * @return integer gravity
771 private static function getGravity(array $item): int
773 $activity = DI::activity();
775 if (isset($item['gravity'])) {
776 return intval($item['gravity']);
777 } elseif ($item['parent-uri-id'] === $item['uri-id']) {
778 return GRAVITY_PARENT;
779 } elseif ($activity->match($item['verb'], Activity::POST)) {
780 return GRAVITY_COMMENT;
781 } elseif ($activity->match($item['verb'], Activity::FOLLOW)) {
782 return GRAVITY_ACTIVITY;
783 } elseif ($activity->match($item['verb'], Activity::ANNOUNCE)) {
784 return GRAVITY_ACTIVITY;
787 Logger::info('Unknown gravity for verb', ['verb' => $item['verb']]);
788 return GRAVITY_UNKNOWN; // Should not happen
792 * Inserts item record
794 * @param array $item Item array to be inserted
795 * @param int $notify Notification (type?)
796 * @param bool $post_local (???)
797 * @return int Zero means error, otherwise primary key (id) is being returned
799 public static function insert(array $item, int $notify = 0, bool $post_local = true): int
803 $priority = PRIORITY_HIGH;
805 // If it is a posting where users should get notifications, then define it as wall posting
809 $item['network'] = Protocol::DFRN;
810 $item['protocol'] = Conversation::PARCEL_DIRECT;
811 $item['direction'] = Conversation::PUSH;
813 if (is_int($notify) && in_array($notify, PRIORITIES)) {
817 $item['network'] = trim(($item['network'] ?? '') ?: Protocol::PHANTOM);
820 $uid = intval($item['uid']);
822 $item['guid'] = self::guid($item, $notify);
823 $item['uri'] = substr(trim($item['uri'] ?? '') ?: self::newURI($item['guid']), 0, 255);
826 $item['uri-id'] = ItemURI::insert(['uri' => $item['uri'], 'guid' => $item['guid']]);
828 // Backward compatibility: parent-uri used to be the direct parent uri.
829 // If it is provided without a thr-parent, it probably is the old behavior.
830 if (empty($item['thr-parent']) || empty($item['parent-uri'])) {
831 $item['thr-parent'] = trim($item['thr-parent'] ?? $item['parent-uri'] ?? $item['uri']);
832 $item['parent-uri'] = $item['thr-parent'];
835 $item['thr-parent-id'] = ItemURI::getIdByURI($item['thr-parent']);
836 $item['parent-uri-id'] = ItemURI::getIdByURI($item['parent-uri']);
838 // Store conversation data
839 $source = $item['source'] ?? '';
840 unset($item['conversation-uri']);
841 unset($item['conversation-href']);
842 unset($item['source']);
845 * Do we already have this item?
846 * We have to check several networks since Friendica posts could be repeated
847 * via OStatus (maybe Diasporsa as well)
849 $duplicate = self::getDuplicateID($item);
854 // Additional duplicate checks
855 /// @todo Check why the first duplication check returns the item number and the second a 0
856 if (self::isDuplicate($item)) {
860 if (!isset($item['post-type'])) {
861 $item['post-type'] = empty($item['title']) ? self::PT_NOTE : self::PT_ARTICLE;
864 $item['wall'] = intval($item['wall'] ?? 0);
865 $item['extid'] = trim($item['extid'] ?? '');
866 $item['author-name'] = trim($item['author-name'] ?? '');
867 $item['author-link'] = trim($item['author-link'] ?? '');
868 $item['author-avatar'] = trim($item['author-avatar'] ?? '');
869 $item['owner-name'] = trim($item['owner-name'] ?? '');
870 $item['owner-link'] = trim($item['owner-link'] ?? '');
871 $item['owner-avatar'] = trim($item['owner-avatar'] ?? '');
872 $item['received'] = (isset($item['received']) ? DateTimeFormat::utc($item['received']) : DateTimeFormat::utcNow());
873 $item['created'] = (isset($item['created']) ? DateTimeFormat::utc($item['created']) : $item['received']);
874 $item['edited'] = (isset($item['edited']) ? DateTimeFormat::utc($item['edited']) : $item['created']);
875 $item['changed'] = (isset($item['changed']) ? DateTimeFormat::utc($item['changed']) : $item['created']);
876 $item['commented'] = (isset($item['commented']) ? DateTimeFormat::utc($item['commented']) : $item['created']);
877 $item['title'] = substr(trim($item['title'] ?? ''), 0, 255);
878 $item['location'] = trim($item['location'] ?? '');
879 $item['coord'] = trim($item['coord'] ?? '');
880 $item['visible'] = (isset($item['visible']) ? intval($item['visible']) : 1);
881 $item['deleted'] = 0;
882 $item['verb'] = trim($item['verb'] ?? '');
883 $item['object-type'] = trim($item['object-type'] ?? '');
884 $item['object'] = trim($item['object'] ?? '');
885 $item['target-type'] = trim($item['target-type'] ?? '');
886 $item['target'] = trim($item['target'] ?? '');
887 $item['plink'] = substr(trim($item['plink'] ?? ''), 0, 255);
888 $item['allow_cid'] = trim($item['allow_cid'] ?? '');
889 $item['allow_gid'] = trim($item['allow_gid'] ?? '');
890 $item['deny_cid'] = trim($item['deny_cid'] ?? '');
891 $item['deny_gid'] = trim($item['deny_gid'] ?? '');
892 $item['private'] = intval($item['private'] ?? self::PUBLIC);
893 $item['body'] = trim($item['body'] ?? '');
894 $item['raw-body'] = trim($item['raw-body'] ?? $item['body']);
895 $item['app'] = trim($item['app'] ?? '');
896 $item['origin'] = intval($item['origin'] ?? 0);
897 $item['postopts'] = trim($item['postopts'] ?? '');
898 $item['resource-id'] = trim($item['resource-id'] ?? '');
899 $item['event-id'] = intval($item['event-id'] ?? 0);
900 $item['inform'] = trim($item['inform'] ?? '');
901 $item['file'] = trim($item['file'] ?? '');
903 // Communities aren't working with the Diaspora protoccol
904 if (($uid != 0) && ($item['network'] == Protocol::DIASPORA)) {
905 $user = User::getById($uid, ['account-type']);
906 if ($user['account-type'] == Contact::TYPE_COMMUNITY) {
907 Logger::info('Community posts are not supported via Diaspora');
912 // Items cannot be stored before they happen ...
913 if ($item['created'] > DateTimeFormat::utcNow()) {
914 $item['created'] = DateTimeFormat::utcNow();
917 // We haven't invented time travel by now.
918 if ($item['edited'] > DateTimeFormat::utcNow()) {
919 $item['edited'] = DateTimeFormat::utcNow();
922 $item['plink'] = ($item['plink'] ?? '') ?: DI::baseUrl() . '/display/' . urlencode($item['guid']);
924 $item['gravity'] = self::getGravity($item);
926 $default = ['url' => $item['author-link'], 'name' => $item['author-name'],
927 'photo' => $item['author-avatar'], 'network' => $item['network']];
928 $item['author-id'] = ($item['author-id'] ?? 0) ?: Contact::getIdForURL($item['author-link'], 0, null, $default);
930 $default = ['url' => $item['owner-link'], 'name' => $item['owner-name'],
931 'photo' => $item['owner-avatar'], 'network' => $item['network']];
932 $item['owner-id'] = ($item['owner-id'] ?? 0) ?: Contact::getIdForURL($item['owner-link'], 0, null, $default);
934 $item['post-reason'] = self::getPostReason($item);
936 // Ensure that there is an avatar cache
937 Contact::checkAvatarCache($item['author-id']);
938 Contact::checkAvatarCache($item['owner-id']);
940 $item['contact-id'] = self::contactId($item);
942 if (!empty($item['direction']) && in_array($item['direction'], [Conversation::PUSH, Conversation::RELAY]) &&
943 empty($item['origin']) && self::isTooOld($item)) {
944 Logger::info('Item is too old', ['item' => $item]);
948 if (!self::isValid($item)) {
952 if ($item['gravity'] !== GRAVITY_PARENT) {
953 $toplevel_parent = self::getTopLevelParent($item);
954 if (empty($toplevel_parent)) {
958 // If the thread originated from this node, we check the permission against the thread starter
959 $condition = ['uri-id' => $toplevel_parent['uri-id'], 'wall' => true];
960 $localTopLevelParent = Post::selectFirst(['uid'], $condition);
961 if (!empty($localTopLevelParent['uid']) && !self::isAllowedByUser($item, $localTopLevelParent['uid'])) {
965 $parent_id = $toplevel_parent['id'];
966 $item['parent-uri'] = $toplevel_parent['uri'];
967 $item['parent-uri-id'] = $toplevel_parent['uri-id'];
968 $item['deleted'] = $toplevel_parent['deleted'];
970 // Reshares have to keep their permissions to allow forums to work
971 if (!$item['origin'] || ($item['verb'] != Activity::ANNOUNCE)) {
972 $item['allow_cid'] = $toplevel_parent['allow_cid'];
973 $item['allow_gid'] = $toplevel_parent['allow_gid'];
974 $item['deny_cid'] = $toplevel_parent['deny_cid'];
975 $item['deny_gid'] = $toplevel_parent['deny_gid'];
978 $parent_origin = $toplevel_parent['origin'];
980 // Don't federate received participation messages
981 if ($item['verb'] != Activity::FOLLOW) {
982 $item['wall'] = $toplevel_parent['wall'];
984 $item['wall'] = false;
985 // Participations are technical messages, so they are set to "seen" automatically
986 $item['unseen'] = false;
990 * If the parent is private, force privacy for the entire conversation
991 * This differs from the above settings as it subtly allows comments from
992 * email correspondents to be private even if the overall thread is not.
994 if ($toplevel_parent['private']) {
995 $item['private'] = $toplevel_parent['private'];
998 // If its a post that originated here then tag the thread as "mention"
999 if ($item['origin'] && $item['uid']) {
1000 DBA::update('post-thread-user', ['mention' => true], ['uri-id' => $item['parent-uri-id'], 'uid' => $item['uid']]);
1001 Logger::info('tagged thread as mention', ['parent' => $parent_id, 'parent-uri-id' => $item['parent-uri-id'], 'uid' => $item['uid']]);
1004 // Update the contact relations
1005 Contact\Relation::store($toplevel_parent['author-id'], $item['author-id'], $item['created']);
1008 $parent_origin = $item['origin'];
1010 if ($item['wall'] && empty($item['conversation'])) {
1011 $item['conversation'] = $item['parent-uri'] . '#context';
1015 $item['parent-uri-id'] = ItemURI::getIdByURI($item['parent-uri']);
1016 $item['thr-parent-id'] = ItemURI::getIdByURI($item['thr-parent']);
1018 if (!empty($item['conversation']) && empty($item['conversation-id'])) {
1019 $item['conversation-id'] = ItemURI::getIdByURI($item['conversation']);
1022 // Is this item available in the global items (with uid=0)?
1023 if ($item['uid'] == 0) {
1024 $item['global'] = true;
1026 // Set the global flag on all items if this was a global item entry
1027 Post::update(['global' => true], ['uri-id' => $item['uri-id']]);
1029 $item['global'] = Post::exists(['uid' => 0, 'uri-id' => $item['uri-id']]);
1033 if (!empty($item['allow_cid'] . $item['allow_gid'] . $item['deny_cid'] . $item['deny_gid'])) {
1034 $item['private'] = self::PRIVATE;
1037 if ($notify && $post_local) {
1038 $item['edit'] = false;
1039 $item['parent'] = $parent_id;
1041 // Trigger automatic reactions for addons
1042 if (!isset($item['api_source'])) {
1043 $item['api_source'] = true;
1046 // We have to tell the hooks who we are - this really should be improved
1047 if (!local_user()) {
1048 $_SESSION['authenticated'] = true;
1049 $_SESSION['uid'] = $uid;
1050 $dummy_session = true;
1052 $dummy_session = false;
1055 Hook::callAll('post_local', $item);
1057 if ($dummy_session) {
1058 unset($_SESSION['authenticated']);
1059 unset($_SESSION['uid']);
1061 } elseif (!$notify) {
1062 Hook::callAll('post_remote', $item);
1065 if (!empty($item['cancel'])) {
1066 Logger::notice('post cancelled by addon.');
1070 if (empty($item['vid']) && !empty($item['verb'])) {
1071 $item['vid'] = Verb::getID($item['verb']);
1074 // Creates or assigns the permission set
1075 $item['psid'] = DI::permissionSet()->selectOrCreate(
1076 DI::permissionSetFactory()->createFromString(
1084 if (!empty($item['extid'])) {
1085 $item['external-id'] = ItemURI::getIdByURI($item['extid']);
1088 if ($item['verb'] == Activity::ANNOUNCE) {
1089 self::setOwnerforResharedItem($item);
1092 if (isset($item['attachments'])) {
1093 foreach ($item['attachments'] as $attachment) {
1094 $attachment['uri-id'] = $item['uri-id'];
1095 Post\Media::insert($attachment);
1097 unset($item['attachments']);
1100 Post\Media::insertFromAttachmentData($item['uri-id'], $item['body']);
1102 // Remove all media attachments from the body and store them in the post-media table
1103 $item['raw-body'] = Post\Media::insertFromBody($item['uri-id'], $item['raw-body']);
1104 $item['raw-body'] = self::setHashtags($item['raw-body']);
1106 if (!DBA::exists('contact', ['id' => $item['author-id'], 'network' => Protocol::DFRN])) {
1107 Post\Media::insertFromRelevantUrl($item['uri-id'], $item['raw-body']);
1110 // Check for hashtags in the body and repair or add hashtag links
1111 $item['body'] = self::setHashtags($item['body']);
1113 $item['language'] = self::getLanguage($item);
1115 $notify_type = Delivery::POST;
1117 // Filling item related side tables
1118 if (!empty($item['attach'])) {
1119 Post\Media::insertFromAttachment($item['uri-id'], $item['attach']);
1122 if (empty($item['event-id'])) {
1123 unset($item['event-id']);
1125 $ev = Event::fromBBCode($item['body']);
1126 if ((!empty($ev['desc']) || !empty($ev['summary'])) && !empty($ev['start'])) {
1127 Logger::info('Event found.');
1128 $ev['cid'] = $item['contact-id'];
1129 $ev['uid'] = $item['uid'];
1130 $ev['uri'] = $item['uri'];
1131 $ev['edited'] = $item['edited'];
1132 $ev['private'] = $item['private'];
1133 $ev['guid'] = $item['guid'];
1134 $ev['plink'] = $item['plink'];
1135 $ev['network'] = $item['network'];
1136 $ev['protocol'] = $item['protocol'] ?? Conversation::PARCEL_UNKNOWN;
1137 $ev['direction'] = $item['direction'] ?? Conversation::UNKNOWN;
1138 $ev['source'] = $item['source'] ?? '';
1140 $event = DBA::selectFirst('event', ['id'], ['uri' => $item['uri'], 'uid' => $item['uid']]);
1141 if (DBA::isResult($event)) {
1142 $ev['id'] = $event['id'];
1145 $event_id = Event::store($ev);
1146 $item = Event::getItemArrayForImportedId($event_id, $item);
1148 Logger::info('Event was stored', ['id' => $event_id]);
1152 if (empty($item['causer-id'])) {
1153 unset($item['causer-id']);
1156 if (in_array($item['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN])) {
1157 $content_warning = BBCode::getAbstract($item['body'], Protocol::ACTIVITYPUB);
1158 if (!empty($content_warning) && empty($item['content-warning'])) {
1159 $item['content-warning'] = BBCode::toPlaintext($content_warning);
1163 Post::insert($item['uri-id'], $item);
1165 if ($item['gravity'] == GRAVITY_PARENT) {
1166 Post\Thread::insert($item['uri-id'], $item);
1169 if (!in_array($item['verb'], self::ACTIVITIES)) {
1170 Post\Content::insert($item['uri-id'], $item);
1173 // Create Diaspora signature
1174 if ($item['origin'] && empty($item['diaspora_signed_text']) && ($item['gravity'] != GRAVITY_PARENT)) {
1175 $signed = Diaspora::createCommentSignature($item);
1176 if (!empty($signed)) {
1177 $item['diaspora_signed_text'] = json_encode($signed);
1181 if (!empty($item['diaspora_signed_text'])) {
1182 DBA::replace('diaspora-interaction', ['uri-id' => $item['uri-id'], 'interaction' => $item['diaspora_signed_text']]);
1185 // Attached file links
1186 if (!empty($item['file'])) {
1187 Post\Category::storeTextByURIId($item['uri-id'], $item['uid'], $item['file']);
1190 // Delivery relevant data
1191 $delivery_data = Post\DeliveryData::extractFields($item);
1193 if (!empty($item['origin']) || !empty($item['wall']) || !empty($delivery_data['postopts']) || !empty($delivery_data['inform'])) {
1194 Post\DeliveryData::insert($item['uri-id'], $delivery_data);
1197 // Store tags from the body if this hadn't been handled previously in the protocol classes
1198 if (!Tag::existsForPost($item['uri-id'])) {
1199 Tag::storeFromBody($item['uri-id'], $item['body']);
1202 $condition = ['uri-id' => $item['uri-id'], 'uid' => $item['uid']];
1203 if (Post::exists($condition)) {
1204 Logger::notice('Item is already inserted - aborting', $condition);
1208 $post_user_id = Post\User::insert($item['uri-id'], $item['uid'], $item);
1209 if (!$post_user_id) {
1210 Logger::notice('Post-User is already inserted - aborting', ['uid' => $item['uid'], 'uri-id' => $item['uri-id']]);
1214 if ($item['gravity'] == GRAVITY_PARENT) {
1215 $item['post-user-id'] = $post_user_id;
1216 Post\ThreadUser::insert($item['uri-id'], $item['uid'], $item);
1219 Logger::notice('created item', ['post-id' => $post_user_id, 'uid' => $item['uid'], 'network' => $item['network'], 'uri-id' => $item['uri-id'], 'guid' => $item['guid']]);
1221 $posted_item = Post::selectFirst(self::ITEM_FIELDLIST, ['post-user-id' => $post_user_id]);
1222 if (!DBA::isResult($posted_item)) {
1223 // On failure store the data into a spool file so that the "SpoolPost" worker can try again later.
1224 Logger::warning('Could not store item. it will be spooled', ['id' => $post_user_id]);
1225 self::spool($orig_item);
1229 // update the commented timestamp on the parent
1230 if (DI::config()->get('system', 'like_no_comment')) {
1231 // Update when it is a comment
1232 $update_commented = in_array($posted_item['gravity'], [GRAVITY_PARENT, GRAVITY_COMMENT]);
1234 // Update when it isn't a follow or tag verb
1235 $update_commented = !in_array($posted_item['verb'], [Activity::FOLLOW, Activity::TAG]);
1238 if ($update_commented) {
1239 $fields = ['commented' => DateTimeFormat::utcNow(), 'changed' => DateTimeFormat::utcNow()];
1241 $fields = ['changed' => DateTimeFormat::utcNow()];
1244 Post::update($fields, ['uri-id' => $posted_item['parent-uri-id'], 'uid' => $posted_item['uid']]);
1246 // In that function we check if this is a forum post. Additionally we delete the item under certain circumstances
1247 if (self::tagDeliver($posted_item['uid'], $post_user_id)) {
1248 // Get the user information for the logging
1249 $user = User::getById($uid);
1251 Logger::notice('Item had been deleted', ['id' => $post_user_id, 'user' => $uid, 'account-type' => $user['account-type']]);
1256 if (!\Friendica\Content\Feature::isEnabled($posted_item['uid'], 'explicit_mentions') && ($posted_item['gravity'] == GRAVITY_COMMENT)) {
1257 Tag::createImplicitMentions($posted_item['uri-id'], $posted_item['thr-parent-id']);
1259 Hook::callAll('post_local_end', $posted_item);
1261 Hook::callAll('post_remote_end', $posted_item);
1264 if ($posted_item['gravity'] === GRAVITY_PARENT) {
1265 self::addShadow($post_user_id);
1267 self::addShadowPost($post_user_id);
1270 self::updateContact($posted_item);
1272 Post\UserNotification::setNotification($posted_item['uri-id'], $posted_item['uid']);
1274 // Distribute items to users who subscribed to their tags
1275 self::distributeByTags($posted_item);
1277 // Automatically reshare the item if the "remote_self" option is selected
1278 self::autoReshare($posted_item);
1280 $transmit = $notify || ($posted_item['visible'] && ($parent_origin || $posted_item['origin']));
1283 // Don't relay participation messages
1284 if (($posted_item['verb'] == Activity::FOLLOW) &&
1285 (!$posted_item['origin'] || ($posted_item['author-id'] != Contact::getPublicIdByUserId($uid)))) {
1286 Logger::info('Participation messages will not be relayed', ['item' => $posted_item['id'], 'uri' => $posted_item['uri'], 'verb' => $posted_item['verb']]);
1292 if (!empty($source)) {
1293 Post\Activity::insert($item['uri-id'], $source);
1295 Worker::add(['priority' => $priority, 'dont_fork' => true], 'Notifier', $notify_type, (int)$posted_item['uri-id'], (int)$posted_item['uid']);
1298 // Fill the cache with the rendered content.
1299 if (in_array($posted_item['gravity'], [GRAVITY_PARENT, GRAVITY_COMMENT]) && ($posted_item['uid'] == 0)) {
1300 self::updateDisplayCache($posted_item['uri-id']);
1303 return $post_user_id;
1307 * Fetch the post reason for a given item array
1309 * @param array $item
1313 public static function getPostReason(array $item): int
1315 $actor = ($item['gravity'] == GRAVITY_PARENT) ? $item['owner-id'] : $item['author-id'];
1316 if (empty($item['origin']) && ($item['uid'] != 0) && Contact::isSharing($actor, $item['uid'])) {
1317 return self::PR_FOLLOWER;
1320 if (!empty($item['origin']) && empty($item['post-reason'])) {
1321 return self::PR_LOCAL;
1324 return $item['post-reason'] ?? self::PR_NONE;
1328 * Update the display cache
1330 * @param integer $uri_id
1333 public static function updateDisplayCache(int $uri_id)
1335 $item = Post::selectFirst(self::DISPLAY_FIELDLIST, ['uri-id' => $uri_id]);
1336 self::prepareBody($item, false, false, true);
1340 * Change the owner of a parent item if it had been shared by a forum
1342 * (public) forum posts in the new format consist of the regular post by the author
1343 * followed by an announce message sent from the forum account.
1344 * Changing the owner helps in grouping forum posts.
1346 * @param array $item
1349 private static function setOwnerforResharedItem(array $item)
1351 $parent = Post::selectFirst(['id', 'causer-id', 'owner-id', 'author-id', 'author-link', 'origin', 'post-reason'],
1352 ['uri-id' => $item['thr-parent-id'], 'uid' => $item['uid']]);
1353 if (!DBA::isResult($parent)) {
1354 Logger::error('Parent not found', ['uri-id' => $item['thr-parent-id'], 'uid' => $item['uid']]);
1358 $author = Contact::selectFirst(['url', 'contact-type', 'network'], ['id' => $item['author-id']]);
1359 if (!DBA::isResult($author)) {
1360 Logger::error('Author not found', ['id' => $item['author-id']]);
1364 $self_contact = Contact::selectFirst(['id'], ['uid' => $item['uid'], 'self' => true]);
1365 $self = !empty($self_contact) ? $self_contact['id'] : 0;
1367 $cid = Contact::getIdForURL($author['url'], $item['uid']);
1368 if (empty($cid) || (!Contact::isSharing($cid, $item['uid']) && ($cid != $self))) {
1369 Logger::info('The resharer is not a following contact: quit', ['resharer' => $author['url'], 'uid' => $item['uid'], 'cid' => $cid]);
1373 if ($author['contact-type'] != Contact::TYPE_COMMUNITY) {
1374 if ($parent['post-reason'] == self::PR_ANNOUNCEMENT) {
1375 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']]);
1379 if (Contact::isSharing($parent['owner-id'], $item['uid'])) {
1380 Logger::info('The resharer is no forum: quit', ['resharer' => $item['author-id'], 'owner' => $parent['owner-id'], 'author' => $parent['author-id'], 'uid' => $item['uid']]);
1385 self::update(['post-reason' => self::PR_ANNOUNCEMENT, 'causer-id' => $item['author-id']], ['id' => $parent['id']]);
1386 Logger::info('Set announcement post-reason', ['uri-id' => $item['uri-id'], 'thr-parent-id' => $item['thr-parent-id'], 'uid' => $item['uid']]);
1390 * Distribute the given item to users who subscribed to their tags
1392 * @param array $item Processed item
1394 private static function distributeByTags(array $item)
1396 if (($item['uid'] != 0) || ($item['gravity'] != GRAVITY_PARENT) || !in_array($item['network'], Protocol::FEDERATED)) {
1400 $uids = Tag::getUIDListByURIId($item['uri-id']);
1401 foreach ($uids as $uid) {
1402 $stored = self::storeForUserByUriId($item['uri-id'], $uid, ['post-reason' => self::PR_TAG]);
1403 Logger::info('Stored item for users', ['uri-id' => $item['uri-id'], 'uid' => $uid, 'stored' => $stored]);
1408 * Distributes public items to the receivers
1410 * @param integer $itemid Item ID that should be added
1411 * @param string $signed_text Original text (for Diaspora signatures), JSON encoded.
1412 * @throws \Exception
1414 public static function distribute(int $itemid, string $signed_text = '')
1416 $condition = ["`id` IN (SELECT `parent` FROM `post-user-view` WHERE `id` = ?)", $itemid];
1417 $parent = Post::selectFirst(['owner-id'], $condition);
1418 if (!DBA::isResult($parent)) {
1419 Logger::warning('Item not found', ['condition' => $condition]);
1423 // Only distribute public items from native networks
1424 $condition = ['id' => $itemid, 'uid' => 0,
1425 'network' => array_merge(Protocol::FEDERATED ,['']),
1426 'visible' => true, 'deleted' => false, 'private' => [self::PUBLIC, self::UNLISTED]];
1427 $item = Post::selectFirst(array_merge(self::ITEM_FIELDLIST, ['protocol']), $condition);
1428 if (!DBA::isResult($item)) {
1429 Logger::warning('Item not found', ['condition' => $condition]);
1433 $origin = $item['origin'];
1437 /// @todo add a field "pcid" in the contact table that referrs to the public contact id.
1438 $owner = DBA::selectFirst('contact', ['url', 'nurl', 'alias'], ['id' => $parent['owner-id']]);
1439 if (!DBA::isResult($owner)) {
1443 $condition = ['nurl' => $owner['nurl'], 'rel' => [Contact::SHARING, Contact::FRIEND]];
1444 $contacts = DBA::select('contact', ['uid'], $condition);
1445 while ($contact = DBA::fetch($contacts)) {
1446 if ($contact['uid'] == 0) {
1450 $users[$contact['uid']] = $contact['uid'];
1452 DBA::close($contacts);
1454 $condition = ['alias' => $owner['url'], 'rel' => [Contact::SHARING, Contact::FRIEND]];
1455 $contacts = DBA::select('contact', ['uid'], $condition);
1456 while ($contact = DBA::fetch($contacts)) {
1457 if ($contact['uid'] == 0) {
1461 $users[$contact['uid']] = $contact['uid'];
1463 DBA::close($contacts);
1465 if (!empty($owner['alias'])) {
1466 $condition = ['nurl' => Strings::normaliseLink($owner['alias']), 'rel' => [Contact::SHARING, Contact::FRIEND]];
1467 $contacts = DBA::select('contact', ['uid'], $condition);
1468 while ($contact = DBA::fetch($contacts)) {
1469 if ($contact['uid'] == 0) {
1473 $users[$contact['uid']] = $contact['uid'];
1475 DBA::close($contacts);
1480 if ($item['uri-id'] != $item['parent-uri-id']) {
1481 $parents = Post::select(['uid', 'origin'], ["`uri-id` = ? AND `uid` != 0", $item['parent-uri-id']]);
1482 while ($parent = Post::fetch($parents)) {
1483 $users[$parent['uid']] = $parent['uid'];
1484 if ($parent['origin'] && !$origin) {
1485 $origin_uid = $parent['uid'];
1488 DBA::close($parents);
1491 foreach ($users as $uid) {
1492 if ($origin_uid == $uid) {
1493 $item['diaspora_signed_text'] = $signed_text;
1495 $item['post-reason'] = self::PR_DISTRIBUTE;
1496 self::storeForUser($item, $uid);
1501 * Store a public item defined by their URI-ID for the given users
1503 * @param integer $uri_id URI-ID of the given item
1504 * @param integer $uid The user that will receive the item entry
1505 * @param array $fields Additional fields to be stored
1506 * @param integer $source_uid User id of the source post
1507 * @return integer stored item id
1509 public static function storeForUserByUriId(int $uri_id, int $uid, array $fields = [], int $source_uid = 0): int
1511 if ($uid == $source_uid) {
1512 Logger::warning('target UID must not be be equal to the source UID', ['uri-id' => $uri_id, 'uid' => $uid]);
1516 $item = Post::selectFirst(array_merge(self::ITEM_FIELDLIST, ['protocol']), ['uri-id' => $uri_id, 'uid' => $source_uid]);
1517 if (!DBA::isResult($item)) {
1518 Logger::warning('Item could not be fetched', ['uri-id' => $uri_id, 'uid' => $source_uid]);
1522 if (($uid != 0) && ($item['gravity'] == GRAVITY_PARENT)) {
1523 $owner = User::getOwnerDataById($uid);
1524 if (($owner['contact-type'] == User::ACCOUNT_TYPE_COMMUNITY) && !Tag::isMentioned($uri_id, $owner['url'])) {
1525 Logger::info('Target user is a forum but is not mentioned here, thread will not be stored', ['uid' => $uid, 'uri-id' => $uri_id]);
1530 if (($source_uid == 0) && (($item['private'] == self::PRIVATE) || !in_array($item['network'], Protocol::FEDERATED))) {
1531 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']]);
1535 $item['post-reason'] = self::PR_STORED;
1537 $item = array_merge($item, $fields);
1539 $item['post-reason'] = self::getPostReason($item);
1541 $is_reshare = ($item['gravity'] == GRAVITY_ACTIVITY) && ($item['verb'] == Activity::ANNOUNCE);
1543 if (($uid != 0) && (($item['gravity'] == GRAVITY_PARENT) || $is_reshare) &&
1544 DI::pConfig()->get($uid, 'system', 'accept_only_sharer') == self::COMPLETION_NONE &&
1545 !in_array($item['post-reason'], [self::PR_FOLLOWER, self::PR_TAG, self::PR_TO, self::PR_CC])) {
1546 Logger::info('Contact is not a follower, thread will not be stored', ['author' => $item['author-link'], 'uid' => $uid, 'uri-id' => $uri_id]);
1550 $causer = $item['causer-id'] ?: $item['author-id'];
1552 if (($uri_id != $item['parent-uri-id']) && ($item['gravity'] == GRAVITY_COMMENT) && !Post::exists(['uri-id' => $item['parent-uri-id'], 'uid' => $uid])) {
1553 if (!self::fetchParent($item['parent-uri-id'], $uid, $causer)) {
1554 Logger::info('Parent post had not been added', ['uri-id' => $item['parent-uri-id'], 'uid' => $uid, 'causer' => $causer]);
1557 Logger::info('Fetched parent post', ['uri-id' => $item['parent-uri-id'], 'uid' => $uid, 'causer' => $causer]);
1558 } elseif (($uri_id != $item['thr-parent-id']) && $is_reshare && !Post::exists(['uri-id' => $item['thr-parent-id'], 'uid' => $uid])) {
1559 if (!self::fetchParent($item['thr-parent-id'], $uid, $causer)) {
1560 Logger::info('Thread parent had not been added', ['uri-id' => $item['thr-parent-id'], 'uid' => $uid, 'causer' => $causer]);
1563 Logger::info('Fetched thread parent', ['uri-id' => $item['thr-parent-id'], 'uid' => $uid, 'causer' => $causer]);
1566 $stored = self::storeForUser($item, $uid);
1567 Logger::info('Item stored for user', ['uri-id' => $item['uri-id'], 'uid' => $uid, 'causer' => $causer, 'source-uid' => $source_uid, 'stored' => $stored]);
1572 * Fetch the parent with the given uri-id
1574 * @param integer $uri_id
1575 * @param integer $uid
1576 * @param integer $causer
1580 private static function fetchParent(int $uri_id, int $uid, int $causer): int
1582 // Fetch the origin user for the post
1583 $origin_uid = self::GetOriginUidForUriId($uri_id, $uid);
1584 if (is_null($origin_uid)) {
1585 Logger::info('Origin item was not found', ['uid' => $uid, 'uri-id' => $uri_id]);
1589 return self::storeForUserByUriId($uri_id, $uid, ['causer-id' => $causer, 'post-reason' => self::PR_FETCHED], $origin_uid);
1593 * Returns the origin uid of a post if the given user is allowed to see it.
1599 private static function GetOriginUidForUriId(int $uriid, int $uid)
1601 if (Post::exists(['uri-id' => $uriid, 'uid' => $uid])) {
1605 $post = Post::selectFirst(['uid', 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid', 'private'], ['uri-id' => $uriid, 'origin' => true]);
1606 if (!empty($post)) {
1607 if (in_array($post['private'], [Item::PUBLIC, Item::UNLISTED])) {
1608 return $post['uid'];
1611 $pcid = Contact::getPublicIdByUserId($uid);
1616 foreach (Item::enumeratePermissions($post, true) as $receiver) {
1617 if ($receiver == $pcid) {
1618 return $post['uid'];
1625 if (Post::exists(['uri-id' => $uriid, 'uid' => 0])) {
1629 // When the post belongs to a a forum then all forum users are allowed to access it
1630 foreach (Tag::getByURIId($uriid, [Tag::MENTION, Tag::EXCLUSIVE_MENTION]) as $tag) {
1631 if (DBA::exists('contact', ['uid' => $uid, 'nurl' => Strings::normaliseLink($tag['url']), 'contact-type' => Contact::TYPE_COMMUNITY])) {
1632 $target_uid = User::getIdForURL($tag['url']);
1633 if (!empty($target_uid)) {
1643 * Store a public item array for the given users
1645 * @param array $item The item entry that will be stored
1646 * @param integer $uid The user that will receive the item entry
1647 * @return integer stored item id
1648 * @throws \Exception
1650 private static function storeForUser(array $item, int $uid): int
1652 $post = Post::selectFirst(['id'], ['uri-id' => $item['uri-id'], 'uid' => $uid]);
1653 if (!empty($post['id'])) {
1654 if (!empty($item['event-id'])) {
1655 $event_post = Post::selectFirst(['event-id'], ['uri-id' => $item['uri-id'], 'uid' => $uid]);
1656 if (!empty($event_post['event-id'])) {
1657 $event = DBA::selectFirst('event', ['edited', 'start', 'finish', 'summary', 'desc', 'location', 'nofinish', 'adjust'], ['id' => $item['event-id']]);
1658 if (!empty($event)) {
1659 // We aren't using "Event::store" here, since we don't want to trigger any further action
1660 $ret = DBA::update('event', $event, ['id' => $event_post['event-id']]);
1661 Logger::info('Event updated', ['uid' => $uid, 'source-event' => $item['event-id'], 'target-event' => $event_post['event-id'], 'ret' => $ret]);
1665 Logger::info('Item already exists', ['uri-id' => $item['uri-id'], 'uid' => $uid, 'id' => $post['id']]);
1669 // Data from the "post-user" table
1671 unset($item['mention']);
1672 unset($item['starred']);
1673 unset($item['unseen']);
1674 unset($item['psid']);
1675 unset($item['pinned']);
1676 unset($item['ignored']);
1677 unset($item['pubmail']);
1678 unset($item['event-id']);
1679 unset($item['hidden']);
1680 unset($item['notification-type']);
1682 // Data from the "post-delivery-data" table
1683 unset($item['postopts']);
1684 unset($item['inform']);
1686 $item['uid'] = $uid;
1687 $item['origin'] = 0;
1690 $item['contact-id'] = self::contactId($item);
1693 if ($item['gravity'] == GRAVITY_PARENT) {
1694 $contact = DBA::selectFirst('contact', [], ['id' => $item['contact-id'], 'self' => false]);
1695 if (DBA::isResult($contact)) {
1696 $notify = self::isRemoteSelf($contact, $item);
1700 $distributed = self::insert($item, $notify);
1702 if (!$distributed) {
1703 Logger::info("Distributed item wasn't stored", ['uri-id' => $item['uri-id'], 'user' => $uid]);
1705 Logger::info('Distributed item was stored', ['uri-id' => $item['uri-id'], 'user' => $uid, 'stored' => $distributed]);
1707 return $distributed;
1711 * Add a shadow entry for a given item id that is a thread starter
1713 * We store every public item entry additionally with the user id "0".
1714 * This is used for the community page and for the search.
1715 * It is planned that in the future we will store public item entries only once.
1717 * @param integer $itemid Item ID that should be added
1718 * @throws \Exception
1720 private static function addShadow(int $itemid)
1722 $fields = ['uid', 'private', 'visible', 'deleted', 'network', 'uri-id'];
1723 $condition = ['id' => $itemid, 'gravity' => GRAVITY_PARENT];
1724 $item = Post::selectFirst($fields, $condition);
1726 if (!DBA::isResult($item)) {
1730 // is it already a copy?
1731 if (($itemid == 0) || ($item['uid'] == 0)) {
1735 // Is it a visible public post?
1736 if (!$item["visible"] || $item["deleted"] || ($item["private"] == self::PRIVATE)) {
1740 // is it an entry from a connector? Only add an entry for natively connected networks
1741 if (!in_array($item["network"], array_merge(Protocol::FEDERATED ,['']))) {
1745 if (Post::exists(['uri-id' => $item['uri-id'], 'uid' => 0])) {
1749 $item = Post::selectFirst(array_merge(self::ITEM_FIELDLIST, ['protocol']), ['id' => $itemid]);
1751 if (DBA::isResult($item)) {
1752 // Preparing public shadow (removing user specific data)
1755 unset($item['parent']);
1756 unset($item['wall']);
1757 unset($item['mention']);
1758 unset($item['origin']);
1759 unset($item['starred']);
1760 unset($item['postopts']);
1761 unset($item['inform']);
1762 unset($item['post-reason']);
1763 if ($item['uri-id'] == $item['parent-uri-id']) {
1764 $item['contact-id'] = $item['owner-id'];
1766 $item['contact-id'] = $item['author-id'];
1769 $public_shadow = self::insert($item);
1771 Logger::info('Stored public shadow', ['thread' => $itemid, 'id' => $public_shadow]);
1776 * Add a shadow entry for a given item id that is a comment
1778 * This function does the same like the function above - but for comments
1780 * @param integer $itemid Item ID that should be added
1781 * @throws \Exception
1783 private static function addShadowPost(int $itemid)
1785 $item = Post::selectFirst(array_merge(self::ITEM_FIELDLIST, ['protocol']), ['id' => $itemid]);
1786 if (!DBA::isResult($item)) {
1790 // Is it a toplevel post?
1791 if ($item['gravity'] == GRAVITY_PARENT) {
1792 self::addShadow($itemid);
1796 // Is this a shadow entry?
1797 if ($item['uid'] == 0) {
1801 // Is there a shadow parent?
1802 if (!Post::exists(['uri-id' => $item['parent-uri-id'], 'uid' => 0])) {
1806 // Is there already a shadow entry?
1807 if (Post::exists(['uri-id' => $item['uri-id'], 'uid' => 0])) {
1811 // Save "origin" and "parent" state
1812 $origin = $item['origin'];
1813 $parent = $item['parent'];
1815 // Preparing public shadow (removing user specific data)
1818 unset($item['parent']);
1819 unset($item['wall']);
1820 unset($item['mention']);
1821 unset($item['origin']);
1822 unset($item['starred']);
1823 unset($item['postopts']);
1824 unset($item['inform']);
1825 unset($item['post-reason']);
1826 $item['contact-id'] = Contact::getIdForURL($item['author-link']);
1828 $public_shadow = self::insert($item);
1830 Logger::info('Stored public shadow', ['uri-id' => $item['uri-id'], 'id' => $public_shadow]);
1832 // If this was a comment to a Diaspora post we don't get our comment back.
1833 // This means that we have to distribute the comment by ourselves.
1834 if ($origin && Post::exists(['id' => $parent, 'network' => Protocol::DIASPORA])) {
1835 self::distribute($public_shadow);
1840 * Adds a language specification in a "language" element of given $arr.
1841 * Expects "body" element to exist in $arr.
1843 * @param array $item
1844 * @return string detected language
1845 * @throws \Text_LanguageDetect_Exception
1847 private static function getLanguage(array $item): string
1849 if (!empty($item['language'])) {
1850 return $item['language'];
1853 if (!in_array($item['gravity'], [GRAVITY_PARENT, GRAVITY_COMMENT]) || empty($item['body'])) {
1857 // Convert attachments to links
1858 $naked_body = BBCode::removeAttachment($item['body']);
1859 if (empty($naked_body)) {
1863 // Remove links and pictures
1864 $naked_body = BBCode::removeLinks($naked_body);
1866 // Convert the title and the body to plain text
1867 $naked_body = trim($item['title'] . "\n" . BBCode::toPlaintext($naked_body));
1869 // Remove possibly remaining links
1870 $naked_body = preg_replace(Strings::autoLinkRegEx(), '', $naked_body);
1872 if (empty($naked_body)) {
1876 $naked_body = self::getDominantLanguage($naked_body);
1878 $availableLanguages = DI::l10n()->getAvailableLanguages();
1879 // See https://github.com/friendica/friendica/issues/10511
1880 // Persian is manually added to language detection until a persian translation is provided for the interface, at
1881 // which point it will be automatically available through `getAvailableLanguages()` and this should be removed.
1882 $availableLanguages['fa'] = 'fa';
1884 $ld = new Language(array_keys($availableLanguages));
1885 $languages = $ld->detect($naked_body)->limit(0, 3)->close();
1886 if (is_array($languages)) {
1887 return json_encode($languages);
1894 * Check if latin or non latin are dominant in the body and only return the dominant one
1896 * @param string $body
1899 private static function getDominantLanguage(string $body): string
1903 for ($i = 0; $i < mb_strlen($body); $i++) {
1904 $character = mb_substr($body, $i, 1);
1905 $ord = mb_ord($character);
1907 // We add the most common characters to both strings.
1908 if (($ord <= 64) || ($ord >= 91 && $ord <= 96) || ($ord >= 123 && $ord <= 191) || in_array($ord, [215, 247]) || ($ord >= 697 && $ord <= 735) || ($ord > 65535)) {
1909 $latin .= $character;
1910 $non_latin .= $character;
1911 } elseif ($ord < 768) {
1912 $latin .= $character;
1914 $non_latin .= $character;
1917 return (mb_strlen($latin) > mb_strlen($non_latin)) ? $latin : $non_latin;
1920 public static function getLanguageMessage(array $item): string
1922 $iso639 = new \Matriphe\ISO639\ISO639;
1924 $used_languages = '';
1925 foreach (json_decode($item['language'], true) as $language => $reliability) {
1926 $used_languages .= $iso639->languageByCode1($language) . ' (' . $language . "): " . number_format($reliability, 5) . '\n';
1928 $used_languages = DI::l10n()->t('Detected languages in this post:\n%s', $used_languages);
1929 return $used_languages;
1933 * Creates an unique guid out of a given uri.
1934 * This function is used for messages outside the fediverse (Connector posts, feeds, Mails, ...)
1935 * Posts that are created on this system are using System::createUUID.
1936 * Received ActivityPub posts are using Processor::getGUIDByURL.
1938 * @param string $uri uri of an item entry
1939 * @param string|null $host hostname for the GUID prefix
1940 * @return string Unique guid
1942 public static function guidFromUri(string $uri, string $host = null): string
1944 // Our regular guid routine is using this kind of prefix as well
1945 // We have to avoid that different routines could accidentally create the same value
1946 $parsed = parse_url($uri);
1948 // Remove the scheme to make sure that "https" and "http" doesn't make a difference
1949 unset($parsed['scheme']);
1951 // Glue it together to be able to make a hash from it
1952 $host_id = implode('/', $parsed);
1954 // Use a mixture of several hashes to provide some GUID like experience
1955 return hash('crc32', $host) . '-'. hash('joaat', $host_id) . '-'. hash('fnv164', $host_id);
1959 * generate an unique URI
1961 * @param string $guid An existing GUID (Otherwise it will be generated)
1964 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1966 public static function newURI(string $guid = ''): string
1969 $guid = System::createUUID();
1972 return DI::baseUrl()->get() . '/objects/' . $guid;
1976 * Set "success_update" and "last-item" to the date of the last time we heard from this contact
1978 * This can be used to filter for inactive contacts.
1979 * Only do this for public postings to avoid privacy problems, since poco data is public.
1980 * Don't set this value if it isn't from the owner (could be an author that we don't know)
1982 * @param array $arr Contains the just posted item record
1983 * @throws \Exception
1985 private static function updateContact(array $arr)
1987 // Unarchive the author
1988 $contact = DBA::selectFirst('contact', [], ['id' => $arr["author-id"]]);
1989 if (DBA::isResult($contact)) {
1990 Contact::unmarkForArchival($contact);
1993 // Unarchive the contact if it's not our own contact
1994 $contact = DBA::selectFirst('contact', [], ['id' => $arr["contact-id"], 'self' => false]);
1995 if (DBA::isResult($contact)) {
1996 Contact::unmarkForArchival($contact);
1999 /// @todo On private posts we could obfuscate the date
2000 $update = ($arr['private'] != self::PRIVATE) || in_array($arr['network'], Protocol::FEDERATED);
2002 // Is it a forum? Then we don't care about the rules from above
2003 if (!$update && in_array($arr["network"], [Protocol::ACTIVITYPUB, Protocol::DFRN]) && ($arr["parent-uri-id"] === $arr["uri-id"])) {
2004 if (DBA::exists('contact', ['id' => $arr['contact-id'], 'forum' => true])) {
2010 // The "self" contact id is used (for example in the connectors) when the contact is unknown
2011 // So we have to ensure to only update the last item when it had been our own post,
2012 // or it had been done by a "regular" contact.
2013 if (!empty($arr['wall'])) {
2014 $condition = ['id' => $arr['contact-id']];
2016 $condition = ['id' => $arr['contact-id'], 'self' => false];
2018 Contact::update(['failed' => false, 'local-data' => true, 'success_update' => $arr['received'], 'last-item' => $arr['received']], $condition);
2020 // Now do the same for the system wide contacts with uid=0
2021 if ($arr['private'] != self::PRIVATE) {
2022 Contact::update(['failed' => false, 'local-data' => true, 'success_update' => $arr['received'], 'last-item' => $arr['received']],
2023 ['id' => $arr['owner-id']]);
2025 if ($arr['owner-id'] != $arr['author-id']) {
2026 Contact::update(['failed' => false, 'local-data' => true, 'success_update' => $arr['received'], 'last-item' => $arr['received']],
2027 ['id' => $arr['author-id']]);
2032 public static function setHashtags(string $body): string
2034 $body = BBCode::performWithEscapedTags($body, ['noparse', 'pre', 'code', 'img'], function ($body) {
2035 $tags = BBCode::getTags($body);
2038 if (!count($tags)) {
2042 // This sorting is important when there are hashtags that are part of other hashtags
2043 // Otherwise there could be problems with hashtags like #test and #test2
2044 // Because of this we are sorting from the longest to the shortest tag.
2045 usort($tags, function ($a, $b) {
2046 return strlen($b) <=> strlen($a);
2049 $URLSearchString = "^\[\]";
2051 // All hashtags should point to the home server if "local_tags" is activated
2052 if (DI::config()->get('system', 'local_tags')) {
2053 $body = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
2054 "#[url=" . DI::baseUrl() . "/search?tag=$2]$2[/url]", $body);
2057 // mask hashtags inside of url, bookmarks and attachments to avoid urls in urls
2058 $body = preg_replace_callback("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
2060 return ("[url=" . str_replace("#", "#", $match[1]) . "]" . str_replace("#", "#", $match[2]) . "[/url]");
2063 $body = preg_replace_callback("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism",
2065 return ("[bookmark=" . str_replace("#", "#", $match[1]) . "]" . str_replace("#", "#", $match[2]) . "[/bookmark]");
2068 $body = preg_replace_callback("/\[attachment (.*?)\](.*?)\[\/attachment\]/ism",
2070 return ("[attachment " . str_replace("#", "#", $match[1]) . "]" . $match[2] . "[/attachment]");
2073 // Repair recursive urls
2074 $body = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
2077 foreach ($tags as $tag) {
2078 if ((strpos($tag, '#') !== 0) || strpos($tag, '[url=') || strlen($tag) < 2 || $tag[1] == '#') {
2082 $basetag = str_replace('_', ' ', substr($tag, 1));
2083 $newtag = '#[url=' . DI::baseUrl() . '/search?tag=' . $basetag . ']' . $basetag . '[/url]';
2085 $body = str_replace($tag, $newtag, $body);
2088 // Convert back the masked hashtags
2089 $body = str_replace("#", "#", $body);
2098 * look for mention tags and setup a second delivery chain for forum/community posts if appropriate
2101 * @param int $item_id
2102 * @return boolean true if item was deleted, else false
2103 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2104 * @throws \ImagickException
2106 private static function tagDeliver(int $uid, int $item_id): bool
2110 $owner = User::getOwnerDataById($uid);
2111 if (!DBA::isResult($owner)) {
2112 Logger::warning('User not found, quitting here.', ['uid' => $uid]);
2116 if ($owner['contact-type'] != User::ACCOUNT_TYPE_COMMUNITY) {
2117 Logger::debug('Owner is no community, quitting here.', ['uid' => $uid, 'id' => $item_id]);
2121 $item = Post::selectFirst(self::ITEM_FIELDLIST, ['id' => $item_id, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT], 'origin' => false]);
2122 if (!DBA::isResult($item)) {
2123 Logger::debug('Post is an activity or origin or not found at all, quitting here.', ['id' => $item_id]);
2127 if ($item['gravity'] == GRAVITY_PARENT) {
2128 if (Tag::isMentioned($item['uri-id'], $owner['url'])) {
2129 Logger::info('Mention found in tag.', ['uri' => $item['uri'], 'uid' => $uid, 'id' => $item_id, 'uri-id' => $item['uri-id'], 'guid' => $item['guid']]);
2131 Logger::info('Top-level post without mention is deleted.', ['uri' => $item['uri'], $uid, 'id' => $item_id, 'uri-id' => $item['uri-id'], 'guid' => $item['guid']]);
2132 Post\User::delete(['uri-id' => $item['uri-id'], 'uid' => $item['uid']]);
2136 $arr = ['item' => $item, 'user' => $owner];
2138 Hook::callAll('tagged', $arr);
2140 if (Tag::isMentioned($item['parent-uri-id'], $owner['url'])) {
2141 Logger::info('Mention found in parent tag.', ['uri' => $item['uri'], 'uid' => $uid, 'id' => $item_id, 'uri-id' => $item['uri-id'], 'guid' => $item['guid']]);
2143 Logger::debug('No mentions found in parent, quitting here.', ['id' => $item_id, 'uri-id' => $item['uri-id'], 'guid' => $item['guid']]);
2148 Logger::info('Community post will be distributed', ['uri' => $item['uri'], 'uid' => $uid, 'id' => $item_id, 'uri-id' => $item['uri-id'], 'guid' => $item['guid']]);
2150 if ($owner['page-flags'] == User::PAGE_FLAGS_PRVGROUP) {
2152 $allow_gid = '<' . Group::FOLLOWERS . '>';
2155 self::performActivity($item['id'], 'announce', $uid, $allow_cid, $allow_gid, $deny_cid, $deny_gid);
2157 self::performActivity($item['id'], 'announce', $uid);
2160 Logger::info('Community post had been distributed', ['uri' => $item['uri'], 'uid' => $uid, 'id' => $item_id, 'uri-id' => $item['uri-id'], 'guid' => $item['guid']]);
2165 * Automatically reshare the item if the "remote_self" option is selected
2167 * @param array $item
2170 private static function autoReshare(array $item)
2172 if ($item['gravity'] != GRAVITY_PARENT) {
2176 if (!DBA::exists('contact', ['id' => $item['contact-id'], 'remote_self' => Contact::MIRROR_NATIVE_RESHARE])) {
2180 if (!in_array($item['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN])) {
2184 Logger::info('Automatically reshare item', ['uid' => $item['uid'], 'id' => $item['id'], 'guid' => $item['guid'], 'uri-id' => $item['uri-id']]);
2186 self::performActivity($item['id'], 'announce', $item['uid']);
2189 public static function isRemoteSelf(array $contact, array &$datarray): bool
2191 if (!$contact['remote_self']) {
2195 // Prevent the forwarding of posts that are forwarded
2196 if (!empty($datarray["extid"]) && ($datarray["extid"] == Protocol::DFRN)) {
2197 Logger::info('Already forwarded');
2201 // Prevent to forward already forwarded posts
2202 if ($datarray["app"] == DI::baseUrl()->getHostname()) {
2203 Logger::info('Already forwarded (second test)');
2207 // Only forward posts
2208 if ($datarray["verb"] != Activity::POST) {
2209 Logger::info('No post');
2213 if (($contact['network'] != Protocol::FEED) && ($datarray['private'] == self::PRIVATE)) {
2214 Logger::info('Not public');
2218 $datarray2 = $datarray;
2219 Logger::info('remote-self start', ['contact' => $contact['url'], 'remote_self'=> $contact['remote_self'], 'item' => $datarray]);
2220 if ($contact['remote_self'] == Contact::MIRROR_OWN_POST) {
2221 $self = DBA::selectFirst('contact', ['id', 'name', 'url', 'thumb'],
2222 ['uid' => $contact['uid'], 'self' => true]);
2223 if (DBA::isResult($self)) {
2224 $datarray['contact-id'] = $self["id"];
2226 $datarray['owner-name'] = $self["name"];
2227 $datarray['owner-link'] = $self["url"];
2228 $datarray['owner-avatar'] = $self["thumb"];
2230 $datarray['author-name'] = $datarray['owner-name'];
2231 $datarray['author-link'] = $datarray['owner-link'];
2232 $datarray['author-avatar'] = $datarray['owner-avatar'];
2234 unset($datarray['edited']);
2236 unset($datarray['network']);
2237 unset($datarray['owner-id']);
2238 unset($datarray['author-id']);
2241 if ($contact['network'] != Protocol::FEED) {
2242 $old_uri_id = $datarray["uri-id"] ?? 0;
2243 $datarray["guid"] = System::createUUID();
2244 unset($datarray["plink"]);
2245 $datarray["uri"] = self::newURI($datarray["guid"]);
2246 $datarray["uri-id"] = ItemURI::getIdByURI($datarray["uri"]);
2247 $datarray["extid"] = Protocol::DFRN;
2248 $urlpart = parse_url($datarray2['author-link']);
2249 $datarray["app"] = $urlpart["host"];
2250 if (!empty($old_uri_id)) {
2251 Post\Media::copy($old_uri_id, $datarray["uri-id"]);
2254 unset($datarray["parent-uri"]);
2255 unset($datarray["thr-parent"]);
2257 $datarray['private'] = self::PUBLIC;
2261 if ($contact['network'] != Protocol::FEED) {
2262 // Store the original post
2263 $result = self::insert($datarray2);
2264 Logger::info('remote-self post original item', ['contact' => $contact['url'], 'result'=> $result, 'item' => $datarray2]);
2266 $datarray["app"] = "Feed";
2270 return (bool)$result;
2277 * @param array $item
2280 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2281 * @throws \ImagickException
2283 public static function fixPrivatePhotos(string $s, int $uid, array $item = null, int $cid = 0): string
2285 if (DI::config()->get('system', 'disable_embedded')) {
2289 Logger::info('check for photos');
2290 $site = substr(DI::baseUrl(), strpos(DI::baseUrl(), '://'));
2295 $img_start = strpos($orig_body, '[img');
2296 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
2297 $img_len = ($img_start !== false ? strpos(substr($orig_body, $img_start + $img_st_close + 1), '[/img]') : false);
2299 while (($img_st_close !== false) && ($img_len !== false)) {
2300 $img_st_close++; // make it point to AFTER the closing bracket
2301 $image = substr($orig_body, $img_start + $img_st_close, $img_len);
2303 Logger::info('found photo', ['image' => $image]);
2305 if (stristr($image, $site . '/photo/')) {
2306 // Only embed locally hosted photos
2308 $i = basename($image);
2309 $i = str_replace(['.jpg', '.png', '.gif'], ['', '', ''], $i);
2310 $x = strpos($i, '-');
2313 $res = substr($i, $x + 1);
2314 $i = substr($i, 0, $x);
2315 $photo = Photo::getPhotoForUser($uid, $i, $res);
2316 if (DBA::isResult($photo)) {
2318 * Check to see if we should replace this photo link with an embedded image
2319 * 1. No need to do so if the photo is public
2320 * 2. If there's a contact-id provided, see if they're in the access list
2321 * for the photo. If so, embed it.
2322 * 3. Otherwise, if we have an item, see if the item permissions match the photo
2323 * permissions, regardless of order but first check to see if they're an exact
2324 * match to save some processing overhead.
2326 if (self::hasPermissions($photo)) {
2328 $recips = self::enumeratePermissions($photo);
2329 if (in_array($cid, $recips)) {
2333 if (self::samePermissions($uid, $item, $photo)) {
2339 $photo_img = Photo::getImageForPhoto($photo);
2340 // If a custom width and height were specified, apply before embedding
2341 if (preg_match("/\[img\=([0-9]*)x([0-9]*)\]/is", substr($orig_body, $img_start, $img_st_close), $match)) {
2342 Logger::info('scaling photo');
2344 $width = intval($match[1]);
2345 $height = intval($match[2]);
2347 $photo_img->scaleDown(max($width, $height));
2350 $data = $photo_img->asString();
2351 $type = $photo_img->getType();
2353 Logger::info('replacing photo');
2354 $image = 'data:' . $type . ';base64,' . base64_encode($data);
2355 Logger::debug('replaced', ['image' => $image]);
2361 $new_body = $new_body . substr($orig_body, 0, $img_start + $img_st_close) . $image . '[/img]';
2362 $orig_body = substr($orig_body, $img_start + $img_st_close + $img_len + strlen('[/img]'));
2363 if ($orig_body === false) {
2367 $img_start = strpos($orig_body, '[img');
2368 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
2369 $img_len = ($img_start !== false ? strpos(substr($orig_body, $img_start + $img_st_close + 1), '[/img]') : false);
2372 $new_body = $new_body . $orig_body;
2377 private static function hasPermissions(array $obj)
2379 return !empty($obj['allow_cid']) || !empty($obj['allow_gid']) ||
2380 !empty($obj['deny_cid']) || !empty($obj['deny_gid']);
2383 // @TODO $uid is unused parameter
2384 private static function samePermissions($uid, array $obj1, array $obj2): bool
2386 // first part is easy. Check that these are exactly the same.
2387 if (($obj1['allow_cid'] == $obj2['allow_cid'])
2388 && ($obj1['allow_gid'] == $obj2['allow_gid'])
2389 && ($obj1['deny_cid'] == $obj2['deny_cid'])
2390 && ($obj1['deny_gid'] == $obj2['deny_gid'])) {
2394 // This is harder. Parse all the permissions and compare the resulting set.
2395 $recipients1 = self::enumeratePermissions($obj1);
2396 $recipients2 = self::enumeratePermissions($obj2);
2400 /// @TODO Comparison of arrays, maybe use array_diff_assoc() here?
2401 return ($recipients1 == $recipients2);
2405 * Returns an array of contact-ids that are allowed to see this object
2407 * @param array $obj Item array with at least uid, allow_cid, allow_gid, deny_cid and deny_gid
2408 * @param bool $check_dead Prunes unavailable contacts from the result
2410 * @throws \Exception
2412 public static function enumeratePermissions(array $obj, bool $check_dead = false): array
2414 $aclFormater = DI::aclFormatter();
2416 $allow_people = $aclFormater->expand($obj['allow_cid']);
2417 $allow_groups = Group::expand($obj['uid'], $aclFormater->expand($obj['allow_gid']), $check_dead);
2418 $deny_people = $aclFormater->expand($obj['deny_cid']);
2419 $deny_groups = Group::expand($obj['uid'], $aclFormater->expand($obj['deny_gid']), $check_dead);
2420 $recipients = array_unique(array_merge($allow_people, $allow_groups));
2421 $deny = array_unique(array_merge($deny_people, $deny_groups));
2422 $recipients = array_diff($recipients, $deny);
2426 public static function expire(int $uid, int $days, string $network = "", bool $force = false)
2428 if (!$uid || ($days < 1)) {
2432 $condition = ["`uid` = ? AND NOT `deleted` AND `gravity` = ?",
2433 $uid, GRAVITY_PARENT];
2436 * $expire_network_only = save your own wall posts
2437 * and just expire conversations started by others
2439 $expire_network_only = DI::pConfig()->get($uid, 'expire', 'network_only', false);
2441 if ($expire_network_only) {
2442 $condition[0] .= " AND NOT `wall`";
2445 if ($network != "") {
2446 $condition[0] .= " AND `network` = ?";
2447 $condition[] = $network;
2450 $condition[0] .= " AND `received` < ?";
2451 $condition[] = DateTimeFormat::utc('now - ' . $days . ' day');
2453 $items = Post::select(['resource-id', 'starred', 'id', 'post-type', 'uid', 'uri-id'], $condition);
2455 if (!DBA::isResult($items)) {
2459 $expire_items = DI::pConfig()->get($uid, 'expire', 'items', true);
2461 // Forcing expiring of items - but not notes and marked items
2463 $expire_items = true;
2466 $expire_notes = DI::pConfig()->get($uid, 'expire', 'notes', true);
2467 $expire_starred = DI::pConfig()->get($uid, 'expire', 'starred', true);
2468 $expire_photos = DI::pConfig()->get($uid, 'expire', 'photos', false);
2472 $priority = DI::config()->get('system', 'expire-notify-priority');
2474 while ($item = Post::fetch($items)) {
2475 // don't expire filed items
2476 if (DBA::exists('post-category', ['uri-id' => $item['uri-id'], 'uid' => $item['uid'], 'type' => Post\Category::FILE])) {
2480 // Only expire posts, not photos and photo comments
2482 if (!$expire_photos && !empty($item['resource-id'])) {
2484 } elseif (!$expire_starred && intval($item['starred'])) {
2486 } elseif (!$expire_notes && ($item['post-type'] == self::PT_PERSONAL_NOTE)) {
2488 } elseif (!$expire_items && ($item['post-type'] != self::PT_PERSONAL_NOTE)) {
2492 self::markForDeletionById($item['id'], $priority);
2497 Logger::notice('User ' . $uid . ": expired $expired items; expire items: $expire_items, expire notes: $expire_notes, expire starred: $expire_starred, expire photos: $expire_photos");
2500 public static function firstPostDate(int $uid, bool $wall = false)
2502 $user = User::getById($uid, ['register_date']);
2507 $condition = ["`uid` = ? AND `wall` = ? AND NOT `deleted` AND `visible` AND `received` >= ?",
2508 $uid, $wall, $user['register_date']];
2509 $params = ['order' => ['received' => false]];
2510 $thread = Post::selectFirstThread(['received'], $condition, $params);
2511 if (DBA::isResult($thread)) {
2512 $postdate = substr(DateTimeFormat::local($thread['received']), 0, 10);
2519 * add/remove activity to an item
2521 * Toggle activities as like,dislike,attend of an item
2523 * @param int $item_id
2524 * @param string $verb
2525 * Activity verb. One of
2526 * like, unlike, dislike, undislike, attendyes, unattendyes,
2527 * attendno, unattendno, attendmaybe, unattendmaybe,
2528 * announce, unannouce
2530 * @param string $allow_cid
2531 * @param string $allow_gid
2532 * @param string $deny_cid
2533 * @param string $deny_gid
2535 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2536 * @throws \ImagickException
2537 * @hook 'post_local_end'
2539 * 'post_id' => ID of posted item
2541 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
2547 Logger::notice('Start create activity', ['verb' => $verb, 'item' => $item_id, 'user' => $uid]);
2549 $item = Post::selectFirst(self::ITEM_FIELDLIST, ['id' => $item_id]);
2550 if (!DBA::isResult($item)) {
2551 Logger::warning('Post had not been fetched', ['id' => $item_id]);
2555 $uri_id = $item['uri-id'];
2557 if (!in_array($item['uid'], [0, $uid])) {
2561 if (!Post::exists(['uri-id' => $item['parent-uri-id'], 'uid' => $uid])) {
2562 $stored = self::storeForUserByUriId($item['parent-uri-id'], $uid, ['post-reason' => Item::PR_ACTIVITY]);
2563 if (($item['parent-uri-id'] == $item['uri-id']) && !empty($stored)) {
2564 $item = Post::selectFirst(self::ITEM_FIELDLIST, ['id' => $stored]);
2565 if (!DBA::isResult($item)) {
2566 Logger::info('Could not fetch just created item - should not happen', ['stored' => $stored, 'uid' => $uid, 'uri-id' => $uri_id]);
2572 // Retrieves the local post owner
2573 $owner = User::getOwnerDataById($uid);
2574 if (empty($owner)) {
2575 Logger::info('Empty owner for user', ['uid' => $uid]);
2579 // Retrieve the current logged in user's public contact
2580 $author_id = Contact::getPublicIdByUserId($uid);
2581 if (empty($author_id)) {
2582 Logger::info('Empty public contact');
2590 $activity = Activity::LIKE;
2594 $activity = Activity::DISLIKE;
2598 $activity = Activity::ATTEND;
2602 $activity = Activity::ATTENDNO;
2605 case 'unattendmaybe':
2606 $activity = Activity::ATTENDMAYBE;
2610 $activity = Activity::FOLLOW;
2614 $activity = Activity::ANNOUNCE;
2617 Logger::warning('unknown verb', ['verb' => $verb, 'item' => $item_id]);
2621 $mode = Strings::startsWith($verb, 'un') ? 'delete' : 'create';
2623 // Enable activity toggling instead of on/off
2624 $event_verb_flag = $activity === Activity::ATTEND || $activity === Activity::ATTENDNO || $activity === Activity::ATTENDMAYBE;
2626 // Look for an existing verb row
2627 // Event participation activities are mutually exclusive, only one of them can exist at all times.
2628 if ($event_verb_flag) {
2629 $verbs = [Activity::ATTEND, Activity::ATTENDNO, Activity::ATTENDMAYBE];
2631 // Translate to the index based activity index
2633 foreach ($verbs as $verb) {
2634 $vids[] = Verb::getID($verb);
2637 $vids = Verb::getID($activity);
2640 $condition = ['vid' => $vids, 'deleted' => false, 'gravity' => GRAVITY_ACTIVITY,
2641 'author-id' => $author_id, 'uid' => $item['uid'], 'thr-parent-id' => $uri_id];
2642 $like_item = Post::selectFirst(['id', 'guid', 'verb'], $condition);
2644 if (DBA::isResult($like_item)) {
2646 * Truth table for existing activities
2648 * | Inputs || Outputs |
2649 * |----------------------------||-------------------|
2650 * | Mode | Event | Same verb || Delete? | Return? |
2651 * |--------|-------|-----------||---------|---------|
2652 * | create | Yes | Yes || No | Yes |
2653 * | create | Yes | No || Yes | No |
2654 * | create | No | Yes || No | Yes |
2655 * | create | No | No || N/A†|
2656 * | delete | Yes | Yes || Yes | N/A‡ |
2657 * | delete | Yes | No || No | N/A‡ |
2658 * | delete | No | Yes || Yes | N/A‡ |
2659 * | delete | No | No || N/A†|
2660 * |--------|-------|-----------||---------|---------|
2661 * | A | B | C || A xor C | !B or C |
2663 * †Can't happen: It's impossible to find an existing non-event activity without
2664 * the same verb because we are only looking for this single verb.
2666 * ‡ The "mode = delete" is returning early whether an existing activity was found or not.
2668 if ($mode == 'create' xor $like_item['verb'] == $activity) {
2669 self::markForDeletionById($like_item['id']);
2672 if (!$event_verb_flag || $like_item['verb'] == $activity) {
2677 // No need to go further if we aren't creating anything
2678 if ($mode == 'delete') {
2682 $objtype = $item['resource-id'] ? Activity\ObjectType::IMAGE : Activity\ObjectType::NOTE;
2685 'guid' => System::createUUID(),
2686 'uri' => self::newURI(),
2688 'contact-id' => $owner['id'],
2689 'wall' => $item['wall'],
2691 'network' => Protocol::DFRN,
2692 'protocol' => Conversation::PARCEL_DIRECT,
2693 'direction' => Conversation::PUSH,
2694 'gravity' => GRAVITY_ACTIVITY,
2695 'parent' => $item['id'],
2696 'thr-parent' => $item['uri'],
2697 'owner-id' => $author_id,
2698 'author-id' => $author_id,
2699 'body' => $activity,
2700 'verb' => $activity,
2701 'object-type' => $objtype,
2702 'allow_cid' => $allow_cid ?? $item['allow_cid'],
2703 'allow_gid' => $allow_gid ?? $item['allow_gid'],
2704 'deny_cid' => $deny_cid ?? $item['deny_cid'],
2705 'deny_gid' => $deny_gid ?? $item['deny_gid'],
2710 if (in_array($activity, [Activity::LIKE, Activity::DISLIKE])) {
2711 $signed = Diaspora::createLikeSignature($uid, $new_item);
2712 if (!empty($signed)) {
2713 $new_item['diaspora_signed_text'] = json_encode($signed);
2717 self::insert($new_item, true);
2719 // If the parent item isn't visible then set it to visible
2720 // @todo Check if this is still needed
2721 if (!$item['visible']) {
2722 self::update(['visible' => true], ['id' => $item['id']]);
2728 * Fetch the SQL condition for the given user id
2730 * @param integer $owner_id User ID for which the permissions should be fetched
2731 * @return array condition
2733 public static function getPermissionsConditionArrayByUserId(int $owner_id): array
2735 $local_user = local_user();
2736 $remote_user = Session::getRemoteContactID($owner_id);
2738 // default permissions - anonymous user
2739 $condition = ["`private` != ?", self::PRIVATE];
2741 if ($local_user && ($local_user == $owner_id)) {
2742 // Profile owner - everything is visible
2744 } elseif ($remote_user) {
2745 // Authenticated visitor - fetch the matching permissionsets
2746 $permissionSets = DI::permissionSet()->selectByContactId($remote_user, $owner_id);
2748 $condition = ["(`private` != ? OR (`private` = ? AND `wall`
2749 AND `psid` IN (" . implode(', ', array_fill(0, count($set), '?')) . ")))",
2750 self::PRIVATE, self::PRIVATE];
2751 $condition = array_merge($condition, $permissionSets->column('id'));
2759 * Get a permission SQL string for the given user
2761 * @param int $owner_id
2762 * @param string $table
2765 public static function getPermissionsSQLByUserId(int $owner_id, string $table = ''): string
2767 $local_user = local_user();
2768 $remote_user = Session::getRemoteContactID($owner_id);
2770 if (!empty($table)) {
2771 $table = DBA::quoteIdentifier($table) . '.';
2775 * Construct permissions
2777 * default permissions - anonymous user
2779 $sql = sprintf(" AND " . $table . "`private` != %d", self::PRIVATE);
2781 // Profile owner - everything is visible
2782 if ($local_user && ($local_user == $owner_id)) {
2784 } elseif ($remote_user) {
2786 * Authenticated visitor. Unless pre-verified,
2787 * check that the contact belongs to this $owner_id
2788 * and load the groups the visitor belongs to.
2789 * If pre-verified, the caller is expected to have already
2790 * done this and passed the groups into this function.
2792 $permissionSets = DI::permissionSet()->selectByContactId($remote_user, $owner_id);
2795 $sql_set = sprintf(" OR (" . $table . "`private` = %d AND " . $table . "`wall` AND " . $table . "`psid` IN (", self::PRIVATE) . implode(',', $permissionSets->column('id')) . "))";
2800 $sql = sprintf(" AND (" . $table . "`private` != %d", self::PRIVATE) . $sql_set . ")";
2807 * get translated item type
2809 * @param array $item
2810 * @param \Friendica\Core\L10n $l10n
2813 public static function postType(array $item, \Friendica\Core\L10n $l10n): string
2815 if (!empty($item['event-id'])) {
2816 return $l10n->t('event');
2817 } elseif (!empty($item['resource-id'])) {
2818 return $l10n->t('photo');
2819 } elseif ($item['gravity'] == GRAVITY_ACTIVITY) {
2820 return $l10n->t('activity');
2821 } elseif ($item['gravity'] == GRAVITY_COMMENT) {
2822 return $l10n->t('comment');
2825 return $l10n->t('post');
2829 * Sets the "rendered-html" field of the provided item
2831 * Body is preserved to avoid side-effects as we modify it just-in-time for spoilers and private image links
2833 * @param array $item
2835 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2836 * @todo Remove reference, simply return "rendered-html" and "rendered-hash"
2838 private static function putInCache(&$item)
2840 // Save original body to prevent addons to modify it
2841 $body = $item['body'];
2843 $rendered_hash = $item['rendered-hash'] ?? '';
2844 $rendered_html = $item['rendered-html'] ?? '';
2846 if ($rendered_hash == ''
2847 || $rendered_html == ''
2848 || $rendered_hash != hash('md5', BBCode::VERSION . '::' . $body)
2849 || DI::config()->get('system', 'ignore_cache')
2851 $item['rendered-html'] = BBCode::convertForUriId($item['uri-id'], $item['body']);
2852 $item['rendered-hash'] = hash('md5', BBCode::VERSION . '::' . $body);
2854 $hook_data = ['item' => $item, 'rendered-html' => $item['rendered-html'], 'rendered-hash' => $item['rendered-hash']];
2855 Hook::callAll('put_item_in_cache', $hook_data);
2856 $item['rendered-html'] = $hook_data['rendered-html'];
2857 $item['rendered-hash'] = $hook_data['rendered-hash'];
2860 // Update if the generated values differ from the existing ones
2861 if ((($rendered_hash != $item['rendered-hash']) || ($rendered_html != $item['rendered-html'])) && !empty($item['id'])) {
2864 'rendered-html' => $item['rendered-html'],
2865 'rendered-hash' => $item['rendered-hash']
2867 ['id' => $item['id']]
2872 $item['body'] = $body;
2876 * Given an item array, convert the body element from bbcode to html and add smilie icons.
2877 * If attach is true, also add icons for item attachments.
2879 * @param array $item Record from item table
2880 * @param boolean $attach If true, add icons for item attachments as well
2881 * @param boolean $is_preview Whether this is a preview
2882 * @param boolean $only_cache Whether only cached HTML should be updated
2883 * @return string item body html
2884 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2885 * @throws \ImagickException
2886 * @hook prepare_body_init item array before any work
2887 * @hook prepare_body_content_filter ('item'=>item array, 'filter_reasons'=>string array) before first bbcode to html
2888 * @hook prepare_body ('item'=>item array, 'html'=>body string, 'is_preview'=>boolean, 'filter_reasons'=>string array) after first bbcode to html
2889 * @hook prepare_body_final ('item'=>item array, 'html'=>body string) after attach icons and blockquote special case handling (spoiler, author)
2891 public static function prepareBody(array &$item, bool $attach = false, bool $is_preview = false, bool $only_cache = false): string
2894 Hook::callAll('prepare_body_init', $item);
2896 // In order to provide theme developers more possibilities, event items
2897 // are treated differently.
2898 if ($item['object-type'] === Activity\ObjectType::EVENT && isset($item['event-id'])) {
2899 $ev = Event::getItemHTML($item);
2903 $tags = Tag::populateFromItem($item);
2905 $item['tags'] = $tags['tags'];
2906 $item['hashtags'] = $tags['hashtags'];
2907 $item['mentions'] = $tags['mentions'];
2909 $body = $item['body'] ?? '';
2910 $shared = BBCode::fetchShareAttributes($body);
2911 if (!empty($shared['guid'])) {
2912 $shared_item = Post::selectFirst(['uri-id', 'plink', 'has-media'], ['guid' => $shared['guid']]);
2913 $shared_uri_id = $shared_item['uri-id'] ?? 0;
2914 $shared_links = [strtolower($shared_item['plink'] ?? '')];
2915 $shared_attachments = Post\Media::splitAttachments($shared_uri_id, $shared['guid'], [], $shared_item['has-media'] ?? false);
2916 $shared_links = array_merge($shared_links, array_column($shared_attachments['visual'], 'url'));
2917 $shared_links = array_merge($shared_links, array_column($shared_attachments['link'], 'url'));
2918 $shared_links = array_merge($shared_links, array_column($shared_attachments['additional'], 'url'));
2919 $item['body'] = self::replaceVisualAttachments($shared_attachments, $item['body']);
2925 $attachments = Post\Media::splitAttachments($item['uri-id'], $item['guid'] ?? '', $shared_links, $item['has-media'] ?? false);
2926 $item['body'] = self::replaceVisualAttachments($attachments, $item['body'] ?? '');
2928 $item['body'] = preg_replace("/\s*\[attachment .*?\].*?\[\/attachment\]\s*/ism", "\n", $item['body']);
2929 self::putInCache($item);
2930 $item['body'] = $body;
2931 $s = $item["rendered-html"];
2937 // Compile eventual content filter reasons
2938 $filter_reasons = [];
2939 if (!$is_preview && public_contact() != $item['author-id']) {
2940 if (!empty($item['content-warning']) && (!local_user() || !DI::pConfig()->get(local_user(), 'system', 'disable_cw', false))) {
2941 $filter_reasons[] = DI::l10n()->t('Content warning: %s', $item['content-warning']);
2944 $item['attachments'] = $attachments;
2948 'filter_reasons' => $filter_reasons
2950 Hook::callAll('prepare_body_content_filter', $hook_data);
2951 $filter_reasons = $hook_data['filter_reasons'];
2958 'preview' => $is_preview,
2959 'filter_reasons' => $filter_reasons
2961 Hook::callAll('prepare_body', $hook_data);
2962 $s = $hook_data['html'];
2966 // Replace the blockquotes with quotes that are used in mails.
2967 $mailquote = '<blockquote type="cite" class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex;">';
2968 $s = str_replace(['<blockquote>', '<blockquote class="spoiler">', '<blockquote class="author">'], [$mailquote, $mailquote, $mailquote], $s);
2972 if (!empty($shared_attachments)) {
2973 $s = self::addVisualAttachments($shared_attachments, $item, $s, true);
2974 $s = self::addLinkAttachment($shared_uri_id ?: $item['uri-id'], $shared_attachments, $body, $s, true, []);
2975 $s = self::addNonVisualAttachments($shared_attachments, $item, $s, true);
2976 $body = preg_replace("/\s*\[share .*?\].*?\[\/share\]\s*/ism", '', $body);
2979 $s = self::addVisualAttachments($attachments, $item, $s, false);
2980 $s = self::addLinkAttachment($item['uri-id'], $attachments, $body, $s, false, $shared_links);
2981 $s = self::addNonVisualAttachments($attachments, $item, $s, false);
2982 $s = self::addQuestions($item, $s);
2985 if (strpos($s, '<div class="map">') !== false && !empty($item['coord'])) {
2986 $x = Map::byCoordinates(trim($item['coord']));
2988 $s = preg_replace('/\<div class\=\"map\"\>/', '$0' . $x, $s);
2992 // Replace friendica image url size with theme preference.
2993 if (!empty($a->getThemeInfoValue('item_image_size'))) {
2994 $ps = $a->getThemeInfoValue('item_image_size');
2995 $s = preg_replace('|(<img[^>]+src="[^"]+/photo/[0-9a-f]+)-[0-9]|', "$1-" . $ps, $s);
2998 $s = HTML::applyContentFilter($s, $filter_reasons);
3000 $hook_data = ['item' => $item, 'html' => $s];
3001 Hook::callAll('prepare_body_final', $hook_data);
3003 return $hook_data['html'];
3007 * Check if the body contains a link
3009 * @param string $body
3010 * @param string $url
3014 public static function containsLink(string $body, string $url, int $type = 0): bool
3016 // Make sure that for example site parameters aren't used when testing if the link is contained in the body
3017 $urlparts = parse_url($url);
3018 if (!empty($urlparts)) {
3019 unset($urlparts['query']);
3020 unset($urlparts['fragment']);
3021 $url = (string)Uri::fromParts($urlparts);
3026 // Remove media links to only search in embedded content
3027 // @todo Check images for image link, audio for audio links, ...
3028 if (in_array($type, [Post\Media::AUDIO, Post\Media::VIDEO, Post\Media::IMAGE])) {
3029 $body = preg_replace("/\[url=[^\[\]]*\](.*)\[\/url\]/Usi", ' $1 ', $body);
3032 if (strpos($body, $url)) {
3035 foreach ([0, 1, 2] as $size) {
3036 if (preg_match('#/photo/.*-' . $size . '\.#ism', $url) &&
3037 strpos(preg_replace('#(/photo/.*)-[012]\.#ism', '$1-' . $size . '.', $body), $url)) {
3045 * Replace visual attachments in the body
3047 * @param array $attachments
3048 * @param string $body
3049 * @return string modified body
3051 private static function replaceVisualAttachments(array $attachments, string $body): string
3053 DI::profiler()->startRecording('rendering');
3055 foreach ($attachments['visual'] as $attachment) {
3056 if (!empty($attachment['preview'])) {
3057 $proxy = Post\Media::getPreviewUrlForId($attachment['id'], Proxy::SIZE_LARGE);
3058 $search = ['[img=' . $attachment['preview'] . ']', ']' . $attachment['preview'] . '[/img]'];
3059 $replace = ['[img=' . $proxy . ']', ']' . $proxy . '[/img]'];
3061 $body = str_replace($search, $replace, $body);
3062 } elseif ($attachment['filetype'] == 'image') {
3063 $proxy = Post\Media::getUrlForId($attachment['id']);
3064 $search = ['[img=' . $attachment['url'] . ']', ']' . $attachment['url'] . '[/img]'];
3065 $replace = ['[img=' . $proxy . ']', ']' . $proxy . '[/img]'];
3067 $body = str_replace($search, $replace, $body);
3070 DI::profiler()->stopRecording();
3075 * Add visual attachments to the content
3077 * @param array $attachments
3078 * @param array $item
3079 * @param string $content
3080 * @return string modified content
3082 private static function addVisualAttachments(array $attachments, array $item, string $content, bool $shared): string
3084 DI::profiler()->startRecording('rendering');
3088 // @todo In the future we should make a single for the template engine with all media in it. This allows more flexibilty.
3089 foreach ($attachments['visual'] as $attachment) {
3090 if (self::containsLink($item['body'], $attachment['preview'] ?? $attachment['url'], $attachment['type'])) {
3094 if (!empty($attachment['preview'])) {
3095 $preview_url = Post\Media::getPreviewUrlForId($attachment['id'], Proxy::SIZE_LARGE);
3100 if (($attachment['filetype'] == 'video')) {
3101 /// @todo Move the template to /content as well
3102 $media = Renderer::replaceMacros(Renderer::getMarkupTemplate('video_top.tpl'), [
3104 'id' => $attachment['id'],
3105 'src' => $attachment['url'],
3106 'name' => $attachment['name'] ?: $attachment['url'],
3107 'preview' => $preview_url,
3108 'mime' => $attachment['mimetype'],
3111 if (($item['post-type'] ?? null) == Item::PT_VIDEO) {
3114 $trailing .= $media;
3116 } elseif ($attachment['filetype'] == 'audio') {
3117 $media = Renderer::replaceMacros(Renderer::getMarkupTemplate('content/audio.tpl'), [
3119 'id' => $attachment['id'],
3120 'src' => $attachment['url'],
3121 'name' => $attachment['name'] ?: $attachment['url'],
3122 'mime' => $attachment['mimetype'],
3125 if (($item['post-type'] ?? null) == Item::PT_AUDIO) {
3128 $trailing .= $media;
3130 } elseif ($attachment['filetype'] == 'image') {
3131 $media = Renderer::replaceMacros(Renderer::getMarkupTemplate('content/image.tpl'), [
3133 'src' => Post\Media::getUrlForId($attachment['id']),
3134 'preview' => Post\Media::getPreviewUrlForId($attachment['id'], ($attachment['width'] > $attachment['height']) ? Proxy::SIZE_MEDIUM : Proxy::SIZE_LARGE),
3135 'attachment' => $attachment,
3138 // On Diaspora posts the attached pictures are leading
3139 if ($item['network'] == Protocol::DIASPORA) {
3142 $trailing .= $media;
3148 $content = str_replace(BBCode::TOP_ANCHOR, '<div class="body-attach">' . $leading . '<div class="clear"></div></div>' . BBCode::TOP_ANCHOR, $content);
3149 $content = str_replace(BBCode::BOTTOM_ANCHOR, '<div class="body-attach">' . $trailing . '<div class="clear"></div></div>' . BBCode::BOTTOM_ANCHOR, $content);
3151 if ($leading != '') {
3152 $content = '<div class="body-attach">' . $leading . '<div class="clear"></div></div>' . $content;
3155 if ($trailing != '') {
3156 $content .= '<div class="body-attach">' . $trailing . '<div class="clear"></div></div>';
3160 DI::profiler()->stopRecording();
3165 * Add link attachment to the content
3167 * @param array $attachments
3168 * @param string $body
3169 * @param string $content
3170 * @param bool $shared
3171 * @param array $ignore_links A list of URLs to ignore
3172 * @return string modified content
3174 private static function addLinkAttachment(int $uriid, array $attachments, string $body, string $content, bool $shared, array $ignore_links): string
3176 DI::profiler()->startRecording('rendering');
3177 // Don't show a preview when there is a visual attachment (audio or video)
3178 $types = array_column($attachments['visual'], 'type');
3179 $preview = !in_array(Post\Media::IMAGE, $types) && !in_array(Post\Media::VIDEO, $types);
3181 if (!empty($attachments['link'])) {
3182 foreach ($attachments['link'] as $link) {
3184 foreach ($ignore_links as $ignore_link) {
3185 if (Strings::compareLink($link['url'], $ignore_link)) {
3189 // @todo Judge between the links to use the one with most information
3190 if (!$found && (empty($attachment) || !empty($link['author-name']) ||
3191 (empty($attachment['name']) && !empty($link['name'])) ||
3192 (empty($attachment['description']) && !empty($link['description'])) ||
3193 (empty($attachment['preview']) && !empty($link['preview'])))) {
3194 $attachment = $link;
3199 if (!empty($attachment)) {
3202 'author_name' => $attachment['author-name'] ?? '',
3203 'author_url' => $attachment['author-url'] ?? '',
3204 'description' => $attachment['description'] ?? '',
3207 'provider_name' => $attachment['publisher-name'] ?? '',
3208 'provider_url' => $attachment['publisher-url'] ?? '',
3210 'title' => $attachment['name'] ?? '',
3212 'url' => $attachment['url']];
3214 if ($preview && !empty($attachment['preview'])) {
3215 if ($attachment['preview-width'] >= 500) {
3216 $data['image'] = Post\Media::getPreviewUrlForId($attachment['id'], Proxy::SIZE_MEDIUM);
3218 $data['preview'] = Post\Media::getPreviewUrlForId($attachment['id'], Proxy::SIZE_MEDIUM);
3222 if (!empty($data['description']) && !empty($content)) {
3223 similar_text($data['description'], $content, $percent);
3228 if (!empty($data['description']) && (($data['title'] == $data['description']) || ($percent > 95) || (strpos($content, $data['description']) !== false))) {
3229 $data['description'] = '';
3232 if (($data['author_name'] ?? '') == ($data['provider_name'] ?? '')) {
3233 $data['author_name'] = '';
3236 if (($data['author_url'] ?? '') == ($data['provider_url'] ?? '')) {
3237 $data['author_url'] = '';
3239 } elseif (preg_match("/.*(\[attachment.*?\].*?\[\/attachment\]).*/ism", $body, $match)) {
3240 $data = BBCode::getAttachmentData($match[1]);
3242 DI::profiler()->stopRecording();
3244 if (isset($data['url']) && !in_array($data['url'], $ignore_links)) {
3245 if (!empty($data['description']) || !empty($data['image']) || !empty($data['preview'])) {
3246 $parts = parse_url($data['url']);
3247 if (!empty($parts['scheme']) && !empty($parts['host'])) {
3248 if (empty($data['provider_name'])) {
3249 $data['provider_name'] = $parts['host'];
3251 if (empty($data['provider_url']) || empty(parse_url($data['provider_url'], PHP_URL_SCHEME))) {
3252 $data['provider_url'] = $parts['scheme'] . '://' . $parts['host'];
3254 if (!empty($parts['port'])) {
3255 $data['provider_url'] .= ':' . $parts['port'];
3260 // @todo Use a template
3261 $rendered = BBCode::convertAttachment('', BBCode::INTERNAL, false, $data, $uriid);
3262 } elseif (!self::containsLink($content, $data['url'], Post\Media::HTML)) {
3263 $rendered = Renderer::replaceMacros(Renderer::getMarkupTemplate('content/link.tpl'), [
3264 '$url' => $data['url'],
3265 '$title' => $data['title'],
3272 return str_replace(BBCode::BOTTOM_ANCHOR, BBCode::BOTTOM_ANCHOR . $rendered, $content);
3274 return $content . $rendered;
3281 * Add non visual attachments to the content
3283 * @param array $attachments
3284 * @param array $item
3285 * @param string $content
3286 * @return string modified content
3288 private static function addNonVisualAttachments(array $attachments, array $item, string $content): string
3290 DI::profiler()->startRecording('rendering');
3292 foreach ($attachments['additional'] as $attachment) {
3293 if (strpos($item['body'], $attachment['url'])) {
3297 $author = ['uid' => 0, 'id' => $item['author-id'],
3298 'network' => $item['author-network'], 'url' => $item['author-link']];
3299 $the_url = Contact::magicLinkByContact($author, $attachment['url']);
3301 $title = Strings::escapeHtml(trim(($attachment['description'] ?? '') ?: $attachment['url']));
3303 if (!empty($attachment['size'])) {
3304 $title .= ' ' . $attachment['size'] . ' ' . DI::l10n()->t('bytes');
3307 /// @todo Use a template
3308 $icon = '<div class="attachtype icon s22 type-' . $attachment['filetype'] . ' subtype-' . $attachment['subtype'] . '"></div>';
3309 $trailing .= '<a href="' . strip_tags($the_url) . '" title="' . $title . '" class="attachlink" target="_blank" rel="noopener noreferrer" >' . $icon . '</a>';
3312 if ($trailing != '') {
3313 $content .= '<div class="body-attach">' . $trailing . '<div class="clear"></div></div>';
3316 DI::profiler()->stopRecording();
3320 private static function addQuestions(array $item, string $content): string
3322 DI::profiler()->startRecording('rendering');
3323 if (!empty($item['question-id'])) {
3325 'id' => $item['question-id'],
3326 'multiple' => $item['question-multiple'],
3327 'voters' => $item['question-voters'],
3328 'endtime' => $item['question-end-time']
3331 $options = Post\QuestionOption::getByURIId($item['uri-id']);
3332 foreach ($options as $key => $option) {
3333 if ($question['voters'] > 0) {
3334 $percent = $option['replies'] / $question['voters'] * 100;
3335 $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));
3337 $options[$key]['vote'] = DI::l10n()->tt('%2$s (%1$d vote)', '%2$s (%1$d votes)', $option['replies'], $option['name'], );
3341 if (!empty($question['voters']) && !empty($question['endtime'])) {
3342 $summary = DI::l10n()->tt('%d voter. Poll end: %s', '%d voters. Poll end: %s', $question['voters'], Temporal::getRelativeDate($question['endtime']));
3343 } elseif (!empty($question['voters'])) {
3344 $summary = DI::l10n()->tt('%d voter.', '%d voters.', $question['voters']);
3345 } elseif (!empty($question['endtime'])) {
3346 $summary = DI::l10n()->t('Poll end: %s', Temporal::getRelativeDate($question['endtime']));
3351 $content .= Renderer::replaceMacros(Renderer::getMarkupTemplate('content/question.tpl'), [
3352 '$question' => $question,
3353 '$options' => $options,
3354 '$summary' => $summary,
3357 DI::profiler()->stopRecording();
3362 * get private link for item
3364 * @param array $item
3365 * @return boolean|array False if item has not plink, otherwise array('href'=>plink url, 'title'=>translated title)
3366 * @throws \Exception
3368 public static function getPlink(array $item)
3370 if (!empty($item['plink']) && Network::isValidHttpUrl($item['plink'])) {
3371 $plink = $item['plink'];
3372 } elseif (!empty($item['uri']) && Network::isValidHttpUrl($item['uri']) && !Network::isLocalLink($item['uri'])) {
3373 $plink = $item['uri'];
3378 'href' => "display/" . $item['guid'],
3379 'orig' => "display/" . $item['guid'],
3380 'title' => DI::l10n()->t('View on separate page'),
3381 'orig_title' => DI::l10n()->t('View on separate page'),
3384 if (!empty($plink) && ($item['private'] == self::PRIVATE)) {
3385 $author = ['uid' => 0, 'id' => $item['author-id'],
3386 'network' => $item['author-network'], 'url' => $item['author-link']];
3387 $plink = Contact::magicLinkByContact($author, $plink);
3390 if (!empty($plink)) {
3391 $ret['href'] = DI::baseUrl()->remove($plink);
3392 $ret['title'] = DI::l10n()->t('Link to source');
3394 } elseif (!empty($plink) && ($item['private'] != self::PRIVATE)) {
3398 'title' => DI::l10n()->t('Link to source'),
3399 'orig_title' => DI::l10n()->t('Link to source'),
3409 * Does the given uri-id belongs to a post that is sent as starting post to a forum?
3411 * @param int $uri_id
3413 * @return boolean "true" when it is a forum post
3415 public static function isForumPost(int $uri_id): bool
3417 foreach (Tag::getByURIId($uri_id, [Tag::EXCLUSIVE_MENTION]) as $tag) {
3418 if (DBA::exists('contact', ['uid' => 0, 'nurl' => Strings::normaliseLink($tag['url']), 'contact-type' => Contact::TYPE_COMMUNITY])) {
3426 * Search item id for given URI or plink
3428 * @param string $uri
3429 * @param integer $uid
3431 * @return integer item id
3433 public static function searchByLink(string $uri, int $uid = 0): int
3435 $ssl_uri = str_replace('http://', 'https://', $uri);
3436 $uris = [$uri, $ssl_uri, Strings::normaliseLink($uri)];
3438 $item = Post::selectFirst(['id'], ['uri' => $uris, 'uid' => $uid]);
3439 if (DBA::isResult($item)) {
3443 $item = Post::selectFirst(['id'], ['plink' => $uris, 'uid' => $uid]);
3444 if (DBA::isResult($item)) {
3452 * Return the URI for a link to the post
3454 * @param string $uri URI or link to post
3456 * @return string URI
3458 public static function getURIByLink(string $uri): string
3460 $ssl_uri = str_replace('http://', 'https://', $uri);
3461 $uris = [$uri, $ssl_uri, Strings::normaliseLink($uri)];
3463 $item = Post::selectFirst(['uri'], ['uri' => $uris]);
3464 if (DBA::isResult($item)) {
3465 return $item['uri'];
3468 $item = Post::selectFirst(['uri'], ['plink' => $uris]);
3469 if (DBA::isResult($item)) {
3470 return $item['uri'];
3477 * Fetches item for given URI or plink
3479 * @param string $uri
3480 * @param integer $uid
3482 * @return integer item id
3484 public static function fetchByLink(string $uri, int $uid = 0): int
3486 Logger::info('Trying to fetch link', ['uid' => $uid, 'uri' => $uri]);
3487 $item_id = self::searchByLink($uri, $uid);
3488 if (!empty($item_id)) {
3489 Logger::info('Link found', ['uid' => $uid, 'uri' => $uri, 'id' => $item_id]);
3499 Hook::callAll('item_by_link', $hookData);
3501 if (isset($hookData['item_id'])) {
3502 return is_numeric($hookData['item_id']) ? $hookData['item_id'] : 0;
3505 $fetched_uri = ActivityPub\Processor::fetchMissingActivity($uri);
3508 $item_id = self::searchByLink($fetched_uri, $uid);
3510 $item_id = Diaspora::fetchByURL($uri);
3513 if (!empty($item_id)) {
3514 Logger::info('Link fetched', ['uid' => $uid, 'uri' => $uri, 'id' => $item_id]);
3518 Logger::info('Link not found', ['uid' => $uid, 'uri' => $uri]);
3523 * Return share data from an item array (if the item is shared item)
3524 * We are providing the complete Item array, because at some time in the future
3525 * we hopefully will define these values not in the body anymore but in some item fields.
3526 * This function is meant to replace all similar functions in the system.
3528 * @param array $item
3530 * @return array with share information
3532 public static function getShareArray(array $item): array
3534 return BBCode::fetchShareAttributes($item['body']);
3538 * Fetch item information for shared items from the original items and adds it.
3540 * @param array $item
3542 * @return array item array with data from the original item
3544 public static function addShareDataFromOriginal(array $item): array
3546 $shared = self::getShareArray($item);
3547 if (empty($shared)) {
3551 // Real reshares always have got a GUID.
3552 if (empty($shared['guid'])) {
3556 $uid = $item['uid'] ?? 0;
3558 // first try to fetch the item via the GUID. This will work for all reshares that had been created on this system
3559 $shared_item = Post::selectFirst(['title', 'body'], ['guid' => $shared['guid'], 'uid' => [0, $uid]]);
3560 if (!DBA::isResult($shared_item)) {
3561 if (empty($shared['link'])) {
3565 // Otherwhise try to find (and possibly fetch) the item via the link. This should work for Diaspora and ActivityPub posts
3566 $id = self::fetchByLink($shared['link'] ?? '', $uid);
3568 Logger::info('Original item not found', ['url' => $shared['link'] ?? '', 'callstack' => System::callstack()]);
3572 $shared_item = Post::selectFirst(['title', 'body'], ['id' => $id]);
3573 if (!DBA::isResult($shared_item)) {
3576 Logger::info('Got shared data from url', ['url' => $shared['link'], 'callstack' => System::callstack()]);
3578 Logger::info('Got shared data from guid', ['guid' => $shared['guid'], 'callstack' => System::callstack()]);
3581 if (!empty($shared_item['title'])) {
3582 $body = '[h3]' . $shared_item['title'] . "[/h3]\n" . $shared_item['body'];
3583 unset($shared_item['title']);
3585 $body = $shared_item['body'];
3588 $item['body'] = preg_replace("/\[share ([^\[\]]*)\].*\[\/share\]/ism", '[share $1]' . str_replace('$', '\$', $body) . '[/share]', $item['body']);
3589 unset($shared_item['body']);
3591 return array_merge($item, $shared_item);
3595 * Check a prospective item array against user-level permissions
3597 * @param array $item Expected keys: uri, gravity, and
3598 * author-link if is author-id is set,
3599 * owner-link if is owner-id is set,
3600 * causer-link if is causer-id is set.
3601 * @param int $user_id Local user ID
3603 * @throws \Exception
3605 protected static function isAllowedByUser(array $item, int $user_id): bool
3607 if (!empty($item['author-id']) && Contact\User::isBlocked($item['author-id'], $user_id)) {
3608 Logger::notice('Author is blocked by user', ['author-link' => $item['author-link'], 'uid' => $user_id, 'item-uri' => $item['uri']]);
3612 if (!empty($item['owner-id']) && Contact\User::isBlocked($item['owner-id'], $user_id)) {
3613 Logger::notice('Owner is blocked by user', ['owner-link' => $item['owner-link'], 'uid' => $user_id, 'item-uri' => $item['uri']]);
3617 // The causer is set during a thread completion, for example because of a reshare. It countains the responsible actor.
3618 if (!empty($item['causer-id']) && Contact\User::isBlocked($item['causer-id'], $user_id)) {
3619 Logger::notice('Causer is blocked by user', ['causer-link' => $item['causer-link'] ?? $item['causer-id'], 'uid' => $user_id, 'item-uri' => $item['uri']]);
3623 if (!empty($item['causer-id']) && ($item['gravity'] === GRAVITY_PARENT) && Contact\User::isIgnored($item['causer-id'], $user_id)) {
3624 Logger::notice('Causer is ignored by user', ['causer-link' => $item['causer-link'] ?? $item['causer-id'], 'uid' => $user_id, 'item-uri' => $item['uri']]);
3632 * Improve the data in shared posts
3634 * @param array $item
3635 * @return string body
3637 public static function improveSharedDataInBody(array $item): string
3639 $shared = BBCode::fetchShareAttributes($item['body']);
3640 if (empty($shared['link'])) {
3641 return $item['body'];
3644 $id = self::fetchByLink($shared['link']);
3645 Logger::info('Fetched shared post', ['uri-id' => $item['uri-id'], 'id' => $id, 'author' => $shared['profile'], 'url' => $shared['link'], 'guid' => $shared['guid'], 'callstack' => System::callstack()]);
3647 return $item['body'];
3650 $shared_item = Post::selectFirst(['author-name', 'author-link', 'author-avatar', 'plink', 'created', 'guid', 'title', 'body'], ['id' => $id]);
3651 if (!DBA::isResult($shared_item)) {
3652 return $item['body'];
3655 $shared_content = BBCode::getShareOpeningTag($shared_item['author-name'], $shared_item['author-link'], $shared_item['author-avatar'], $shared_item['plink'], $shared_item['created'], $shared_item['guid']);
3657 if (!empty($shared_item['title'])) {
3658 $shared_content .= '[h3]'.$shared_item['title'].'[/h3]'."\n";
3661 $shared_content .= $shared_item['body'];
3663 $item['body'] = preg_replace("/\[share.*?\](.*)\[\/share\]/ism", $shared_content . '[/share]', $item['body']);
3664 Logger::info('New shared data', ['uri-id' => $item['uri-id'], 'id' => $id, 'shared_item' => $shared_item]);
3665 return $item['body'];