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 if (!empty($fields['body'])) {
200 Post\Media::insertFromAttachmentData($item['uri-id'], $fields['body']);
202 $content_fields = ['raw-body' => trim($fields['raw-body'] ?? $fields['body'])];
204 // Remove all media attachments from the body and store them in the post-media table
205 // @todo On shared postings (Diaspora style and commented reshare) don't fetch content from the shared part
206 $content_fields['raw-body'] = Post\Media::insertFromBody($item['uri-id'], $content_fields['raw-body']);
207 $content_fields['raw-body'] = self::setHashtags($content_fields['raw-body']);
209 if ($item['author-network'] != Protocol::DFRN) {
210 Post\Media::insertFromRelevantUrl($item['uri-id'], $content_fields['raw-body']);
213 Post\Content::update($item['uri-id'], $content_fields);
216 if (!empty($fields['file'])) {
217 Post\Category::storeTextByURIId($item['uri-id'], $item['uid'], $fields['file']);
220 if (!empty($fields['attach'])) {
221 Post\Media::insertFromAttachment($item['uri-id'], $fields['attach']);
224 // We only need to notfiy others when it is an original entry from us.
225 // Only call the notifier when the item had been edited and records had been changed.
226 if ($item['origin'] && !empty($fields['edited']) && ($previous['edited'] != $fields['edited'])) {
227 $notify_items[] = $item['id'];
233 foreach ($notify_items as $notify_item) {
234 $post = Post::selectFirst(['uri-id', 'uid'], ['id' => $notify_item]);
235 Worker::add(PRIORITY_HIGH, 'Notifier', Delivery::POST, (int)$post['uri-id'], (int)$post['uid']);
242 * Delete an item and notify others about it - if it was ours
244 * @param array $condition The condition for finding the item entries
245 * @param integer $priority Priority for the notification
247 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
249 public static function markForDeletion(array $condition, int $priority = PRIORITY_HIGH)
251 $items = Post::select(['id'], $condition);
252 while ($item = Post::fetch($items)) {
253 self::markForDeletionById($item['id'], $priority);
259 * Delete an item for an user and notify others about it - if it was ours
261 * @param array $condition The condition for finding the item entries
262 * @param integer $uid User who wants to delete this item
264 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
266 public static function deleteForUser(array $condition, int $uid)
272 $items = Post::select(['id', 'uid', 'uri-id'], $condition);
273 while ($item = Post::fetch($items)) {
274 if (in_array($item['uid'], [$uid, 0])) {
275 Post\User::update($item['uri-id'], $uid, ['hidden' => true], true);
276 Post\ThreadUser::update($item['uri-id'], $uid, ['hidden' => true], true);
279 if ($item['uid'] == $uid) {
280 self::markForDeletionById($item['id'], PRIORITY_HIGH);
281 } elseif ($item['uid'] != 0) {
282 Logger::warning('Wrong ownership. Not deleting item', ['id' => $item['id']]);
289 * Mark an item for deletion, delete related data and notify others about it - if it was ours
291 * @param integer $item_id
292 * @param integer $priority Priority for the notification
293 * @return boolean success
294 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
296 public static function markForDeletionById(int $item_id, int $priority = PRIORITY_HIGH): bool
298 Logger::info('Mark item for deletion by id', ['id' => $item_id, 'callstack' => System::callstack()]);
299 // locate item to be deleted
300 $fields = ['id', 'uri', 'uri-id', 'uid', 'parent', 'parent-uri-id', 'origin',
301 'deleted', 'resource-id', 'event-id',
302 'verb', 'object-type', 'object', 'target', 'contact-id', 'psid', 'gravity'];
303 $item = Post::selectFirst($fields, ['id' => $item_id]);
304 if (!DBA::isResult($item)) {
305 Logger::info('Item not found.', ['id' => $item_id]);
309 if ($item['deleted']) {
310 Logger::info('Item has already been marked for deletion.', ['id' => $item_id]);
314 $parent = Post::selectFirst(['origin'], ['id' => $item['parent']]);
315 if (!DBA::isResult($parent)) {
316 $parent = ['origin' => false];
319 // clean up categories and tags so they don't end up as orphans
320 Post\Category::deleteByURIId($item['uri-id'], $item['uid']);
323 * If item is a link to a photo resource, nuke all the associated photos
324 * (visitors will not have photo resources)
325 * This only applies to photos uploaded from the photos page. Photos inserted into a post do not
326 * generate a resource-id and therefore aren't intimately linked to the item.
328 /// @TODO: this should first check if photo is used elsewhere
329 if (strlen($item['resource-id'])) {
330 Photo::delete(['resource-id' => $item['resource-id'], 'uid' => $item['uid']]);
333 // If item is a link to an event, delete the event.
334 if (intval($item['event-id'])) {
335 Event::delete($item['event-id']);
338 // If item has attachments, drop them
339 $attachments = Post\Media::getByURIId($item['uri-id'], [Post\Media::DOCUMENT]);
340 foreach($attachments as $attachment) {
341 if (preg_match('|attach/(\d+)|', $attachment['url'], $matches)) {
342 Attach::delete(['id' => $matches[1], 'uid' => $item['uid']]);
346 // Set the item to "deleted"
347 $item_fields = ['deleted' => true, 'edited' => DateTimeFormat::utcNow(), 'changed' => DateTimeFormat::utcNow()];
348 Post::update($item_fields, ['id' => $item['id']]);
350 Post\Category::storeTextByURIId($item['uri-id'], $item['uid'], '');
352 if (!Post::exists(["`uri-id` = ? AND `uid` != 0 AND NOT `deleted`", $item['uri-id']])) {
353 self::markForDeletion(['uri-id' => $item['uri-id'], 'uid' => 0, 'deleted' => false], $priority);
356 Post\DeliveryData::delete($item['uri-id']);
358 // If it's the parent of a comment thread, kill all the kids
359 if ($item['gravity'] == GRAVITY_PARENT) {
360 self::markForDeletion(['parent' => $item['parent'], 'deleted' => false], $priority);
363 // Is it our comment and/or our thread?
364 if (($item['origin'] || $parent['origin']) && ($item['uid'] != 0)) {
365 // When we delete the original post we will delete all existing copies on the server as well
366 self::markForDeletion(['uri-id' => $item['uri-id'], 'deleted' => false], $priority);
368 // send the notification upstream/downstream
370 Worker::add(['priority' => $priority, 'dont_fork' => true], 'Notifier', Delivery::DELETION, (int)$item['uri-id'], (int)$item['uid']);
372 } elseif ($item['uid'] != 0) {
373 Post\User::update($item['uri-id'], $item['uid'], ['hidden' => true]);
374 Post\ThreadUser::update($item['uri-id'], $item['uid'], ['hidden' => true]);
377 Logger::info('Item has been marked for deletion.', ['id' => $item_id]);
383 * Get guid from given item record
385 * @param array $item Item record
386 * @param bool Whether to notify (?)
387 * @return string Guid
389 public static function guid(array $item, bool $notify): string
391 if (!empty($item['guid'])) {
392 return trim($item['guid']);
396 // We have to avoid duplicates. So we create the GUID in form of a hash of the plink or uri.
397 // We add the hash of our own host because our host is the original creator of the post.
398 $prefix_host = DI::baseUrl()->getHostname();
402 // We are only storing the post so we create a GUID from the original hostname.
403 if (!empty($item['author-link'])) {
404 $parsed = parse_url($item['author-link']);
405 if (!empty($parsed['host'])) {
406 $prefix_host = $parsed['host'];
410 if (empty($prefix_host) && !empty($item['plink'])) {
411 $parsed = parse_url($item['plink']);
412 if (!empty($parsed['host'])) {
413 $prefix_host = $parsed['host'];
417 if (empty($prefix_host) && !empty($item['uri'])) {
418 $parsed = parse_url($item['uri']);
419 if (!empty($parsed['host'])) {
420 $prefix_host = $parsed['host'];
424 // Is it in the format data@host.tld? - Used for mail contacts
425 if (empty($prefix_host) && !empty($item['author-link']) && strstr($item['author-link'], '@')) {
426 $mailparts = explode('@', $item['author-link']);
427 $prefix_host = array_pop($mailparts);
431 if (!empty($item['plink'])) {
432 $guid = self::guidFromUri($item['plink'], $prefix_host);
433 } elseif (!empty($item['uri'])) {
434 $guid = self::guidFromUri($item['uri'], $prefix_host);
436 $guid = System::createUUID(hash('crc32', $prefix_host));
443 * Returns contact id from given item record
445 * @param array $item Item record
446 * @return int Contact id
448 private static function contactId(array $item): int
450 if ($item['uid'] == 0) {
451 return $item['author-id'];
454 if ($item['origin']) {
455 $owner = User::getOwnerDataById($item['uid']);
459 if (!empty($item['causer-id']) && Contact::isSharing($item['causer-id'], $item['uid'], true)) {
460 $cdata = Contact::getPublicAndUserContactID($item['causer-id'], $item['uid']);
461 if (!empty($cdata['user'])) {
462 return $cdata['user'];
466 if ($item['gravity'] == GRAVITY_PARENT) {
467 if (Contact::isSharingByURL($item['owner-link'], $item['uid'], true)) {
468 $contact_id = Contact::getIdForURL($item['owner-link'], $item['uid']);
470 $contact_id = Contact::getIdForURL($item['owner-link']);
472 if (!empty($contact_id)) {
477 if (Contact::isSharingByURL($item['author-link'], $item['uid'], true)) {
478 $contact_id = Contact::getIdForURL($item['author-link'], $item['uid']);
480 $contact_id = Contact::getIdForURL($item['author-link']);
483 if (!empty($contact_id)) {
487 Logger::warning('contact-id could not be fetched, using self contact instead.', ['uid' => $item['uid'], 'item' => $item]);
488 $self = Contact::selectFirst(['id'], ['self' => true, 'uid' => $item['uid']]);
493 * Write an item array into a spool file to be inserted later.
494 * This command is called whenever there are issues storing an item.
496 * @param array $item The item fields that are to be inserted
499 private static function spool(array $item)
501 // Now we store the data in the spool directory
502 // We use "microtime" to keep the arrival order and "mt_rand" to avoid duplicates
503 $file = 'item-' . round(microtime(true) * 10000) . '-' . mt_rand() . '.msg';
505 $spoolpath = System::getSpoolPath();
506 if ($spoolpath != '') {
507 $spool = $spoolpath . '/' . $file;
509 file_put_contents($spool, json_encode($item));
510 Logger::warning("Item wasn't stored - Item was spooled into file", ['file' => $file]);
515 * Check if the item array is a duplicate
517 * @param array $item Item record
518 * @return boolean is it a duplicate?
520 private static function isDuplicate(array $item): bool
522 // Checking if there is already an item with the same guid
523 $condition = ['guid' => $item['guid'], 'network' => $item['network'], 'uid' => $item['uid']];
524 if (Post::exists($condition)) {
525 Logger::notice('Found already existing item', $condition);
529 $condition = ['uri-id' => $item['uri-id'], 'uid' => $item['uid'],
530 'network' => [$item['network'], Protocol::DFRN]];
531 if (Post::exists($condition)) {
532 Logger::notice('duplicated item with the same uri found.', $condition);
536 // On Friendica and Diaspora the GUID is unique
537 if (in_array($item['network'], [Protocol::DFRN, Protocol::DIASPORA])) {
538 $condition = ['guid' => $item['guid'], 'uid' => $item['uid']];
539 if (Post::exists($condition)) {
540 Logger::notice('duplicated item with the same guid found.', $condition);
543 } elseif ($item['network'] == Protocol::OSTATUS) {
544 // Check for an existing post with the same content. There seems to be a problem with OStatus.
545 $condition = ["`body` = ? AND `network` = ? AND `created` = ? AND `contact-id` = ? AND `uid` = ?",
546 $item['body'], $item['network'], $item['created'], $item['contact-id'], $item['uid']];
547 if (Post::exists($condition)) {
548 Logger::notice('duplicated item with the same body found.', $item);
554 * Check for already added items.
555 * There is a timing issue here that sometimes creates double postings.
556 * An unique index would help - but the limitations of MySQL (maximum size of index values) prevent this.
558 if (($item['uid'] == 0) && Post::exists(['uri-id' => $item['uri-id'], 'uid' => 0])) {
559 Logger::notice('Global item already stored.', ['uri-id' => $item['uri-id'], 'network' => $item['network']]);
567 * Check if the item array is valid
569 * @param array $item Item record
570 * @return boolean item is valid
572 public static function isValid(array $item): bool
574 // When there is no content then we don't post it
575 if (($item['body'] . $item['title'] == '') && (empty($item['uri-id']) || !Post\Media::existsByURIId($item['uri-id']))) {
576 Logger::notice('No body, no title.');
580 if (!empty($item['uid'])) {
581 $owner = User::getOwnerDataById($item['uid'], false);
583 Logger::warning('Missing item user owner data', ['uid' => $item['uid']]);
587 if ($owner['account_expired'] || $owner['account_removed']) {
588 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']]);
593 if (!empty($item['author-id']) && Contact::isBlocked($item['author-id'])) {
594 Logger::notice('Author is blocked node-wide', ['author-link' => $item['author-link'], 'item-uri' => $item['uri']]);
598 if (!empty($item['author-link']) && Network::isUrlBlocked($item['author-link'])) {
599 Logger::notice('Author server is blocked', ['author-link' => $item['author-link'], 'item-uri' => $item['uri']]);
603 if (!empty($item['owner-id']) && Contact::isBlocked($item['owner-id'])) {
604 Logger::notice('Owner is blocked node-wide', ['owner-link' => $item['owner-link'], 'item-uri' => $item['uri']]);
608 if (!empty($item['owner-link']) && Network::isUrlBlocked($item['owner-link'])) {
609 Logger::notice('Owner server is blocked', ['owner-link' => $item['owner-link'], 'item-uri' => $item['uri']]);
613 if (!empty($item['uid']) && !self::isAllowedByUser($item, $item['uid'])) {
617 if ($item['verb'] == Activity::FOLLOW) {
618 if (!$item['origin'] && ($item['author-id'] == Contact::getPublicIdByUserId($item['uid']))) {
619 // Our own follow request can be relayed to us. We don't store it to avoid notification chaos.
620 Logger::info("Follow: Don't store not origin follow request", ['parent-uri' => $item['parent-uri']]);
624 $condition = ['verb' => Activity::FOLLOW, 'uid' => $item['uid'],
625 'parent-uri' => $item['parent-uri'], 'author-id' => $item['author-id']];
626 if (Post::exists($condition)) {
627 // It happens that we receive multiple follow requests by the same author - we only store one.
628 Logger::info('Follow: Found existing follow request from author', ['author-id' => $item['author-id'], 'parent-uri' => $item['parent-uri']]);
637 * Check if the item array is too old
639 * @param array $item Item record
640 * @return boolean item is too old
642 public static function isTooOld(array $item): bool
644 // check for create date and expire time
645 $expire_interval = DI::config()->get('system', 'dbclean-expire-days', 0);
647 $user = DBA::selectFirst('user', ['expire'], ['uid' => $item['uid']]);
648 if (DBA::isResult($user) && ($user['expire'] > 0) && (($user['expire'] < $expire_interval) || ($expire_interval == 0))) {
649 $expire_interval = $user['expire'];
652 if (($expire_interval > 0) && !empty($item['created'])) {
653 $expire_date = time() - ($expire_interval * 86400);
654 $created_date = strtotime($item['created']);
655 if ($created_date < $expire_date) {
656 Logger::notice('Item created before expiration interval.', [
657 'created' => date('c', $created_date),
658 'expired' => date('c', $expire_date),
669 * Return the id of the given item array if it has been stored before
671 * @param array $item Item record
672 * @return integer Item id or zero on error
674 private static function getDuplicateID(array $item): int
676 if (empty($item['network']) || in_array($item['network'], Protocol::FEDERATED)) {
677 $condition = ['`uri-id` = ? AND `uid` = ? AND `network` IN (?, ?, ?, ?)',
680 Protocol::ACTIVITYPUB,
685 $existing = Post::selectFirst(['id', 'network'], $condition);
686 if (DBA::isResult($existing)) {
687 // We only log the entries with a different user id than 0. Otherwise we would have too many false positives
688 if ($item['uid'] != 0) {
689 Logger::notice('Item already existed for user', [
690 'uri-id' => $item['uri-id'],
691 'uid' => $item['uid'],
692 'network' => $item['network'],
693 'existing_id' => $existing['id'],
694 'existing_network' => $existing['network']
698 return $existing['id'];
705 * Fetch the uri-id of the parent for the given uri-id
707 * @param integer $uriid
710 public static function getParent(int $uriid): int
712 $thread_parent = Post::selectFirstPost(['thr-parent-id', 'gravity'], ['uri-id' => $uriid]);
713 if (empty($thread_parent)) {
717 if ($thread_parent['gravity'] == GRAVITY_PARENT) {
721 return self::getParent($thread_parent['thr-parent-id']);
725 * Fetch top-level parent data for the given item array
728 * @return array item array with parent data
731 private static function getTopLevelParent(array $item): array
733 $fields = ['uid', 'uri', 'parent-uri', 'id', 'deleted',
734 'uri-id', 'parent-uri-id',
735 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid',
736 'wall', 'private', 'origin', 'author-id'];
737 $condition = ['uri-id' => [$item['thr-parent-id'], $item['parent-uri-id']], 'uid' => $item['uid']];
738 $params = ['order' => ['id' => false]];
739 $parent = Post::selectFirst($fields, $condition, $params);
741 if (!DBA::isResult($parent) && Post::exists(['uri-id' => [$item['thr-parent-id'], $item['parent-uri-id']], 'uid' => 0])) {
742 $stored = Item::storeForUserByUriId($item['thr-parent-id'], $item['uid'], ['post-reason' => Item::PR_COMPLETION]);
743 if (!$stored && ($item['thr-parent-id'] != $item['parent-uri-id'])) {
744 $stored = Item::storeForUserByUriId($item['parent-uri-id'], $item['uid'], ['post-reason' => Item::PR_COMPLETION]);
747 Logger::info('Stored thread parent item for user', ['uri-id' => $item['thr-parent-id'], 'uid' => $item['uid'], 'stored' => $stored]);
748 $parent = Post::selectFirst($fields, $condition, $params);
752 if (!DBA::isResult($parent)) {
753 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)]);
757 if ($parent['uri-id'] == $parent['parent-uri-id']) {
761 $condition = ['uri-id' => $parent['parent-uri-id'],
762 'parent-uri-id' => $parent['parent-uri-id'],
763 'uid' => $parent['uid']];
764 $params = ['order' => ['id' => false]];
765 $toplevel_parent = Post::selectFirst($fields, $condition, $params);
767 if (!DBA::isResult($toplevel_parent) && $item['origin']) {
768 $stored = Item::storeForUserByUriId($item['parent-uri-id'], $item['uid'], ['post-reason' => Item::PR_COMPLETION]);
769 Logger::info('Stored parent item for user', ['uri-id' => $item['parent-uri-id'], 'uid' => $item['uid'], 'stored' => $stored]);
770 $toplevel_parent = Post::selectFirst($fields, $condition, $params);
773 if (!DBA::isResult($toplevel_parent)) {
774 Logger::notice('item top level parent was not found - ignoring item', ['parent-uri-id' => $parent['parent-uri-id'], 'uid' => $parent['uid']]);
778 return $toplevel_parent;
782 * Get the gravity for the given item array
785 * @return integer gravity
787 private static function getGravity(array $item): int
789 $activity = DI::activity();
791 if (isset($item['gravity'])) {
792 return intval($item['gravity']);
793 } elseif ($item['parent-uri-id'] === $item['uri-id']) {
794 return GRAVITY_PARENT;
795 } elseif ($activity->match($item['verb'], Activity::POST)) {
796 return GRAVITY_COMMENT;
797 } elseif ($activity->match($item['verb'], Activity::FOLLOW)) {
798 return GRAVITY_ACTIVITY;
799 } elseif ($activity->match($item['verb'], Activity::ANNOUNCE)) {
800 return GRAVITY_ACTIVITY;
803 Logger::info('Unknown gravity for verb', ['verb' => $item['verb']]);
804 return GRAVITY_UNKNOWN; // Should not happen
808 * Inserts item record
810 * @param array $item Item array to be inserted
811 * @param int $notify Notification (type?)
812 * @param bool $post_local (???)
813 * @return int Zero means error, otherwise primary key (id) is being returned
815 public static function insert(array $item, int $notify = 0, bool $post_local = true): int
819 $priority = PRIORITY_HIGH;
821 // If it is a posting where users should get notifications, then define it as wall posting
825 $item['network'] = Protocol::DFRN;
826 $item['protocol'] = Conversation::PARCEL_DIRECT;
827 $item['direction'] = Conversation::PUSH;
829 if (is_int($notify) && in_array($notify, PRIORITIES)) {
833 $item['network'] = trim(($item['network'] ?? '') ?: Protocol::PHANTOM);
836 $uid = intval($item['uid']);
838 $item['guid'] = self::guid($item, $notify);
839 $item['uri'] = substr(trim($item['uri'] ?? '') ?: self::newURI($item['guid']), 0, 255);
842 $item['uri-id'] = ItemURI::insert(['uri' => $item['uri'], 'guid' => $item['guid']]);
844 // Backward compatibility: parent-uri used to be the direct parent uri.
845 // If it is provided without a thr-parent, it probably is the old behavior.
846 if (empty($item['thr-parent']) || empty($item['parent-uri'])) {
847 $item['thr-parent'] = trim($item['thr-parent'] ?? $item['parent-uri'] ?? $item['uri']);
848 $item['parent-uri'] = $item['thr-parent'];
851 $item['thr-parent-id'] = ItemURI::getIdByURI($item['thr-parent']);
852 $item['parent-uri-id'] = ItemURI::getIdByURI($item['parent-uri']);
854 // Store conversation data
855 $source = $item['source'] ?? '';
856 unset($item['conversation-uri']);
857 unset($item['conversation-href']);
858 unset($item['source']);
861 * Do we already have this item?
862 * We have to check several networks since Friendica posts could be repeated
863 * via OStatus (maybe Diasporsa as well)
865 $duplicate = self::getDuplicateID($item);
870 // Additional duplicate checks
871 /// @todo Check why the first duplication check returns the item number and the second a 0
872 if (self::isDuplicate($item)) {
876 if (!isset($item['post-type'])) {
877 $item['post-type'] = empty($item['title']) ? self::PT_NOTE : self::PT_ARTICLE;
880 $item['wall'] = intval($item['wall'] ?? 0);
881 $item['extid'] = trim($item['extid'] ?? '');
882 $item['author-name'] = trim($item['author-name'] ?? '');
883 $item['author-link'] = trim($item['author-link'] ?? '');
884 $item['author-avatar'] = trim($item['author-avatar'] ?? '');
885 $item['owner-name'] = trim($item['owner-name'] ?? '');
886 $item['owner-link'] = trim($item['owner-link'] ?? '');
887 $item['owner-avatar'] = trim($item['owner-avatar'] ?? '');
888 $item['received'] = (isset($item['received']) ? DateTimeFormat::utc($item['received']) : DateTimeFormat::utcNow());
889 $item['created'] = (isset($item['created']) ? DateTimeFormat::utc($item['created']) : $item['received']);
890 $item['edited'] = (isset($item['edited']) ? DateTimeFormat::utc($item['edited']) : $item['created']);
891 $item['changed'] = (isset($item['changed']) ? DateTimeFormat::utc($item['changed']) : $item['created']);
892 $item['commented'] = (isset($item['commented']) ? DateTimeFormat::utc($item['commented']) : $item['created']);
893 $item['title'] = substr(trim($item['title'] ?? ''), 0, 255);
894 $item['location'] = trim($item['location'] ?? '');
895 $item['coord'] = trim($item['coord'] ?? '');
896 $item['visible'] = (isset($item['visible']) ? intval($item['visible']) : 1);
897 $item['deleted'] = 0;
898 $item['verb'] = trim($item['verb'] ?? '');
899 $item['object-type'] = trim($item['object-type'] ?? '');
900 $item['object'] = trim($item['object'] ?? '');
901 $item['target-type'] = trim($item['target-type'] ?? '');
902 $item['target'] = trim($item['target'] ?? '');
903 $item['plink'] = substr(trim($item['plink'] ?? ''), 0, 255);
904 $item['allow_cid'] = trim($item['allow_cid'] ?? '');
905 $item['allow_gid'] = trim($item['allow_gid'] ?? '');
906 $item['deny_cid'] = trim($item['deny_cid'] ?? '');
907 $item['deny_gid'] = trim($item['deny_gid'] ?? '');
908 $item['private'] = intval($item['private'] ?? self::PUBLIC);
909 $item['body'] = trim($item['body'] ?? '');
910 $item['raw-body'] = trim($item['raw-body'] ?? $item['body']);
911 $item['app'] = trim($item['app'] ?? '');
912 $item['origin'] = intval($item['origin'] ?? 0);
913 $item['postopts'] = trim($item['postopts'] ?? '');
914 $item['resource-id'] = trim($item['resource-id'] ?? '');
915 $item['event-id'] = intval($item['event-id'] ?? 0);
916 $item['inform'] = trim($item['inform'] ?? '');
917 $item['file'] = trim($item['file'] ?? '');
919 // Communities aren't working with the Diaspora protoccol
920 if (($uid != 0) && ($item['network'] == Protocol::DIASPORA)) {
921 $user = User::getById($uid, ['account-type']);
922 if ($user['account-type'] == Contact::TYPE_COMMUNITY) {
923 Logger::info('Community posts are not supported via Diaspora');
928 // Items cannot be stored before they happen ...
929 if ($item['created'] > DateTimeFormat::utcNow()) {
930 $item['created'] = DateTimeFormat::utcNow();
933 // We haven't invented time travel by now.
934 if ($item['edited'] > DateTimeFormat::utcNow()) {
935 $item['edited'] = DateTimeFormat::utcNow();
938 $item['plink'] = ($item['plink'] ?? '') ?: DI::baseUrl() . '/display/' . urlencode($item['guid']);
940 $item['gravity'] = self::getGravity($item);
942 $default = ['url' => $item['author-link'], 'name' => $item['author-name'],
943 'photo' => $item['author-avatar'], 'network' => $item['network']];
944 $item['author-id'] = ($item['author-id'] ?? 0) ?: Contact::getIdForURL($item['author-link'], 0, null, $default);
946 $default = ['url' => $item['owner-link'], 'name' => $item['owner-name'],
947 'photo' => $item['owner-avatar'], 'network' => $item['network']];
948 $item['owner-id'] = ($item['owner-id'] ?? 0) ?: Contact::getIdForURL($item['owner-link'], 0, null, $default);
950 $item['post-reason'] = self::getPostReason($item);
952 // Ensure that there is an avatar cache
953 Contact::checkAvatarCache($item['author-id']);
954 Contact::checkAvatarCache($item['owner-id']);
956 $item['contact-id'] = self::contactId($item);
958 if (!empty($item['direction']) && in_array($item['direction'], [Conversation::PUSH, Conversation::RELAY]) &&
959 empty($item['origin']) && self::isTooOld($item)) {
960 Logger::info('Item is too old', ['item' => $item]);
964 if (!self::isValid($item)) {
968 if ($item['gravity'] !== GRAVITY_PARENT) {
969 $toplevel_parent = self::getTopLevelParent($item);
970 if (empty($toplevel_parent)) {
974 // If the thread originated from this node, we check the permission against the thread starter
975 $condition = ['uri-id' => $toplevel_parent['uri-id'], 'wall' => true];
976 $localTopLevelParent = Post::selectFirst(['uid'], $condition);
977 if (!empty($localTopLevelParent['uid']) && !self::isAllowedByUser($item, $localTopLevelParent['uid'])) {
981 $parent_id = $toplevel_parent['id'];
982 $item['parent-uri'] = $toplevel_parent['uri'];
983 $item['parent-uri-id'] = $toplevel_parent['uri-id'];
984 $item['deleted'] = $toplevel_parent['deleted'];
986 // Reshares have to keep their permissions to allow forums to work
987 if (!$item['origin'] || ($item['verb'] != Activity::ANNOUNCE)) {
988 $item['allow_cid'] = $toplevel_parent['allow_cid'];
989 $item['allow_gid'] = $toplevel_parent['allow_gid'];
990 $item['deny_cid'] = $toplevel_parent['deny_cid'];
991 $item['deny_gid'] = $toplevel_parent['deny_gid'];
994 $parent_origin = $toplevel_parent['origin'];
996 // Don't federate received participation messages
997 if ($item['verb'] != Activity::FOLLOW) {
998 $item['wall'] = $toplevel_parent['wall'];
1000 $item['wall'] = false;
1001 // Participations are technical messages, so they are set to "seen" automatically
1002 $item['unseen'] = false;
1006 * If the parent is private, force privacy for the entire conversation
1007 * This differs from the above settings as it subtly allows comments from
1008 * email correspondents to be private even if the overall thread is not.
1010 if ($toplevel_parent['private']) {
1011 $item['private'] = $toplevel_parent['private'];
1014 // If its a post that originated here then tag the thread as "mention"
1015 if ($item['origin'] && $item['uid']) {
1016 DBA::update('post-thread-user', ['mention' => true], ['uri-id' => $item['parent-uri-id'], 'uid' => $item['uid']]);
1017 Logger::info('tagged thread as mention', ['parent' => $parent_id, 'parent-uri-id' => $item['parent-uri-id'], 'uid' => $item['uid']]);
1020 // Update the contact relations
1021 Contact\Relation::store($toplevel_parent['author-id'], $item['author-id'], $item['created']);
1024 $parent_origin = $item['origin'];
1026 if ($item['wall'] && empty($item['conversation'])) {
1027 $item['conversation'] = $item['parent-uri'] . '#context';
1031 $item['parent-uri-id'] = ItemURI::getIdByURI($item['parent-uri']);
1032 $item['thr-parent-id'] = ItemURI::getIdByURI($item['thr-parent']);
1034 if (!empty($item['conversation']) && empty($item['conversation-id'])) {
1035 $item['conversation-id'] = ItemURI::getIdByURI($item['conversation']);
1038 // Is this item available in the global items (with uid=0)?
1039 if ($item['uid'] == 0) {
1040 $item['global'] = true;
1042 // Set the global flag on all items if this was a global item entry
1043 Post::update(['global' => true], ['uri-id' => $item['uri-id']]);
1045 $item['global'] = Post::exists(['uid' => 0, 'uri-id' => $item['uri-id']]);
1049 if (!empty($item['allow_cid'] . $item['allow_gid'] . $item['deny_cid'] . $item['deny_gid'])) {
1050 $item['private'] = self::PRIVATE;
1053 if ($notify && $post_local) {
1054 $item['edit'] = false;
1055 $item['parent'] = $parent_id;
1057 // Trigger automatic reactions for addons
1058 if (!isset($item['api_source'])) {
1059 $item['api_source'] = true;
1062 // We have to tell the hooks who we are - this really should be improved
1063 if (!local_user()) {
1064 $_SESSION['authenticated'] = true;
1065 $_SESSION['uid'] = $uid;
1066 $dummy_session = true;
1068 $dummy_session = false;
1071 Hook::callAll('post_local', $item);
1073 if ($dummy_session) {
1074 unset($_SESSION['authenticated']);
1075 unset($_SESSION['uid']);
1077 } elseif (!$notify) {
1078 Hook::callAll('post_remote', $item);
1081 if (!empty($item['cancel'])) {
1082 Logger::notice('post cancelled by addon.');
1086 if (empty($item['vid']) && !empty($item['verb'])) {
1087 $item['vid'] = Verb::getID($item['verb']);
1090 // Creates or assigns the permission set
1091 $item['psid'] = DI::permissionSet()->selectOrCreate(
1092 DI::permissionSetFactory()->createFromString(
1100 if (!empty($item['extid'])) {
1101 $item['external-id'] = ItemURI::getIdByURI($item['extid']);
1104 if ($item['verb'] == Activity::ANNOUNCE) {
1105 self::setOwnerforResharedItem($item);
1108 if (isset($item['attachments'])) {
1109 foreach ($item['attachments'] as $attachment) {
1110 $attachment['uri-id'] = $item['uri-id'];
1111 Post\Media::insert($attachment);
1113 unset($item['attachments']);
1116 Post\Media::insertFromAttachmentData($item['uri-id'], $item['body']);
1118 // Remove all media attachments from the body and store them in the post-media table
1119 $item['raw-body'] = Post\Media::insertFromBody($item['uri-id'], $item['raw-body']);
1120 $item['raw-body'] = self::setHashtags($item['raw-body']);
1122 if (!DBA::exists('contact', ['id' => $item['author-id'], 'network' => Protocol::DFRN])) {
1123 Post\Media::insertFromRelevantUrl($item['uri-id'], $item['raw-body']);
1126 // Check for hashtags in the body and repair or add hashtag links
1127 $item['body'] = self::setHashtags($item['body']);
1129 $item['language'] = self::getLanguage($item);
1131 $notify_type = Delivery::POST;
1133 // Filling item related side tables
1134 if (!empty($item['attach'])) {
1135 Post\Media::insertFromAttachment($item['uri-id'], $item['attach']);
1138 if (empty($item['event-id'])) {
1139 unset($item['event-id']);
1141 $ev = Event::fromBBCode($item['body']);
1142 if ((!empty($ev['desc']) || !empty($ev['summary'])) && !empty($ev['start'])) {
1143 Logger::info('Event found.');
1144 $ev['cid'] = $item['contact-id'];
1145 $ev['uid'] = $item['uid'];
1146 $ev['uri'] = $item['uri'];
1147 $ev['edited'] = $item['edited'];
1148 $ev['private'] = $item['private'];
1149 $ev['guid'] = $item['guid'];
1150 $ev['plink'] = $item['plink'];
1151 $ev['network'] = $item['network'];
1152 $ev['protocol'] = $item['protocol'] ?? Conversation::PARCEL_UNKNOWN;
1153 $ev['direction'] = $item['direction'] ?? Conversation::UNKNOWN;
1154 $ev['source'] = $item['source'] ?? '';
1156 $event = DBA::selectFirst('event', ['id'], ['uri' => $item['uri'], 'uid' => $item['uid']]);
1157 if (DBA::isResult($event)) {
1158 $ev['id'] = $event['id'];
1161 $event_id = Event::store($ev);
1162 $item = Event::getItemArrayForImportedId($event_id, $item);
1164 Logger::info('Event was stored', ['id' => $event_id]);
1168 if (empty($item['causer-id'])) {
1169 unset($item['causer-id']);
1172 if (in_array($item['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN])) {
1173 $content_warning = BBCode::getAbstract($item['body'], Protocol::ACTIVITYPUB);
1174 if (!empty($content_warning) && empty($item['content-warning'])) {
1175 $item['content-warning'] = BBCode::toPlaintext($content_warning);
1179 Post::insert($item['uri-id'], $item);
1181 if ($item['gravity'] == GRAVITY_PARENT) {
1182 Post\Thread::insert($item['uri-id'], $item);
1185 if (!in_array($item['verb'], self::ACTIVITIES)) {
1186 Post\Content::insert($item['uri-id'], $item);
1189 // Create Diaspora signature
1190 if ($item['origin'] && empty($item['diaspora_signed_text']) && ($item['gravity'] != GRAVITY_PARENT)) {
1191 $signed = Diaspora::createCommentSignature($item);
1192 if (!empty($signed)) {
1193 $item['diaspora_signed_text'] = json_encode($signed);
1197 if (!empty($item['diaspora_signed_text'])) {
1198 DBA::replace('diaspora-interaction', ['uri-id' => $item['uri-id'], 'interaction' => $item['diaspora_signed_text']]);
1201 // Attached file links
1202 if (!empty($item['file'])) {
1203 Post\Category::storeTextByURIId($item['uri-id'], $item['uid'], $item['file']);
1206 // Delivery relevant data
1207 $delivery_data = Post\DeliveryData::extractFields($item);
1209 if (!empty($item['origin']) || !empty($item['wall']) || !empty($delivery_data['postopts']) || !empty($delivery_data['inform'])) {
1210 Post\DeliveryData::insert($item['uri-id'], $delivery_data);
1213 // Store tags from the body if this hadn't been handled previously in the protocol classes
1214 if (!Tag::existsForPost($item['uri-id'])) {
1215 Tag::storeFromBody($item['uri-id'], $item['body']);
1218 $condition = ['uri-id' => $item['uri-id'], 'uid' => $item['uid']];
1219 if (Post::exists($condition)) {
1220 Logger::notice('Item is already inserted - aborting', $condition);
1224 $post_user_id = Post\User::insert($item['uri-id'], $item['uid'], $item);
1225 if (!$post_user_id) {
1226 Logger::notice('Post-User is already inserted - aborting', ['uid' => $item['uid'], 'uri-id' => $item['uri-id']]);
1230 if ($item['gravity'] == GRAVITY_PARENT) {
1231 $item['post-user-id'] = $post_user_id;
1232 Post\ThreadUser::insert($item['uri-id'], $item['uid'], $item);
1235 Logger::notice('created item', ['post-id' => $post_user_id, 'uid' => $item['uid'], 'network' => $item['network'], 'uri-id' => $item['uri-id'], 'guid' => $item['guid']]);
1237 $posted_item = Post::selectFirst(self::ITEM_FIELDLIST, ['post-user-id' => $post_user_id]);
1238 if (!DBA::isResult($posted_item)) {
1239 // On failure store the data into a spool file so that the "SpoolPost" worker can try again later.
1240 Logger::warning('Could not store item. it will be spooled', ['id' => $post_user_id]);
1241 self::spool($orig_item);
1245 // update the commented timestamp on the parent
1246 if (DI::config()->get('system', 'like_no_comment')) {
1247 // Update when it is a comment
1248 $update_commented = in_array($posted_item['gravity'], [GRAVITY_PARENT, GRAVITY_COMMENT]);
1250 // Update when it isn't a follow or tag verb
1251 $update_commented = !in_array($posted_item['verb'], [Activity::FOLLOW, Activity::TAG]);
1254 if ($update_commented) {
1255 $fields = ['commented' => DateTimeFormat::utcNow(), 'changed' => DateTimeFormat::utcNow()];
1257 $fields = ['changed' => DateTimeFormat::utcNow()];
1260 Post::update($fields, ['uri-id' => $posted_item['parent-uri-id'], 'uid' => $posted_item['uid']]);
1262 // In that function we check if this is a forum post. Additionally we delete the item under certain circumstances
1263 if (self::tagDeliver($posted_item['uid'], $post_user_id)) {
1264 // Get the user information for the logging
1265 $user = User::getById($uid);
1267 Logger::notice('Item had been deleted', ['id' => $post_user_id, 'user' => $uid, 'account-type' => $user['account-type']]);
1272 if (!\Friendica\Content\Feature::isEnabled($posted_item['uid'], 'explicit_mentions') && ($posted_item['gravity'] == GRAVITY_COMMENT)) {
1273 Tag::createImplicitMentions($posted_item['uri-id'], $posted_item['thr-parent-id']);
1275 Hook::callAll('post_local_end', $posted_item);
1277 Hook::callAll('post_remote_end', $posted_item);
1280 if ($posted_item['gravity'] === GRAVITY_PARENT) {
1281 self::addShadow($post_user_id);
1283 self::addShadowPost($post_user_id);
1286 self::updateContact($posted_item);
1288 Post\UserNotification::setNotification($posted_item['uri-id'], $posted_item['uid']);
1290 // Distribute items to users who subscribed to their tags
1291 self::distributeByTags($posted_item);
1293 // Automatically reshare the item if the "remote_self" option is selected
1294 self::autoReshare($posted_item);
1296 $transmit = $notify || ($posted_item['visible'] && ($parent_origin || $posted_item['origin']));
1299 // Don't relay participation messages
1300 if (($posted_item['verb'] == Activity::FOLLOW) &&
1301 (!$posted_item['origin'] || ($posted_item['author-id'] != Contact::getPublicIdByUserId($uid)))) {
1302 Logger::info('Participation messages will not be relayed', ['item' => $posted_item['id'], 'uri' => $posted_item['uri'], 'verb' => $posted_item['verb']]);
1308 if (!empty($source)) {
1309 Post\Activity::insert($item['uri-id'], $source);
1311 Worker::add(['priority' => $priority, 'dont_fork' => true], 'Notifier', $notify_type, (int)$posted_item['uri-id'], (int)$posted_item['uid']);
1314 // Fill the cache with the rendered content.
1315 if (in_array($posted_item['gravity'], [GRAVITY_PARENT, GRAVITY_COMMENT]) && ($posted_item['uid'] == 0)) {
1316 self::updateDisplayCache($posted_item['uri-id']);
1319 return $post_user_id;
1323 * Fetch the post reason for a given item array
1325 * @param array $item
1329 public static function getPostReason(array $item): int
1331 $actor = ($item['gravity'] == GRAVITY_PARENT) ? $item['owner-id'] : $item['author-id'];
1332 if (empty($item['origin']) && ($item['uid'] != 0) && Contact::isSharing($actor, $item['uid'])) {
1333 return self::PR_FOLLOWER;
1336 if (!empty($item['origin']) && empty($item['post-reason'])) {
1337 return self::PR_LOCAL;
1340 return $item['post-reason'] ?? self::PR_NONE;
1344 * Update the display cache
1346 * @param integer $uri_id
1349 public static function updateDisplayCache(int $uri_id)
1351 $item = Post::selectFirst(self::DISPLAY_FIELDLIST, ['uri-id' => $uri_id]);
1352 self::prepareBody($item, false, false, true);
1356 * Change the owner of a parent item if it had been shared by a forum
1358 * (public) forum posts in the new format consist of the regular post by the author
1359 * followed by an announce message sent from the forum account.
1360 * Changing the owner helps in grouping forum posts.
1362 * @param array $item
1365 private static function setOwnerforResharedItem(array $item)
1367 $parent = Post::selectFirst(['id', 'causer-id', 'owner-id', 'author-id', 'author-link', 'origin', 'post-reason'],
1368 ['uri-id' => $item['thr-parent-id'], 'uid' => $item['uid']]);
1369 if (!DBA::isResult($parent)) {
1370 Logger::error('Parent not found', ['uri-id' => $item['thr-parent-id'], 'uid' => $item['uid']]);
1374 $author = Contact::selectFirst(['url', 'contact-type', 'network'], ['id' => $item['author-id']]);
1375 if (!DBA::isResult($author)) {
1376 Logger::error('Author not found', ['id' => $item['author-id']]);
1380 $self_contact = Contact::selectFirst(['id'], ['uid' => $item['uid'], 'self' => true]);
1381 $self = !empty($self_contact) ? $self_contact['id'] : 0;
1383 $cid = Contact::getIdForURL($author['url'], $item['uid']);
1384 if (empty($cid) || (!Contact::isSharing($cid, $item['uid']) && ($cid != $self))) {
1385 Logger::info('The resharer is not a following contact: quit', ['resharer' => $author['url'], 'uid' => $item['uid'], 'cid' => $cid]);
1389 if ($author['contact-type'] != Contact::TYPE_COMMUNITY) {
1390 if ($parent['post-reason'] == self::PR_ANNOUNCEMENT) {
1391 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']]);
1395 if (Contact::isSharing($parent['owner-id'], $item['uid'])) {
1396 Logger::info('The resharer is no forum: quit', ['resharer' => $item['author-id'], 'owner' => $parent['owner-id'], 'author' => $parent['author-id'], 'uid' => $item['uid']]);
1401 self::update(['post-reason' => self::PR_ANNOUNCEMENT, 'causer-id' => $item['author-id']], ['id' => $parent['id']]);
1402 Logger::info('Set announcement post-reason', ['uri-id' => $item['uri-id'], 'thr-parent-id' => $item['thr-parent-id'], 'uid' => $item['uid']]);
1406 * Distribute the given item to users who subscribed to their tags
1408 * @param array $item Processed item
1410 private static function distributeByTags(array $item)
1412 if (($item['uid'] != 0) || ($item['gravity'] != GRAVITY_PARENT) || !in_array($item['network'], Protocol::FEDERATED)) {
1416 $uids = Tag::getUIDListByURIId($item['uri-id']);
1417 foreach ($uids as $uid) {
1418 $stored = self::storeForUserByUriId($item['uri-id'], $uid, ['post-reason' => self::PR_TAG]);
1419 Logger::info('Stored item for users', ['uri-id' => $item['uri-id'], 'uid' => $uid, 'stored' => $stored]);
1424 * Distributes public items to the receivers
1426 * @param integer $itemid Item ID that should be added
1427 * @param string $signed_text Original text (for Diaspora signatures), JSON encoded.
1428 * @throws \Exception
1430 public static function distribute(int $itemid, string $signed_text = '')
1432 $condition = ["`id` IN (SELECT `parent` FROM `post-user-view` WHERE `id` = ?)", $itemid];
1433 $parent = Post::selectFirst(['owner-id'], $condition);
1434 if (!DBA::isResult($parent)) {
1435 Logger::warning('Item not found', ['condition' => $condition]);
1439 // Only distribute public items from native networks
1440 $condition = ['id' => $itemid, 'uid' => 0,
1441 'network' => array_merge(Protocol::FEDERATED ,['']),
1442 'visible' => true, 'deleted' => false, 'private' => [self::PUBLIC, self::UNLISTED]];
1443 $item = Post::selectFirst(array_merge(self::ITEM_FIELDLIST, ['protocol']), $condition);
1444 if (!DBA::isResult($item)) {
1445 Logger::warning('Item not found', ['condition' => $condition]);
1449 $origin = $item['origin'];
1453 /// @todo add a field "pcid" in the contact table that referrs to the public contact id.
1454 $owner = DBA::selectFirst('contact', ['url', 'nurl', 'alias'], ['id' => $parent['owner-id']]);
1455 if (!DBA::isResult($owner)) {
1459 $condition = ['nurl' => $owner['nurl'], 'rel' => [Contact::SHARING, Contact::FRIEND]];
1460 $contacts = DBA::select('contact', ['uid'], $condition);
1461 while ($contact = DBA::fetch($contacts)) {
1462 if ($contact['uid'] == 0) {
1466 $users[$contact['uid']] = $contact['uid'];
1468 DBA::close($contacts);
1470 $condition = ['alias' => $owner['url'], 'rel' => [Contact::SHARING, Contact::FRIEND]];
1471 $contacts = DBA::select('contact', ['uid'], $condition);
1472 while ($contact = DBA::fetch($contacts)) {
1473 if ($contact['uid'] == 0) {
1477 $users[$contact['uid']] = $contact['uid'];
1479 DBA::close($contacts);
1481 if (!empty($owner['alias'])) {
1482 $condition = ['nurl' => Strings::normaliseLink($owner['alias']), 'rel' => [Contact::SHARING, Contact::FRIEND]];
1483 $contacts = DBA::select('contact', ['uid'], $condition);
1484 while ($contact = DBA::fetch($contacts)) {
1485 if ($contact['uid'] == 0) {
1489 $users[$contact['uid']] = $contact['uid'];
1491 DBA::close($contacts);
1496 if ($item['uri-id'] != $item['parent-uri-id']) {
1497 $parents = Post::select(['uid', 'origin'], ["`uri-id` = ? AND `uid` != 0", $item['parent-uri-id']]);
1498 while ($parent = Post::fetch($parents)) {
1499 $users[$parent['uid']] = $parent['uid'];
1500 if ($parent['origin'] && !$origin) {
1501 $origin_uid = $parent['uid'];
1504 DBA::close($parents);
1507 foreach ($users as $uid) {
1508 if ($origin_uid == $uid) {
1509 $item['diaspora_signed_text'] = $signed_text;
1511 $item['post-reason'] = self::PR_DISTRIBUTE;
1512 self::storeForUser($item, $uid);
1517 * Store a public item defined by their URI-ID for the given users
1519 * @param integer $uri_id URI-ID of the given item
1520 * @param integer $uid The user that will receive the item entry
1521 * @param array $fields Additional fields to be stored
1522 * @param integer $source_uid User id of the source post
1523 * @return integer stored item id
1525 public static function storeForUserByUriId(int $uri_id, int $uid, array $fields = [], int $source_uid = 0): int
1527 if ($uid == $source_uid) {
1528 Logger::warning('target UID must not be be equal to the source UID', ['uri-id' => $uri_id, 'uid' => $uid]);
1532 $item = Post::selectFirst(array_merge(self::ITEM_FIELDLIST, ['protocol']), ['uri-id' => $uri_id, 'uid' => $source_uid]);
1533 if (!DBA::isResult($item)) {
1534 Logger::warning('Item could not be fetched', ['uri-id' => $uri_id, 'uid' => $source_uid]);
1538 if (($uid != 0) && ($item['gravity'] == GRAVITY_PARENT)) {
1539 $owner = User::getOwnerDataById($uid);
1540 if (($owner['contact-type'] == User::ACCOUNT_TYPE_COMMUNITY) && !Tag::isMentioned($uri_id, $owner['url'])) {
1541 Logger::info('Target user is a forum but is not mentioned here, thread will not be stored', ['uid' => $uid, 'uri-id' => $uri_id]);
1546 if (($source_uid == 0) && (($item['private'] == self::PRIVATE) || !in_array($item['network'], Protocol::FEDERATED))) {
1547 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']]);
1551 $item['post-reason'] = self::PR_STORED;
1553 $item = array_merge($item, $fields);
1555 $item['post-reason'] = self::getPostReason($item);
1557 $is_reshare = ($item['gravity'] == GRAVITY_ACTIVITY) && ($item['verb'] == Activity::ANNOUNCE);
1559 if (($uid != 0) && (($item['gravity'] == GRAVITY_PARENT) || $is_reshare) &&
1560 DI::pConfig()->get($uid, 'system', 'accept_only_sharer') == self::COMPLETION_NONE &&
1561 !in_array($item['post-reason'], [self::PR_FOLLOWER, self::PR_TAG, self::PR_TO, self::PR_CC])) {
1562 Logger::info('Contact is not a follower, thread will not be stored', ['author' => $item['author-link'], 'uid' => $uid, 'uri-id' => $uri_id]);
1566 $causer = $item['causer-id'] ?: $item['author-id'];
1568 if (($uri_id != $item['parent-uri-id']) && ($item['gravity'] == GRAVITY_COMMENT) && !Post::exists(['uri-id' => $item['parent-uri-id'], 'uid' => $uid])) {
1569 if (!self::fetchParent($item['parent-uri-id'], $uid, $causer)) {
1570 Logger::info('Parent post had not been added', ['uri-id' => $item['parent-uri-id'], 'uid' => $uid, 'causer' => $causer]);
1573 Logger::info('Fetched parent post', ['uri-id' => $item['parent-uri-id'], 'uid' => $uid, 'causer' => $causer]);
1574 } elseif (($uri_id != $item['thr-parent-id']) && $is_reshare && !Post::exists(['uri-id' => $item['thr-parent-id'], 'uid' => $uid])) {
1575 if (!self::fetchParent($item['thr-parent-id'], $uid, $causer)) {
1576 Logger::info('Thread parent had not been added', ['uri-id' => $item['thr-parent-id'], 'uid' => $uid, 'causer' => $causer]);
1579 Logger::info('Fetched thread parent', ['uri-id' => $item['thr-parent-id'], 'uid' => $uid, 'causer' => $causer]);
1582 $stored = self::storeForUser($item, $uid);
1583 Logger::info('Item stored for user', ['uri-id' => $item['uri-id'], 'uid' => $uid, 'causer' => $causer, 'source-uid' => $source_uid, 'stored' => $stored]);
1588 * Fetch the parent with the given uri-id
1590 * @param integer $uri_id
1591 * @param integer $uid
1592 * @param integer $causer
1596 private static function fetchParent(int $uri_id, int $uid, int $causer): int
1598 // Fetch the origin user for the post
1599 $origin_uid = self::GetOriginUidForUriId($uri_id, $uid);
1600 if (is_null($origin_uid)) {
1601 Logger::info('Origin item was not found', ['uid' => $uid, 'uri-id' => $uri_id]);
1605 return self::storeForUserByUriId($uri_id, $uid, ['causer-id' => $causer, 'post-reason' => self::PR_FETCHED], $origin_uid);
1609 * Returns the origin uid of a post if the given user is allowed to see it.
1615 private static function GetOriginUidForUriId(int $uriid, int $uid)
1617 if (Post::exists(['uri-id' => $uriid, 'uid' => $uid])) {
1621 $post = Post::selectFirst(['uid', 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid', 'private'], ['uri-id' => $uriid, 'origin' => true]);
1622 if (!empty($post)) {
1623 if (in_array($post['private'], [Item::PUBLIC, Item::UNLISTED])) {
1624 return $post['uid'];
1627 $pcid = Contact::getPublicIdByUserId($uid);
1632 foreach (Item::enumeratePermissions($post, true) as $receiver) {
1633 if ($receiver == $pcid) {
1634 return $post['uid'];
1641 if (Post::exists(['uri-id' => $uriid, 'uid' => 0])) {
1645 // When the post belongs to a a forum then all forum users are allowed to access it
1646 foreach (Tag::getByURIId($uriid, [Tag::MENTION, Tag::EXCLUSIVE_MENTION]) as $tag) {
1647 if (DBA::exists('contact', ['uid' => $uid, 'nurl' => Strings::normaliseLink($tag['url']), 'contact-type' => Contact::TYPE_COMMUNITY])) {
1648 $target_uid = User::getIdForURL($tag['url']);
1649 if (!empty($target_uid)) {
1659 * Store a public item array for the given users
1661 * @param array $item The item entry that will be stored
1662 * @param integer $uid The user that will receive the item entry
1663 * @return integer stored item id
1664 * @throws \Exception
1666 private static function storeForUser(array $item, int $uid): int
1668 $post = Post::selectFirst(['id'], ['uri-id' => $item['uri-id'], 'uid' => $uid]);
1669 if (!empty($post['id'])) {
1670 if (!empty($item['event-id'])) {
1671 $event_post = Post::selectFirst(['event-id'], ['uri-id' => $item['uri-id'], 'uid' => $uid]);
1672 if (!empty($event_post['event-id'])) {
1673 $event = DBA::selectFirst('event', ['edited', 'start', 'finish', 'summary', 'desc', 'location', 'nofinish', 'adjust'], ['id' => $item['event-id']]);
1674 if (!empty($event)) {
1675 // We aren't using "Event::store" here, since we don't want to trigger any further action
1676 $ret = DBA::update('event', $event, ['id' => $event_post['event-id']]);
1677 Logger::info('Event updated', ['uid' => $uid, 'source-event' => $item['event-id'], 'target-event' => $event_post['event-id'], 'ret' => $ret]);
1681 Logger::info('Item already exists', ['uri-id' => $item['uri-id'], 'uid' => $uid, 'id' => $post['id']]);
1685 // Data from the "post-user" table
1687 unset($item['mention']);
1688 unset($item['starred']);
1689 unset($item['unseen']);
1690 unset($item['psid']);
1691 unset($item['pinned']);
1692 unset($item['ignored']);
1693 unset($item['pubmail']);
1694 unset($item['event-id']);
1695 unset($item['hidden']);
1696 unset($item['notification-type']);
1698 // Data from the "post-delivery-data" table
1699 unset($item['postopts']);
1700 unset($item['inform']);
1702 $item['uid'] = $uid;
1703 $item['origin'] = 0;
1706 $item['contact-id'] = self::contactId($item);
1709 if ($item['gravity'] == GRAVITY_PARENT) {
1710 $contact = DBA::selectFirst('contact', [], ['id' => $item['contact-id'], 'self' => false]);
1711 if (DBA::isResult($contact)) {
1712 $notify = self::isRemoteSelf($contact, $item);
1716 $distributed = self::insert($item, $notify);
1718 if (!$distributed) {
1719 Logger::info("Distributed item wasn't stored", ['uri-id' => $item['uri-id'], 'user' => $uid]);
1721 Logger::info('Distributed item was stored', ['uri-id' => $item['uri-id'], 'user' => $uid, 'stored' => $distributed]);
1723 return $distributed;
1727 * Add a shadow entry for a given item id that is a thread starter
1729 * We store every public item entry additionally with the user id "0".
1730 * This is used for the community page and for the search.
1731 * It is planned that in the future we will store public item entries only once.
1733 * @param integer $itemid Item ID that should be added
1734 * @throws \Exception
1736 private static function addShadow(int $itemid)
1738 $fields = ['uid', 'private', 'visible', 'deleted', 'network', 'uri-id'];
1739 $condition = ['id' => $itemid, 'gravity' => GRAVITY_PARENT];
1740 $item = Post::selectFirst($fields, $condition);
1742 if (!DBA::isResult($item)) {
1746 // is it already a copy?
1747 if (($itemid == 0) || ($item['uid'] == 0)) {
1751 // Is it a visible public post?
1752 if (!$item["visible"] || $item["deleted"] || ($item["private"] == self::PRIVATE)) {
1756 // is it an entry from a connector? Only add an entry for natively connected networks
1757 if (!in_array($item["network"], array_merge(Protocol::FEDERATED ,['']))) {
1761 if (Post::exists(['uri-id' => $item['uri-id'], 'uid' => 0])) {
1765 $item = Post::selectFirst(array_merge(self::ITEM_FIELDLIST, ['protocol']), ['id' => $itemid]);
1767 if (DBA::isResult($item)) {
1768 // Preparing public shadow (removing user specific data)
1771 unset($item['parent']);
1772 unset($item['wall']);
1773 unset($item['mention']);
1774 unset($item['origin']);
1775 unset($item['starred']);
1776 unset($item['postopts']);
1777 unset($item['inform']);
1778 unset($item['post-reason']);
1779 if ($item['uri-id'] == $item['parent-uri-id']) {
1780 $item['contact-id'] = $item['owner-id'];
1782 $item['contact-id'] = $item['author-id'];
1785 $public_shadow = self::insert($item);
1787 Logger::info('Stored public shadow', ['thread' => $itemid, 'id' => $public_shadow]);
1792 * Add a shadow entry for a given item id that is a comment
1794 * This function does the same like the function above - but for comments
1796 * @param integer $itemid Item ID that should be added
1797 * @throws \Exception
1799 private static function addShadowPost(int $itemid)
1801 $item = Post::selectFirst(array_merge(self::ITEM_FIELDLIST, ['protocol']), ['id' => $itemid]);
1802 if (!DBA::isResult($item)) {
1806 // Is it a toplevel post?
1807 if ($item['gravity'] == GRAVITY_PARENT) {
1808 self::addShadow($itemid);
1812 // Is this a shadow entry?
1813 if ($item['uid'] == 0) {
1817 // Is there a shadow parent?
1818 if (!Post::exists(['uri-id' => $item['parent-uri-id'], 'uid' => 0])) {
1822 // Is there already a shadow entry?
1823 if (Post::exists(['uri-id' => $item['uri-id'], 'uid' => 0])) {
1827 // Save "origin" and "parent" state
1828 $origin = $item['origin'];
1829 $parent = $item['parent'];
1831 // Preparing public shadow (removing user specific data)
1834 unset($item['parent']);
1835 unset($item['wall']);
1836 unset($item['mention']);
1837 unset($item['origin']);
1838 unset($item['starred']);
1839 unset($item['postopts']);
1840 unset($item['inform']);
1841 unset($item['post-reason']);
1842 $item['contact-id'] = Contact::getIdForURL($item['author-link']);
1844 $public_shadow = self::insert($item);
1846 Logger::info('Stored public shadow', ['uri-id' => $item['uri-id'], 'id' => $public_shadow]);
1848 // If this was a comment to a Diaspora post we don't get our comment back.
1849 // This means that we have to distribute the comment by ourselves.
1850 if ($origin && Post::exists(['id' => $parent, 'network' => Protocol::DIASPORA])) {
1851 self::distribute($public_shadow);
1856 * Adds a language specification in a "language" element of given $arr.
1857 * Expects "body" element to exist in $arr.
1859 * @param array $item
1860 * @return string detected language
1861 * @throws \Text_LanguageDetect_Exception
1863 private static function getLanguage(array $item): string
1865 if (!empty($item['language'])) {
1866 return $item['language'];
1869 if (!in_array($item['gravity'], [GRAVITY_PARENT, GRAVITY_COMMENT]) || empty($item['body'])) {
1873 $languages = self::getLanguageArray(trim($item['title'] . "\n" . $item['body']), 3);
1874 if (empty($languages)) {
1878 return json_encode($languages);
1882 * Get a language array from a given text
1884 * @param string $body
1885 * @param integer $count
1888 public static function getLanguageArray(string $body, int $count): array
1890 // Convert attachments to links
1891 $naked_body = BBCode::removeAttachment($body);
1892 if (empty($naked_body)) {
1896 // Remove links and pictures
1897 $naked_body = BBCode::removeLinks($naked_body);
1899 // Convert the title and the body to plain text
1900 $naked_body = BBCode::toPlaintext($naked_body);
1902 // Remove possibly remaining links
1903 $naked_body = preg_replace(Strings::autoLinkRegEx(), '', $naked_body);
1905 if (empty($naked_body)) {
1909 $naked_body = self::getDominantLanguage($naked_body);
1911 $availableLanguages = DI::l10n()->getAvailableLanguages();
1912 // See https://github.com/friendica/friendica/issues/10511
1913 // Persian is manually added to language detection until a persian translation is provided for the interface, at
1914 // which point it will be automatically available through `getAvailableLanguages()` and this should be removed.
1915 $availableLanguages['fa'] = 'fa';
1917 $ld = new Language(array_keys($availableLanguages));
1918 return $ld->detect($naked_body)->limit(0, $count)->close() ?: [];
1922 * Check if latin or non latin are dominant in the body and only return the dominant one
1924 * @param string $body
1927 private static function getDominantLanguage(string $body): string
1931 for ($i = 0; $i < mb_strlen($body); $i++) {
1932 $character = mb_substr($body, $i, 1);
1933 $ord = mb_ord($character);
1935 // We add the most common characters to both strings.
1936 if (($ord <= 64) || ($ord >= 91 && $ord <= 96) || ($ord >= 123 && $ord <= 191) || in_array($ord, [215, 247]) || ($ord >= 697 && $ord <= 735) || ($ord > 65535)) {
1937 $latin .= $character;
1938 $non_latin .= $character;
1939 } elseif ($ord < 768) {
1940 $latin .= $character;
1942 $non_latin .= $character;
1945 return (mb_strlen($latin) > mb_strlen($non_latin)) ? $latin : $non_latin;
1948 public static function getLanguageMessage(array $item): string
1950 $iso639 = new \Matriphe\ISO639\ISO639;
1952 $used_languages = '';
1953 foreach (json_decode($item['language'], true) as $language => $reliability) {
1954 $used_languages .= $iso639->languageByCode1($language) . ' (' . $language . "): " . number_format($reliability, 5) . '\n';
1956 $used_languages = DI::l10n()->t('Detected languages in this post:\n%s', $used_languages);
1957 return $used_languages;
1961 * Creates an unique guid out of a given uri.
1962 * This function is used for messages outside the fediverse (Connector posts, feeds, Mails, ...)
1963 * Posts that are created on this system are using System::createUUID.
1964 * Received ActivityPub posts are using Processor::getGUIDByURL.
1966 * @param string $uri uri of an item entry
1967 * @param string|null $host hostname for the GUID prefix
1968 * @return string Unique guid
1970 public static function guidFromUri(string $uri, string $host = null): string
1972 // Our regular guid routine is using this kind of prefix as well
1973 // We have to avoid that different routines could accidentally create the same value
1974 $parsed = parse_url($uri);
1976 // Remove the scheme to make sure that "https" and "http" doesn't make a difference
1977 unset($parsed['scheme']);
1979 // Glue it together to be able to make a hash from it
1980 $host_id = implode('/', $parsed);
1982 // Use a mixture of several hashes to provide some GUID like experience
1983 return hash('crc32', $host) . '-'. hash('joaat', $host_id) . '-'. hash('fnv164', $host_id);
1987 * generate an unique URI
1989 * @param string $guid An existing GUID (Otherwise it will be generated)
1992 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1994 public static function newURI(string $guid = ''): string
1997 $guid = System::createUUID();
2000 return DI::baseUrl()->get() . '/objects/' . $guid;
2004 * Set "success_update" and "last-item" to the date of the last time we heard from this contact
2006 * This can be used to filter for inactive contacts.
2007 * Only do this for public postings to avoid privacy problems, since poco data is public.
2008 * Don't set this value if it isn't from the owner (could be an author that we don't know)
2010 * @param array $arr Contains the just posted item record
2011 * @throws \Exception
2013 private static function updateContact(array $arr)
2015 // Unarchive the author
2016 $contact = DBA::selectFirst('contact', [], ['id' => $arr["author-id"]]);
2017 if (DBA::isResult($contact)) {
2018 Contact::unmarkForArchival($contact);
2021 // Unarchive the contact if it's not our own contact
2022 $contact = DBA::selectFirst('contact', [], ['id' => $arr["contact-id"], 'self' => false]);
2023 if (DBA::isResult($contact)) {
2024 Contact::unmarkForArchival($contact);
2027 /// @todo On private posts we could obfuscate the date
2028 $update = ($arr['private'] != self::PRIVATE) || in_array($arr['network'], Protocol::FEDERATED);
2030 // Is it a forum? Then we don't care about the rules from above
2031 if (!$update && in_array($arr["network"], [Protocol::ACTIVITYPUB, Protocol::DFRN]) && ($arr["parent-uri-id"] === $arr["uri-id"])) {
2032 if (DBA::exists('contact', ['id' => $arr['contact-id'], 'forum' => true])) {
2038 // The "self" contact id is used (for example in the connectors) when the contact is unknown
2039 // So we have to ensure to only update the last item when it had been our own post,
2040 // or it had been done by a "regular" contact.
2041 if (!empty($arr['wall'])) {
2042 $condition = ['id' => $arr['contact-id']];
2044 $condition = ['id' => $arr['contact-id'], 'self' => false];
2046 Contact::update(['failed' => false, 'local-data' => true, 'success_update' => $arr['received'], 'last-item' => $arr['received']], $condition);
2048 // Now do the same for the system wide contacts with uid=0
2049 if ($arr['private'] != self::PRIVATE) {
2050 Contact::update(['failed' => false, 'local-data' => true, 'success_update' => $arr['received'], 'last-item' => $arr['received']],
2051 ['id' => $arr['owner-id']]);
2053 if ($arr['owner-id'] != $arr['author-id']) {
2054 Contact::update(['failed' => false, 'local-data' => true, 'success_update' => $arr['received'], 'last-item' => $arr['received']],
2055 ['id' => $arr['author-id']]);
2060 public static function setHashtags(string $body): string
2062 $body = BBCode::performWithEscapedTags($body, ['noparse', 'pre', 'code', 'img'], function ($body) {
2063 $tags = BBCode::getTags($body);
2066 if (!count($tags)) {
2070 // This sorting is important when there are hashtags that are part of other hashtags
2071 // Otherwise there could be problems with hashtags like #test and #test2
2072 // Because of this we are sorting from the longest to the shortest tag.
2073 usort($tags, function ($a, $b) {
2074 return strlen($b) <=> strlen($a);
2077 $URLSearchString = "^\[\]";
2079 // All hashtags should point to the home server if "local_tags" is activated
2080 if (DI::config()->get('system', 'local_tags')) {
2081 $body = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
2082 "#[url=" . DI::baseUrl() . "/search?tag=$2]$2[/url]", $body);
2085 // mask hashtags inside of url, bookmarks and attachments to avoid urls in urls
2086 $body = preg_replace_callback("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
2088 return ("[url=" . str_replace("#", "#", $match[1]) . "]" . str_replace("#", "#", $match[2]) . "[/url]");
2091 $body = preg_replace_callback("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism",
2093 return ("[bookmark=" . str_replace("#", "#", $match[1]) . "]" . str_replace("#", "#", $match[2]) . "[/bookmark]");
2096 $body = preg_replace_callback("/\[attachment (.*?)\](.*?)\[\/attachment\]/ism",
2098 return ("[attachment " . str_replace("#", "#", $match[1]) . "]" . $match[2] . "[/attachment]");
2101 // Repair recursive urls
2102 $body = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
2105 foreach ($tags as $tag) {
2106 if ((strpos($tag, '#') !== 0) || strpos($tag, '[url=') || strlen($tag) < 2 || $tag[1] == '#') {
2110 $basetag = str_replace('_', ' ', substr($tag, 1));
2111 $newtag = '#[url=' . DI::baseUrl() . '/search?tag=' . $basetag . ']' . $basetag . '[/url]';
2113 $body = str_replace($tag, $newtag, $body);
2116 // Convert back the masked hashtags
2117 $body = str_replace("#", "#", $body);
2126 * look for mention tags and setup a second delivery chain for forum/community posts if appropriate
2129 * @param int $item_id
2130 * @return boolean true if item was deleted, else false
2131 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2132 * @throws \ImagickException
2134 private static function tagDeliver(int $uid, int $item_id): bool
2138 $owner = User::getOwnerDataById($uid);
2139 if (!DBA::isResult($owner)) {
2140 Logger::warning('User not found, quitting here.', ['uid' => $uid]);
2144 if ($owner['contact-type'] != User::ACCOUNT_TYPE_COMMUNITY) {
2145 Logger::debug('Owner is no community, quitting here.', ['uid' => $uid, 'id' => $item_id]);
2149 $item = Post::selectFirst(self::ITEM_FIELDLIST, ['id' => $item_id, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT], 'origin' => false]);
2150 if (!DBA::isResult($item)) {
2151 Logger::debug('Post is an activity or origin or not found at all, quitting here.', ['id' => $item_id]);
2155 if ($item['gravity'] == GRAVITY_PARENT) {
2156 if (Tag::isMentioned($item['uri-id'], $owner['url'])) {
2157 Logger::info('Mention found in tag.', ['uri' => $item['uri'], 'uid' => $uid, 'id' => $item_id, 'uri-id' => $item['uri-id'], 'guid' => $item['guid']]);
2159 Logger::info('Top-level post without mention is deleted.', ['uri' => $item['uri'], $uid, 'id' => $item_id, 'uri-id' => $item['uri-id'], 'guid' => $item['guid']]);
2160 Post\User::delete(['uri-id' => $item['uri-id'], 'uid' => $item['uid']]);
2164 $arr = ['item' => $item, 'user' => $owner];
2166 Hook::callAll('tagged', $arr);
2168 if (Tag::isMentioned($item['parent-uri-id'], $owner['url'])) {
2169 Logger::info('Mention found in parent tag.', ['uri' => $item['uri'], 'uid' => $uid, 'id' => $item_id, 'uri-id' => $item['uri-id'], 'guid' => $item['guid']]);
2171 Logger::debug('No mentions found in parent, quitting here.', ['id' => $item_id, 'uri-id' => $item['uri-id'], 'guid' => $item['guid']]);
2176 Logger::info('Community post will be distributed', ['uri' => $item['uri'], 'uid' => $uid, 'id' => $item_id, 'uri-id' => $item['uri-id'], 'guid' => $item['guid']]);
2178 if ($owner['page-flags'] == User::PAGE_FLAGS_PRVGROUP) {
2180 $allow_gid = '<' . Group::FOLLOWERS . '>';
2183 self::performActivity($item['id'], 'announce', $uid, $allow_cid, $allow_gid, $deny_cid, $deny_gid);
2185 self::performActivity($item['id'], 'announce', $uid);
2188 Logger::info('Community post had been distributed', ['uri' => $item['uri'], 'uid' => $uid, 'id' => $item_id, 'uri-id' => $item['uri-id'], 'guid' => $item['guid']]);
2193 * Automatically reshare the item if the "remote_self" option is selected
2195 * @param array $item
2198 private static function autoReshare(array $item)
2200 if ($item['gravity'] != GRAVITY_PARENT) {
2204 if (!DBA::exists('contact', ['id' => $item['contact-id'], 'remote_self' => Contact::MIRROR_NATIVE_RESHARE])) {
2208 if (!in_array($item['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN])) {
2212 Logger::info('Automatically reshare item', ['uid' => $item['uid'], 'id' => $item['id'], 'guid' => $item['guid'], 'uri-id' => $item['uri-id']]);
2214 self::performActivity($item['id'], 'announce', $item['uid']);
2217 public static function isRemoteSelf(array $contact, array &$datarray): bool
2219 if (!$contact['remote_self']) {
2223 // Prevent the forwarding of posts that are forwarded
2224 if (!empty($datarray["extid"]) && ($datarray["extid"] == Protocol::DFRN)) {
2225 Logger::info('Already forwarded');
2229 // Prevent to forward already forwarded posts
2230 if ($datarray["app"] == DI::baseUrl()->getHostname()) {
2231 Logger::info('Already forwarded (second test)');
2235 // Only forward posts
2236 if ($datarray["verb"] != Activity::POST) {
2237 Logger::info('No post');
2241 if (($contact['network'] != Protocol::FEED) && ($datarray['private'] == self::PRIVATE)) {
2242 Logger::info('Not public');
2246 $datarray2 = $datarray;
2247 Logger::info('remote-self start', ['contact' => $contact['url'], 'remote_self'=> $contact['remote_self'], 'item' => $datarray]);
2248 if ($contact['remote_self'] == Contact::MIRROR_OWN_POST) {
2249 $self = DBA::selectFirst('contact', ['id', 'name', 'url', 'thumb'],
2250 ['uid' => $contact['uid'], 'self' => true]);
2251 if (DBA::isResult($self)) {
2252 $datarray['contact-id'] = $self["id"];
2254 $datarray['owner-name'] = $self["name"];
2255 $datarray['owner-link'] = $self["url"];
2256 $datarray['owner-avatar'] = $self["thumb"];
2258 $datarray['author-name'] = $datarray['owner-name'];
2259 $datarray['author-link'] = $datarray['owner-link'];
2260 $datarray['author-avatar'] = $datarray['owner-avatar'];
2262 unset($datarray['edited']);
2264 unset($datarray['network']);
2265 unset($datarray['owner-id']);
2266 unset($datarray['author-id']);
2269 if ($contact['network'] != Protocol::FEED) {
2270 $old_uri_id = $datarray["uri-id"] ?? 0;
2271 $datarray["guid"] = System::createUUID();
2272 unset($datarray["plink"]);
2273 $datarray["uri"] = self::newURI($datarray["guid"]);
2274 $datarray["uri-id"] = ItemURI::getIdByURI($datarray["uri"]);
2275 $datarray["extid"] = Protocol::DFRN;
2276 $urlpart = parse_url($datarray2['author-link']);
2277 $datarray["app"] = $urlpart["host"];
2278 if (!empty($old_uri_id)) {
2279 Post\Media::copy($old_uri_id, $datarray["uri-id"]);
2282 unset($datarray["parent-uri"]);
2283 unset($datarray["thr-parent"]);
2285 $datarray['private'] = self::PUBLIC;
2289 if ($contact['network'] != Protocol::FEED) {
2290 // Store the original post
2291 $result = self::insert($datarray2);
2292 Logger::info('remote-self post original item', ['contact' => $contact['url'], 'result'=> $result, 'item' => $datarray2]);
2294 $datarray["app"] = "Feed";
2298 return (bool)$result;
2305 * @param array $item
2308 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2309 * @throws \ImagickException
2311 public static function fixPrivatePhotos(string $s, int $uid, array $item = null, int $cid = 0): string
2313 if (DI::config()->get('system', 'disable_embedded')) {
2317 Logger::info('check for photos');
2318 $site = substr(DI::baseUrl(), strpos(DI::baseUrl(), '://'));
2323 $img_start = strpos($orig_body, '[img');
2324 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
2325 $img_len = ($img_start !== false ? strpos(substr($orig_body, $img_start + $img_st_close + 1), '[/img]') : false);
2327 while (($img_st_close !== false) && ($img_len !== false)) {
2328 $img_st_close++; // make it point to AFTER the closing bracket
2329 $image = substr($orig_body, $img_start + $img_st_close, $img_len);
2331 Logger::info('found photo', ['image' => $image]);
2333 if (stristr($image, $site . '/photo/')) {
2334 // Only embed locally hosted photos
2336 $i = basename($image);
2337 $i = str_replace(['.jpg', '.png', '.gif'], ['', '', ''], $i);
2338 $x = strpos($i, '-');
2341 $res = substr($i, $x + 1);
2342 $i = substr($i, 0, $x);
2343 $photo = Photo::getPhotoForUser($uid, $i, $res);
2344 if (DBA::isResult($photo)) {
2346 * Check to see if we should replace this photo link with an embedded image
2347 * 1. No need to do so if the photo is public
2348 * 2. If there's a contact-id provided, see if they're in the access list
2349 * for the photo. If so, embed it.
2350 * 3. Otherwise, if we have an item, see if the item permissions match the photo
2351 * permissions, regardless of order but first check to see if they're an exact
2352 * match to save some processing overhead.
2354 if (self::hasPermissions($photo)) {
2356 $recips = self::enumeratePermissions($photo);
2357 if (in_array($cid, $recips)) {
2361 if (self::samePermissions($uid, $item, $photo)) {
2367 $photo_img = Photo::getImageForPhoto($photo);
2368 // If a custom width and height were specified, apply before embedding
2369 if (preg_match("/\[img\=([0-9]*)x([0-9]*)\]/is", substr($orig_body, $img_start, $img_st_close), $match)) {
2370 Logger::info('scaling photo');
2372 $width = intval($match[1]);
2373 $height = intval($match[2]);
2375 $photo_img->scaleDown(max($width, $height));
2378 $data = $photo_img->asString();
2379 $type = $photo_img->getType();
2381 Logger::info('replacing photo');
2382 $image = 'data:' . $type . ';base64,' . base64_encode($data);
2383 Logger::debug('replaced', ['image' => $image]);
2389 $new_body = $new_body . substr($orig_body, 0, $img_start + $img_st_close) . $image . '[/img]';
2390 $orig_body = substr($orig_body, $img_start + $img_st_close + $img_len + strlen('[/img]'));
2391 if ($orig_body === false) {
2395 $img_start = strpos($orig_body, '[img');
2396 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
2397 $img_len = ($img_start !== false ? strpos(substr($orig_body, $img_start + $img_st_close + 1), '[/img]') : false);
2400 $new_body = $new_body . $orig_body;
2405 private static function hasPermissions(array $obj)
2407 return !empty($obj['allow_cid']) || !empty($obj['allow_gid']) ||
2408 !empty($obj['deny_cid']) || !empty($obj['deny_gid']);
2411 // @TODO $uid is unused parameter
2412 private static function samePermissions($uid, array $obj1, array $obj2): bool
2414 // first part is easy. Check that these are exactly the same.
2415 if (($obj1['allow_cid'] == $obj2['allow_cid'])
2416 && ($obj1['allow_gid'] == $obj2['allow_gid'])
2417 && ($obj1['deny_cid'] == $obj2['deny_cid'])
2418 && ($obj1['deny_gid'] == $obj2['deny_gid'])) {
2422 // This is harder. Parse all the permissions and compare the resulting set.
2423 $recipients1 = self::enumeratePermissions($obj1);
2424 $recipients2 = self::enumeratePermissions($obj2);
2428 /// @TODO Comparison of arrays, maybe use array_diff_assoc() here?
2429 return ($recipients1 == $recipients2);
2433 * Returns an array of contact-ids that are allowed to see this object
2435 * @param array $obj Item array with at least uid, allow_cid, allow_gid, deny_cid and deny_gid
2436 * @param bool $check_dead Prunes unavailable contacts from the result
2438 * @throws \Exception
2440 public static function enumeratePermissions(array $obj, bool $check_dead = false): array
2442 $aclFormater = DI::aclFormatter();
2444 $allow_people = $aclFormater->expand($obj['allow_cid']);
2445 $allow_groups = Group::expand($obj['uid'], $aclFormater->expand($obj['allow_gid']), $check_dead);
2446 $deny_people = $aclFormater->expand($obj['deny_cid']);
2447 $deny_groups = Group::expand($obj['uid'], $aclFormater->expand($obj['deny_gid']), $check_dead);
2448 $recipients = array_unique(array_merge($allow_people, $allow_groups));
2449 $deny = array_unique(array_merge($deny_people, $deny_groups));
2450 $recipients = array_diff($recipients, $deny);
2454 public static function expire(int $uid, int $days, string $network = "", bool $force = false)
2456 if (!$uid || ($days < 1)) {
2460 $condition = ["`uid` = ? AND NOT `deleted` AND `gravity` = ?",
2461 $uid, GRAVITY_PARENT];
2464 * $expire_network_only = save your own wall posts
2465 * and just expire conversations started by others
2467 $expire_network_only = DI::pConfig()->get($uid, 'expire', 'network_only', false);
2469 if ($expire_network_only) {
2470 $condition[0] .= " AND NOT `wall`";
2473 if ($network != "") {
2474 $condition[0] .= " AND `network` = ?";
2475 $condition[] = $network;
2478 $condition[0] .= " AND `received` < ?";
2479 $condition[] = DateTimeFormat::utc('now - ' . $days . ' day');
2481 $items = Post::select(['resource-id', 'starred', 'id', 'post-type', 'uid', 'uri-id'], $condition);
2483 if (!DBA::isResult($items)) {
2487 $expire_items = DI::pConfig()->get($uid, 'expire', 'items', true);
2489 // Forcing expiring of items - but not notes and marked items
2491 $expire_items = true;
2494 $expire_notes = DI::pConfig()->get($uid, 'expire', 'notes', true);
2495 $expire_starred = DI::pConfig()->get($uid, 'expire', 'starred', true);
2496 $expire_photos = DI::pConfig()->get($uid, 'expire', 'photos', false);
2500 $priority = DI::config()->get('system', 'expire-notify-priority');
2502 while ($item = Post::fetch($items)) {
2503 // don't expire filed items
2504 if (DBA::exists('post-category', ['uri-id' => $item['uri-id'], 'uid' => $item['uid'], 'type' => Post\Category::FILE])) {
2508 // Only expire posts, not photos and photo comments
2510 if (!$expire_photos && !empty($item['resource-id'])) {
2512 } elseif (!$expire_starred && intval($item['starred'])) {
2514 } elseif (!$expire_notes && ($item['post-type'] == self::PT_PERSONAL_NOTE)) {
2516 } elseif (!$expire_items && ($item['post-type'] != self::PT_PERSONAL_NOTE)) {
2520 self::markForDeletionById($item['id'], $priority);
2525 Logger::notice('User ' . $uid . ": expired $expired items; expire items: $expire_items, expire notes: $expire_notes, expire starred: $expire_starred, expire photos: $expire_photos");
2528 public static function firstPostDate(int $uid, bool $wall = false)
2530 $user = User::getById($uid, ['register_date']);
2535 $condition = ["`uid` = ? AND `wall` = ? AND NOT `deleted` AND `visible` AND `received` >= ?",
2536 $uid, $wall, $user['register_date']];
2537 $params = ['order' => ['received' => false]];
2538 $thread = Post::selectFirstThread(['received'], $condition, $params);
2539 if (DBA::isResult($thread)) {
2540 $postdate = substr(DateTimeFormat::local($thread['received']), 0, 10);
2547 * add/remove activity to an item
2549 * Toggle activities as like,dislike,attend of an item
2551 * @param int $item_id
2552 * @param string $verb
2553 * Activity verb. One of
2554 * like, unlike, dislike, undislike, attendyes, unattendyes,
2555 * attendno, unattendno, attendmaybe, unattendmaybe,
2556 * announce, unannouce
2558 * @param string $allow_cid
2559 * @param string $allow_gid
2560 * @param string $deny_cid
2561 * @param string $deny_gid
2563 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2564 * @throws \ImagickException
2565 * @hook 'post_local_end'
2567 * 'post_id' => ID of posted item
2569 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
2575 Logger::notice('Start create activity', ['verb' => $verb, 'item' => $item_id, 'user' => $uid]);
2577 $item = Post::selectFirst(self::ITEM_FIELDLIST, ['id' => $item_id]);
2578 if (!DBA::isResult($item)) {
2579 Logger::warning('Post had not been fetched', ['id' => $item_id]);
2583 $uri_id = $item['uri-id'];
2585 if (!in_array($item['uid'], [0, $uid])) {
2589 if (!Post::exists(['uri-id' => $item['parent-uri-id'], 'uid' => $uid])) {
2590 $stored = self::storeForUserByUriId($item['parent-uri-id'], $uid, ['post-reason' => Item::PR_ACTIVITY]);
2591 if (($item['parent-uri-id'] == $item['uri-id']) && !empty($stored)) {
2592 $item = Post::selectFirst(self::ITEM_FIELDLIST, ['id' => $stored]);
2593 if (!DBA::isResult($item)) {
2594 Logger::info('Could not fetch just created item - should not happen', ['stored' => $stored, 'uid' => $uid, 'uri-id' => $uri_id]);
2600 // Retrieves the local post owner
2601 $owner = User::getOwnerDataById($uid);
2602 if (empty($owner)) {
2603 Logger::info('Empty owner for user', ['uid' => $uid]);
2607 // Retrieve the current logged in user's public contact
2608 $author_id = Contact::getPublicIdByUserId($uid);
2609 if (empty($author_id)) {
2610 Logger::info('Empty public contact');
2618 $activity = Activity::LIKE;
2622 $activity = Activity::DISLIKE;
2626 $activity = Activity::ATTEND;
2630 $activity = Activity::ATTENDNO;
2633 case 'unattendmaybe':
2634 $activity = Activity::ATTENDMAYBE;
2638 $activity = Activity::FOLLOW;
2642 $activity = Activity::ANNOUNCE;
2645 Logger::warning('unknown verb', ['verb' => $verb, 'item' => $item_id]);
2649 $mode = Strings::startsWith($verb, 'un') ? 'delete' : 'create';
2651 // Enable activity toggling instead of on/off
2652 $event_verb_flag = $activity === Activity::ATTEND || $activity === Activity::ATTENDNO || $activity === Activity::ATTENDMAYBE;
2654 // Look for an existing verb row
2655 // Event participation activities are mutually exclusive, only one of them can exist at all times.
2656 if ($event_verb_flag) {
2657 $verbs = [Activity::ATTEND, Activity::ATTENDNO, Activity::ATTENDMAYBE];
2659 // Translate to the index based activity index
2661 foreach ($verbs as $verb) {
2662 $vids[] = Verb::getID($verb);
2665 $vids = Verb::getID($activity);
2668 $condition = ['vid' => $vids, 'deleted' => false, 'gravity' => GRAVITY_ACTIVITY,
2669 'author-id' => $author_id, 'uid' => $item['uid'], 'thr-parent-id' => $uri_id];
2670 $like_item = Post::selectFirst(['id', 'guid', 'verb'], $condition);
2672 if (DBA::isResult($like_item)) {
2674 * Truth table for existing activities
2676 * | Inputs || Outputs |
2677 * |----------------------------||-------------------|
2678 * | Mode | Event | Same verb || Delete? | Return? |
2679 * |--------|-------|-----------||---------|---------|
2680 * | create | Yes | Yes || No | Yes |
2681 * | create | Yes | No || Yes | No |
2682 * | create | No | Yes || No | Yes |
2683 * | create | No | No || N/A†|
2684 * | delete | Yes | Yes || Yes | N/A‡ |
2685 * | delete | Yes | No || No | N/A‡ |
2686 * | delete | No | Yes || Yes | N/A‡ |
2687 * | delete | No | No || N/A†|
2688 * |--------|-------|-----------||---------|---------|
2689 * | A | B | C || A xor C | !B or C |
2691 * †Can't happen: It's impossible to find an existing non-event activity without
2692 * the same verb because we are only looking for this single verb.
2694 * ‡ The "mode = delete" is returning early whether an existing activity was found or not.
2696 if ($mode == 'create' xor $like_item['verb'] == $activity) {
2697 self::markForDeletionById($like_item['id']);
2700 if (!$event_verb_flag || $like_item['verb'] == $activity) {
2705 // No need to go further if we aren't creating anything
2706 if ($mode == 'delete') {
2710 $objtype = $item['resource-id'] ? Activity\ObjectType::IMAGE : Activity\ObjectType::NOTE;
2713 'guid' => System::createUUID(),
2714 'uri' => self::newURI(),
2716 'contact-id' => $owner['id'],
2717 'wall' => $item['wall'],
2719 'network' => Protocol::DFRN,
2720 'protocol' => Conversation::PARCEL_DIRECT,
2721 'direction' => Conversation::PUSH,
2722 'gravity' => GRAVITY_ACTIVITY,
2723 'parent' => $item['id'],
2724 'thr-parent' => $item['uri'],
2725 'owner-id' => $author_id,
2726 'author-id' => $author_id,
2727 'body' => $activity,
2728 'verb' => $activity,
2729 'object-type' => $objtype,
2730 'allow_cid' => $allow_cid ?? $item['allow_cid'],
2731 'allow_gid' => $allow_gid ?? $item['allow_gid'],
2732 'deny_cid' => $deny_cid ?? $item['deny_cid'],
2733 'deny_gid' => $deny_gid ?? $item['deny_gid'],
2738 if (in_array($activity, [Activity::LIKE, Activity::DISLIKE])) {
2739 $signed = Diaspora::createLikeSignature($uid, $new_item);
2740 if (!empty($signed)) {
2741 $new_item['diaspora_signed_text'] = json_encode($signed);
2745 self::insert($new_item, true);
2747 // If the parent item isn't visible then set it to visible
2748 // @todo Check if this is still needed
2749 if (!$item['visible']) {
2750 self::update(['visible' => true], ['id' => $item['id']]);
2756 * Fetch the SQL condition for the given user id
2758 * @param integer $owner_id User ID for which the permissions should be fetched
2759 * @return array condition
2761 public static function getPermissionsConditionArrayByUserId(int $owner_id): array
2763 $local_user = local_user();
2764 $remote_user = Session::getRemoteContactID($owner_id);
2766 // default permissions - anonymous user
2767 $condition = ["`private` != ?", self::PRIVATE];
2769 if ($local_user && ($local_user == $owner_id)) {
2770 // Profile owner - everything is visible
2772 } elseif ($remote_user) {
2773 // Authenticated visitor - fetch the matching permissionsets
2774 $permissionSets = DI::permissionSet()->selectByContactId($remote_user, $owner_id);
2776 $condition = ["(`private` != ? OR (`private` = ? AND `wall`
2777 AND `psid` IN (" . implode(', ', array_fill(0, count($set), '?')) . ")))",
2778 self::PRIVATE, self::PRIVATE];
2779 $condition = array_merge($condition, $permissionSets->column('id'));
2787 * Get a permission SQL string for the given user
2789 * @param int $owner_id
2790 * @param string $table
2793 public static function getPermissionsSQLByUserId(int $owner_id, string $table = ''): string
2795 $local_user = local_user();
2796 $remote_user = Session::getRemoteContactID($owner_id);
2798 if (!empty($table)) {
2799 $table = DBA::quoteIdentifier($table) . '.';
2803 * Construct permissions
2805 * default permissions - anonymous user
2807 $sql = sprintf(" AND " . $table . "`private` != %d", self::PRIVATE);
2809 // Profile owner - everything is visible
2810 if ($local_user && ($local_user == $owner_id)) {
2812 } elseif ($remote_user) {
2814 * Authenticated visitor. Unless pre-verified,
2815 * check that the contact belongs to this $owner_id
2816 * and load the groups the visitor belongs to.
2817 * If pre-verified, the caller is expected to have already
2818 * done this and passed the groups into this function.
2820 $permissionSets = DI::permissionSet()->selectByContactId($remote_user, $owner_id);
2823 $sql_set = sprintf(" OR (" . $table . "`private` = %d AND " . $table . "`wall` AND " . $table . "`psid` IN (", self::PRIVATE) . implode(',', $permissionSets->column('id')) . "))";
2828 $sql = sprintf(" AND (" . $table . "`private` != %d", self::PRIVATE) . $sql_set . ")";
2835 * get translated item type
2837 * @param array $item
2838 * @param \Friendica\Core\L10n $l10n
2841 public static function postType(array $item, \Friendica\Core\L10n $l10n): string
2843 if (!empty($item['event-id'])) {
2844 return $l10n->t('event');
2845 } elseif (!empty($item['resource-id'])) {
2846 return $l10n->t('photo');
2847 } elseif ($item['gravity'] == GRAVITY_ACTIVITY) {
2848 return $l10n->t('activity');
2849 } elseif ($item['gravity'] == GRAVITY_COMMENT) {
2850 return $l10n->t('comment');
2853 return $l10n->t('post');
2857 * Sets the "rendered-html" field of the provided item
2859 * Body is preserved to avoid side-effects as we modify it just-in-time for spoilers and private image links
2861 * @param array $item
2863 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2864 * @todo Remove reference, simply return "rendered-html" and "rendered-hash"
2866 private static function putInCache(&$item)
2868 // Save original body to prevent addons to modify it
2869 $body = $item['body'];
2871 $rendered_hash = $item['rendered-hash'] ?? '';
2872 $rendered_html = $item['rendered-html'] ?? '';
2874 if ($rendered_hash == ''
2875 || $rendered_html == ''
2876 || $rendered_hash != hash('md5', BBCode::VERSION . '::' . $body)
2877 || DI::config()->get('system', 'ignore_cache')
2879 $item['rendered-html'] = BBCode::convertForUriId($item['uri-id'], $item['body']);
2880 $item['rendered-hash'] = hash('md5', BBCode::VERSION . '::' . $body);
2882 $hook_data = ['item' => $item, 'rendered-html' => $item['rendered-html'], 'rendered-hash' => $item['rendered-hash']];
2883 Hook::callAll('put_item_in_cache', $hook_data);
2884 $item['rendered-html'] = $hook_data['rendered-html'];
2885 $item['rendered-hash'] = $hook_data['rendered-hash'];
2888 // Update if the generated values differ from the existing ones
2889 if ((($rendered_hash != $item['rendered-hash']) || ($rendered_html != $item['rendered-html'])) && !empty($item['id'])) {
2892 'rendered-html' => $item['rendered-html'],
2893 'rendered-hash' => $item['rendered-hash']
2895 ['id' => $item['id']]
2900 $item['body'] = $body;
2904 * Given an item array, convert the body element from bbcode to html and add smilie icons.
2905 * If attach is true, also add icons for item attachments.
2907 * @param array $item Record from item table
2908 * @param boolean $attach If true, add icons for item attachments as well
2909 * @param boolean $is_preview Whether this is a preview
2910 * @param boolean $only_cache Whether only cached HTML should be updated
2911 * @return string item body html
2912 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2913 * @throws \ImagickException
2914 * @hook prepare_body_init item array before any work
2915 * @hook prepare_body_content_filter ('item'=>item array, 'filter_reasons'=>string array) before first bbcode to html
2916 * @hook prepare_body ('item'=>item array, 'html'=>body string, 'is_preview'=>boolean, 'filter_reasons'=>string array) after first bbcode to html
2917 * @hook prepare_body_final ('item'=>item array, 'html'=>body string) after attach icons and blockquote special case handling (spoiler, author)
2919 public static function prepareBody(array &$item, bool $attach = false, bool $is_preview = false, bool $only_cache = false): string
2922 Hook::callAll('prepare_body_init', $item);
2924 // In order to provide theme developers more possibilities, event items
2925 // are treated differently.
2926 if ($item['object-type'] === Activity\ObjectType::EVENT && isset($item['event-id'])) {
2927 $ev = Event::getItemHTML($item);
2931 $tags = Tag::populateFromItem($item);
2933 $item['tags'] = $tags['tags'];
2934 $item['hashtags'] = $tags['hashtags'];
2935 $item['mentions'] = $tags['mentions'];
2937 $body = $item['body'] ?? '';
2938 $shared = BBCode::fetchShareAttributes($body);
2939 if (!empty($shared['guid'])) {
2940 $shared_item = Post::selectFirst(['uri-id', 'plink', 'has-media'], ['guid' => $shared['guid']]);
2941 $shared_uri_id = $shared_item['uri-id'] ?? 0;
2942 $shared_links = [strtolower($shared_item['plink'] ?? '')];
2943 $shared_attachments = Post\Media::splitAttachments($shared_uri_id, $shared['guid'], [], $shared_item['has-media'] ?? false);
2944 $shared_links = array_merge($shared_links, array_column($shared_attachments['visual'], 'url'));
2945 $shared_links = array_merge($shared_links, array_column($shared_attachments['link'], 'url'));
2946 $shared_links = array_merge($shared_links, array_column($shared_attachments['additional'], 'url'));
2947 $item['body'] = self::replaceVisualAttachments($shared_attachments, $item['body']);
2953 $attachments = Post\Media::splitAttachments($item['uri-id'], $item['guid'] ?? '', $shared_links, $item['has-media'] ?? false);
2954 $item['body'] = self::replaceVisualAttachments($attachments, $item['body'] ?? '');
2956 $item['body'] = preg_replace("/\s*\[attachment .*?\].*?\[\/attachment\]\s*/ism", "\n", $item['body']);
2957 self::putInCache($item);
2958 $item['body'] = $body;
2959 $s = $item["rendered-html"];
2965 // Compile eventual content filter reasons
2966 $filter_reasons = [];
2967 if (!$is_preview && public_contact() != $item['author-id']) {
2968 if (!empty($item['content-warning']) && (!local_user() || !DI::pConfig()->get(local_user(), 'system', 'disable_cw', false))) {
2969 $filter_reasons[] = DI::l10n()->t('Content warning: %s', $item['content-warning']);
2972 $item['attachments'] = $attachments;
2976 'filter_reasons' => $filter_reasons
2978 Hook::callAll('prepare_body_content_filter', $hook_data);
2979 $filter_reasons = $hook_data['filter_reasons'];
2986 'preview' => $is_preview,
2987 'filter_reasons' => $filter_reasons
2989 Hook::callAll('prepare_body', $hook_data);
2990 $s = $hook_data['html'];
2994 // Replace the blockquotes with quotes that are used in mails.
2995 $mailquote = '<blockquote type="cite" class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex;">';
2996 $s = str_replace(['<blockquote>', '<blockquote class="spoiler">', '<blockquote class="author">'], [$mailquote, $mailquote, $mailquote], $s);
3000 if (!empty($shared_attachments)) {
3001 $s = self::addVisualAttachments($shared_attachments, $item, $s, true);
3002 $s = self::addLinkAttachment($shared_uri_id ?: $item['uri-id'], $shared_attachments, $body, $s, true, []);
3003 $s = self::addNonVisualAttachments($shared_attachments, $item, $s, true);
3004 $body = preg_replace("/\s*\[share .*?\].*?\[\/share\]\s*/ism", '', $body);
3007 $s = self::addVisualAttachments($attachments, $item, $s, false);
3008 $s = self::addLinkAttachment($item['uri-id'], $attachments, $body, $s, false, $shared_links);
3009 $s = self::addNonVisualAttachments($attachments, $item, $s, false);
3010 $s = self::addQuestions($item, $s);
3013 if (strpos($s, '<div class="map">') !== false && !empty($item['coord'])) {
3014 $x = Map::byCoordinates(trim($item['coord']));
3016 $s = preg_replace('/\<div class\=\"map\"\>/', '$0' . $x, $s);
3020 // Replace friendica image url size with theme preference.
3021 if (!empty($a->getThemeInfoValue('item_image_size'))) {
3022 $ps = $a->getThemeInfoValue('item_image_size');
3023 $s = preg_replace('|(<img[^>]+src="[^"]+/photo/[0-9a-f]+)-[0-9]|', "$1-" . $ps, $s);
3026 $s = HTML::applyContentFilter($s, $filter_reasons);
3028 $hook_data = ['item' => $item, 'html' => $s];
3029 Hook::callAll('prepare_body_final', $hook_data);
3031 return $hook_data['html'];
3035 * Check if the body contains a link
3037 * @param string $body
3038 * @param string $url
3042 public static function containsLink(string $body, string $url, int $type = 0): bool
3044 // Make sure that for example site parameters aren't used when testing if the link is contained in the body
3045 $urlparts = parse_url($url);
3046 if (!empty($urlparts)) {
3047 unset($urlparts['query']);
3048 unset($urlparts['fragment']);
3049 $url = (string)Uri::fromParts($urlparts);
3054 // Remove media links to only search in embedded content
3055 // @todo Check images for image link, audio for audio links, ...
3056 if (in_array($type, [Post\Media::AUDIO, Post\Media::VIDEO, Post\Media::IMAGE])) {
3057 $body = preg_replace("/\[url=[^\[\]]*\](.*)\[\/url\]/Usi", ' $1 ', $body);
3060 if (strpos($body, $url)) {
3063 foreach ([0, 1, 2] as $size) {
3064 if (preg_match('#/photo/.*-' . $size . '\.#ism', $url) &&
3065 strpos(preg_replace('#(/photo/.*)-[012]\.#ism', '$1-' . $size . '.', $body), $url)) {
3073 * Replace visual attachments in the body
3075 * @param array $attachments
3076 * @param string $body
3077 * @return string modified body
3079 private static function replaceVisualAttachments(array $attachments, string $body): string
3081 DI::profiler()->startRecording('rendering');
3083 foreach ($attachments['visual'] as $attachment) {
3084 if (!empty($attachment['preview'])) {
3085 $proxy = Post\Media::getPreviewUrlForId($attachment['id'], Proxy::SIZE_LARGE);
3086 $search = ['[img=' . $attachment['preview'] . ']', ']' . $attachment['preview'] . '[/img]'];
3087 $replace = ['[img=' . $proxy . ']', ']' . $proxy . '[/img]'];
3089 $body = str_replace($search, $replace, $body);
3090 } elseif ($attachment['filetype'] == 'image') {
3091 $proxy = Post\Media::getUrlForId($attachment['id']);
3092 $search = ['[img=' . $attachment['url'] . ']', ']' . $attachment['url'] . '[/img]'];
3093 $replace = ['[img=' . $proxy . ']', ']' . $proxy . '[/img]'];
3095 $body = str_replace($search, $replace, $body);
3098 DI::profiler()->stopRecording();
3103 * Add visual attachments to the content
3105 * @param array $attachments
3106 * @param array $item
3107 * @param string $content
3108 * @return string modified content
3110 private static function addVisualAttachments(array $attachments, array $item, string $content, bool $shared): string
3112 DI::profiler()->startRecording('rendering');
3116 // @todo In the future we should make a single for the template engine with all media in it. This allows more flexibilty.
3117 foreach ($attachments['visual'] as $attachment) {
3118 if (self::containsLink($item['body'], $attachment['preview'] ?? $attachment['url'], $attachment['type'])) {
3122 if (!empty($attachment['preview'])) {
3123 $preview_url = Post\Media::getPreviewUrlForId($attachment['id'], Proxy::SIZE_LARGE);
3128 if (($attachment['filetype'] == 'video')) {
3129 /// @todo Move the template to /content as well
3130 $media = Renderer::replaceMacros(Renderer::getMarkupTemplate('video_top.tpl'), [
3132 'id' => $attachment['id'],
3133 'src' => $attachment['url'],
3134 'name' => $attachment['name'] ?: $attachment['url'],
3135 'preview' => $preview_url,
3136 'mime' => $attachment['mimetype'],
3139 if (($item['post-type'] ?? null) == Item::PT_VIDEO) {
3142 $trailing .= $media;
3144 } elseif ($attachment['filetype'] == 'audio') {
3145 $media = Renderer::replaceMacros(Renderer::getMarkupTemplate('content/audio.tpl'), [
3147 'id' => $attachment['id'],
3148 'src' => $attachment['url'],
3149 'name' => $attachment['name'] ?: $attachment['url'],
3150 'mime' => $attachment['mimetype'],
3153 if (($item['post-type'] ?? null) == Item::PT_AUDIO) {
3156 $trailing .= $media;
3158 } elseif ($attachment['filetype'] == 'image') {
3159 $media = Renderer::replaceMacros(Renderer::getMarkupTemplate('content/image.tpl'), [
3161 'src' => Post\Media::getUrlForId($attachment['id']),
3162 'preview' => Post\Media::getPreviewUrlForId($attachment['id'], ($attachment['width'] > $attachment['height']) ? Proxy::SIZE_MEDIUM : Proxy::SIZE_LARGE),
3163 'attachment' => $attachment,
3166 // On Diaspora posts the attached pictures are leading
3167 if ($item['network'] == Protocol::DIASPORA) {
3170 $trailing .= $media;
3176 $content = str_replace(BBCode::TOP_ANCHOR, '<div class="body-attach">' . $leading . '<div class="clear"></div></div>' . BBCode::TOP_ANCHOR, $content);
3177 $content = str_replace(BBCode::BOTTOM_ANCHOR, '<div class="body-attach">' . $trailing . '<div class="clear"></div></div>' . BBCode::BOTTOM_ANCHOR, $content);
3179 if ($leading != '') {
3180 $content = '<div class="body-attach">' . $leading . '<div class="clear"></div></div>' . $content;
3183 if ($trailing != '') {
3184 $content .= '<div class="body-attach">' . $trailing . '<div class="clear"></div></div>';
3188 DI::profiler()->stopRecording();
3193 * Add link attachment to the content
3195 * @param array $attachments
3196 * @param string $body
3197 * @param string $content
3198 * @param bool $shared
3199 * @param array $ignore_links A list of URLs to ignore
3200 * @return string modified content
3202 private static function addLinkAttachment(int $uriid, array $attachments, string $body, string $content, bool $shared, array $ignore_links): string
3204 DI::profiler()->startRecording('rendering');
3205 // Don't show a preview when there is a visual attachment (audio or video)
3206 $types = array_column($attachments['visual'], 'type');
3207 $preview = !in_array(Post\Media::IMAGE, $types) && !in_array(Post\Media::VIDEO, $types);
3209 if (!empty($attachments['link'])) {
3210 foreach ($attachments['link'] as $link) {
3212 foreach ($ignore_links as $ignore_link) {
3213 if (Strings::compareLink($link['url'], $ignore_link)) {
3217 // @todo Judge between the links to use the one with most information
3218 if (!$found && (empty($attachment) || !empty($link['author-name']) ||
3219 (empty($attachment['name']) && !empty($link['name'])) ||
3220 (empty($attachment['description']) && !empty($link['description'])) ||
3221 (empty($attachment['preview']) && !empty($link['preview'])))) {
3222 $attachment = $link;
3227 if (!empty($attachment)) {
3230 'author_name' => $attachment['author-name'] ?? '',
3231 'author_url' => $attachment['author-url'] ?? '',
3232 'description' => $attachment['description'] ?? '',
3235 'provider_name' => $attachment['publisher-name'] ?? '',
3236 'provider_url' => $attachment['publisher-url'] ?? '',
3238 'title' => $attachment['name'] ?? '',
3240 'url' => $attachment['url']];
3242 if ($preview && !empty($attachment['preview'])) {
3243 if ($attachment['preview-width'] >= 500) {
3244 $data['image'] = Post\Media::getPreviewUrlForId($attachment['id'], Proxy::SIZE_MEDIUM);
3246 $data['preview'] = Post\Media::getPreviewUrlForId($attachment['id'], Proxy::SIZE_MEDIUM);
3250 if (!empty($data['description']) && !empty($content)) {
3251 similar_text($data['description'], $content, $percent);
3256 if (!empty($data['description']) && (($data['title'] == $data['description']) || ($percent > 95) || (strpos($content, $data['description']) !== false))) {
3257 $data['description'] = '';
3260 if (($data['author_name'] ?? '') == ($data['provider_name'] ?? '')) {
3261 $data['author_name'] = '';
3264 if (($data['author_url'] ?? '') == ($data['provider_url'] ?? '')) {
3265 $data['author_url'] = '';
3267 } elseif (preg_match("/.*(\[attachment.*?\].*?\[\/attachment\]).*/ism", $body, $match)) {
3268 $data = BBCode::getAttachmentData($match[1]);
3270 DI::profiler()->stopRecording();
3272 if (isset($data['url']) && !in_array($data['url'], $ignore_links)) {
3273 if (!empty($data['description']) || !empty($data['image']) || !empty($data['preview'])) {
3274 $parts = parse_url($data['url']);
3275 if (!empty($parts['scheme']) && !empty($parts['host'])) {
3276 if (empty($data['provider_name'])) {
3277 $data['provider_name'] = $parts['host'];
3279 if (empty($data['provider_url']) || empty(parse_url($data['provider_url'], PHP_URL_SCHEME))) {
3280 $data['provider_url'] = $parts['scheme'] . '://' . $parts['host'];
3282 if (!empty($parts['port'])) {
3283 $data['provider_url'] .= ':' . $parts['port'];
3288 // @todo Use a template
3289 $rendered = BBCode::convertAttachment('', BBCode::INTERNAL, false, $data, $uriid);
3290 } elseif (!self::containsLink($content, $data['url'], Post\Media::HTML)) {
3291 $rendered = Renderer::replaceMacros(Renderer::getMarkupTemplate('content/link.tpl'), [
3292 '$url' => $data['url'],
3293 '$title' => $data['title'],
3300 return str_replace(BBCode::BOTTOM_ANCHOR, BBCode::BOTTOM_ANCHOR . $rendered, $content);
3302 return $content . $rendered;
3309 * Add non visual attachments to the content
3311 * @param array $attachments
3312 * @param array $item
3313 * @param string $content
3314 * @return string modified content
3316 private static function addNonVisualAttachments(array $attachments, array $item, string $content): string
3318 DI::profiler()->startRecording('rendering');
3320 foreach ($attachments['additional'] as $attachment) {
3321 if (strpos($item['body'], $attachment['url'])) {
3325 $author = ['uid' => 0, 'id' => $item['author-id'],
3326 'network' => $item['author-network'], 'url' => $item['author-link']];
3327 $the_url = Contact::magicLinkByContact($author, $attachment['url']);
3329 $title = Strings::escapeHtml(trim(($attachment['description'] ?? '') ?: $attachment['url']));
3331 if (!empty($attachment['size'])) {
3332 $title .= ' ' . $attachment['size'] . ' ' . DI::l10n()->t('bytes');
3335 /// @todo Use a template
3336 $icon = '<div class="attachtype icon s22 type-' . $attachment['filetype'] . ' subtype-' . $attachment['subtype'] . '"></div>';
3337 $trailing .= '<a href="' . strip_tags($the_url) . '" title="' . $title . '" class="attachlink" target="_blank" rel="noopener noreferrer" >' . $icon . '</a>';
3340 if ($trailing != '') {
3341 $content .= '<div class="body-attach">' . $trailing . '<div class="clear"></div></div>';
3344 DI::profiler()->stopRecording();
3348 private static function addQuestions(array $item, string $content): string
3350 DI::profiler()->startRecording('rendering');
3351 if (!empty($item['question-id'])) {
3353 'id' => $item['question-id'],
3354 'multiple' => $item['question-multiple'],
3355 'voters' => $item['question-voters'],
3356 'endtime' => $item['question-end-time']
3359 $options = Post\QuestionOption::getByURIId($item['uri-id']);
3360 foreach ($options as $key => $option) {
3361 if ($question['voters'] > 0) {
3362 $percent = $option['replies'] / $question['voters'] * 100;
3363 $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));
3365 $options[$key]['vote'] = DI::l10n()->tt('%2$s (%1$d vote)', '%2$s (%1$d votes)', $option['replies'], $option['name'], );
3369 if (!empty($question['voters']) && !empty($question['endtime'])) {
3370 $summary = DI::l10n()->tt('%d voter. Poll end: %s', '%d voters. Poll end: %s', $question['voters'], Temporal::getRelativeDate($question['endtime']));
3371 } elseif (!empty($question['voters'])) {
3372 $summary = DI::l10n()->tt('%d voter.', '%d voters.', $question['voters']);
3373 } elseif (!empty($question['endtime'])) {
3374 $summary = DI::l10n()->t('Poll end: %s', Temporal::getRelativeDate($question['endtime']));
3379 $content .= Renderer::replaceMacros(Renderer::getMarkupTemplate('content/question.tpl'), [
3380 '$question' => $question,
3381 '$options' => $options,
3382 '$summary' => $summary,
3385 DI::profiler()->stopRecording();
3390 * get private link for item
3392 * @param array $item
3393 * @return boolean|array False if item has not plink, otherwise array('href'=>plink url, 'title'=>translated title)
3394 * @throws \Exception
3396 public static function getPlink(array $item)
3398 if (!empty($item['plink']) && Network::isValidHttpUrl($item['plink'])) {
3399 $plink = $item['plink'];
3400 } elseif (!empty($item['uri']) && Network::isValidHttpUrl($item['uri']) && !Network::isLocalLink($item['uri'])) {
3401 $plink = $item['uri'];
3406 'href' => "display/" . $item['guid'],
3407 'orig' => "display/" . $item['guid'],
3408 'title' => DI::l10n()->t('View on separate page'),
3409 'orig_title' => DI::l10n()->t('View on separate page'),
3412 if (!empty($plink) && ($item['private'] == self::PRIVATE)) {
3413 $author = ['uid' => 0, 'id' => $item['author-id'],
3414 'network' => $item['author-network'], 'url' => $item['author-link']];
3415 $plink = Contact::magicLinkByContact($author, $plink);
3418 if (!empty($plink)) {
3419 $ret['href'] = DI::baseUrl()->remove($plink);
3420 $ret['title'] = DI::l10n()->t('Link to source');
3422 } elseif (!empty($plink) && ($item['private'] != self::PRIVATE)) {
3426 'title' => DI::l10n()->t('Link to source'),
3427 'orig_title' => DI::l10n()->t('Link to source'),
3437 * Does the given uri-id belongs to a post that is sent as starting post to a forum?
3439 * @param int $uri_id
3441 * @return boolean "true" when it is a forum post
3443 public static function isForumPost(int $uri_id): bool
3445 foreach (Tag::getByURIId($uri_id, [Tag::EXCLUSIVE_MENTION]) as $tag) {
3446 if (DBA::exists('contact', ['uid' => 0, 'nurl' => Strings::normaliseLink($tag['url']), 'contact-type' => Contact::TYPE_COMMUNITY])) {
3454 * Search item id for given URI or plink
3456 * @param string $uri
3457 * @param integer $uid
3459 * @return integer item id
3461 public static function searchByLink(string $uri, int $uid = 0): int
3463 $ssl_uri = str_replace('http://', 'https://', $uri);
3464 $uris = [$uri, $ssl_uri, Strings::normaliseLink($uri)];
3466 $item = Post::selectFirst(['id'], ['uri' => $uris, 'uid' => $uid]);
3467 if (DBA::isResult($item)) {
3471 $item = Post::selectFirst(['id'], ['plink' => $uris, 'uid' => $uid]);
3472 if (DBA::isResult($item)) {
3480 * Return the URI for a link to the post
3482 * @param string $uri URI or link to post
3484 * @return string URI
3486 public static function getURIByLink(string $uri): string
3488 $ssl_uri = str_replace('http://', 'https://', $uri);
3489 $uris = [$uri, $ssl_uri, Strings::normaliseLink($uri)];
3491 $item = Post::selectFirst(['uri'], ['uri' => $uris]);
3492 if (DBA::isResult($item)) {
3493 return $item['uri'];
3496 $item = Post::selectFirst(['uri'], ['plink' => $uris]);
3497 if (DBA::isResult($item)) {
3498 return $item['uri'];
3505 * Fetches item for given URI or plink
3507 * @param string $uri
3508 * @param integer $uid
3510 * @return integer item id
3512 public static function fetchByLink(string $uri, int $uid = 0): int
3514 Logger::info('Trying to fetch link', ['uid' => $uid, 'uri' => $uri]);
3515 $item_id = self::searchByLink($uri, $uid);
3516 if (!empty($item_id)) {
3517 Logger::info('Link found', ['uid' => $uid, 'uri' => $uri, 'id' => $item_id]);
3527 Hook::callAll('item_by_link', $hookData);
3529 if (isset($hookData['item_id'])) {
3530 return is_numeric($hookData['item_id']) ? $hookData['item_id'] : 0;
3533 $fetched_uri = ActivityPub\Processor::fetchMissingActivity($uri);
3536 $item_id = self::searchByLink($fetched_uri, $uid);
3538 $item_id = Diaspora::fetchByURL($uri);
3541 if (!empty($item_id)) {
3542 Logger::info('Link fetched', ['uid' => $uid, 'uri' => $uri, 'id' => $item_id]);
3546 Logger::info('Link not found', ['uid' => $uid, 'uri' => $uri]);
3551 * Return share data from an item array (if the item is shared item)
3552 * We are providing the complete Item array, because at some time in the future
3553 * we hopefully will define these values not in the body anymore but in some item fields.
3554 * This function is meant to replace all similar functions in the system.
3556 * @param array $item
3558 * @return array with share information
3560 public static function getShareArray(array $item): array
3562 return BBCode::fetchShareAttributes($item['body']);
3566 * Fetch item information for shared items from the original items and adds it.
3568 * @param array $item
3570 * @return array item array with data from the original item
3572 public static function addShareDataFromOriginal(array $item): array
3574 $shared = self::getShareArray($item);
3575 if (empty($shared)) {
3579 // Real reshares always have got a GUID.
3580 if (empty($shared['guid'])) {
3584 $uid = $item['uid'] ?? 0;
3586 // first try to fetch the item via the GUID. This will work for all reshares that had been created on this system
3587 $shared_item = Post::selectFirst(['title', 'body'], ['guid' => $shared['guid'], 'uid' => [0, $uid]]);
3588 if (!DBA::isResult($shared_item)) {
3589 if (empty($shared['link'])) {
3593 // Otherwhise try to find (and possibly fetch) the item via the link. This should work for Diaspora and ActivityPub posts
3594 $id = self::fetchByLink($shared['link'] ?? '', $uid);
3596 Logger::info('Original item not found', ['url' => $shared['link'] ?? '', 'callstack' => System::callstack()]);
3600 $shared_item = Post::selectFirst(['title', 'body'], ['id' => $id]);
3601 if (!DBA::isResult($shared_item)) {
3604 Logger::info('Got shared data from url', ['url' => $shared['link'], 'callstack' => System::callstack()]);
3606 Logger::info('Got shared data from guid', ['guid' => $shared['guid'], 'callstack' => System::callstack()]);
3609 if (!empty($shared_item['title'])) {
3610 $body = '[h3]' . $shared_item['title'] . "[/h3]\n" . $shared_item['body'];
3611 unset($shared_item['title']);
3613 $body = $shared_item['body'];
3616 $item['body'] = preg_replace("/\[share ([^\[\]]*)\].*\[\/share\]/ism", '[share $1]' . str_replace('$', '\$', $body) . '[/share]', $item['body']);
3617 unset($shared_item['body']);
3619 return array_merge($item, $shared_item);
3623 * Check a prospective item array against user-level permissions
3625 * @param array $item Expected keys: uri, gravity, and
3626 * author-link if is author-id is set,
3627 * owner-link if is owner-id is set,
3628 * causer-link if is causer-id is set.
3629 * @param int $user_id Local user ID
3631 * @throws \Exception
3633 protected static function isAllowedByUser(array $item, int $user_id): bool
3635 if (!empty($item['author-id']) && Contact\User::isBlocked($item['author-id'], $user_id)) {
3636 Logger::notice('Author is blocked by user', ['author-link' => $item['author-link'], 'uid' => $user_id, 'item-uri' => $item['uri']]);
3640 if (!empty($item['owner-id']) && Contact\User::isBlocked($item['owner-id'], $user_id)) {
3641 Logger::notice('Owner is blocked by user', ['owner-link' => $item['owner-link'], 'uid' => $user_id, 'item-uri' => $item['uri']]);
3645 // The causer is set during a thread completion, for example because of a reshare. It countains the responsible actor.
3646 if (!empty($item['causer-id']) && Contact\User::isBlocked($item['causer-id'], $user_id)) {
3647 Logger::notice('Causer is blocked by user', ['causer-link' => $item['causer-link'] ?? $item['causer-id'], 'uid' => $user_id, 'item-uri' => $item['uri']]);
3651 if (!empty($item['causer-id']) && ($item['gravity'] === GRAVITY_PARENT) && Contact\User::isIgnored($item['causer-id'], $user_id)) {
3652 Logger::notice('Causer is ignored by user', ['causer-link' => $item['causer-link'] ?? $item['causer-id'], 'uid' => $user_id, 'item-uri' => $item['uri']]);
3660 * Improve the data in shared posts
3662 * @param array $item
3663 * @return string body
3665 public static function improveSharedDataInBody(array $item): string
3667 $shared = BBCode::fetchShareAttributes($item['body']);
3668 if (empty($shared['link'])) {
3669 return $item['body'];
3672 $id = self::fetchByLink($shared['link']);
3673 Logger::info('Fetched shared post', ['uri-id' => $item['uri-id'], 'id' => $id, 'author' => $shared['profile'], 'url' => $shared['link'], 'guid' => $shared['guid'], 'callstack' => System::callstack()]);
3675 return $item['body'];
3678 $shared_item = Post::selectFirst(['author-name', 'author-link', 'author-avatar', 'plink', 'created', 'guid', 'title', 'body'], ['id' => $id]);
3679 if (!DBA::isResult($shared_item)) {
3680 return $item['body'];
3683 $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']);
3685 if (!empty($shared_item['title'])) {
3686 $shared_content .= '[h3]'.$shared_item['title'].'[/h3]'."\n";
3689 $shared_content .= $shared_item['body'];
3691 $item['body'] = preg_replace("/\[share.*?\](.*)\[\/share\]/ism", $shared_content . '[/share]', $item['body']);
3692 Logger::info('New shared data', ['uri-id' => $item['uri-id'], 'id' => $id, 'shared_item' => $shared_item]);
3693 return $item['body'];