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\System;
31 use Friendica\Model\Tag;
32 use Friendica\Core\Worker;
33 use Friendica\Database\DBA;
35 use Friendica\Protocol\Activity;
36 use Friendica\Protocol\ActivityPub;
37 use Friendica\Protocol\Diaspora;
38 use Friendica\Util\DateTimeFormat;
39 use Friendica\Util\Map;
40 use Friendica\Util\Network;
41 use Friendica\Util\Proxy;
42 use Friendica\Util\Strings;
43 use Friendica\Util\Temporal;
44 use Friendica\Worker\Delivery;
45 use GuzzleHttp\Psr7\Uri;
46 use LanguageDetection\Language;
50 // Posting types, inspired by https://www.w3.org/TR/activitystreams-vocabulary/#object-types
57 const PT_DOCUMENT = 19;
60 const PT_PERSONAL_NOTE = 128;
62 // Posting reasons (Why had a post been stored for a user?)
69 const PR_FOLLOWER = 69;
70 const PR_ANNOUNCEMENT = 70;
71 const PR_COMMENT = 71;
75 const PR_FETCHED = 75;
76 const PR_COMPLETION = 76;
78 const PR_ACTIVITY = 78;
79 const PR_DISTRIBUTE = 79;
83 // system.accept_only_sharer setting values
84 const COMPLETION_NONE = 1;
85 const COMPLETION_COMMENT = 0;
86 const COMPLETION_LIKE = 2;
88 // Field list that is used to display the items
89 const DISPLAY_FIELDLIST = [
90 'uid', 'id', 'parent', 'guid', 'network', 'gravity',
91 'uri-id', 'uri', 'thr-parent-id', 'thr-parent', 'parent-uri-id', 'parent-uri', 'conversation',
92 'commented', 'created', 'edited', 'received', 'verb', 'object-type', 'postopts', 'plink',
93 'wall', 'private', 'starred', 'origin', 'parent-origin', 'title', 'body', 'language',
94 'content-warning', 'location', 'coord', 'app', 'rendered-hash', 'rendered-html', 'object',
95 'quote-uri', 'quote-uri-id', 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid', 'mention', 'global',
96 'author-id', 'author-link', 'author-name', 'author-avatar', 'author-network', 'author-updated', 'author-gsid', 'author-addr', 'author-uri-id',
97 'owner-id', 'owner-link', 'owner-name', 'owner-avatar', 'owner-network', 'owner-contact-type', 'owner-updated',
98 'causer-id', 'causer-link', 'causer-name', 'causer-avatar', 'causer-contact-type', 'causer-network',
99 'contact-id', 'contact-uid', 'contact-link', 'contact-name', 'contact-avatar',
100 'writable', 'self', 'cid', 'alias',
101 'event-created', 'event-edited', 'event-start', 'event-finish',
102 'event-summary', 'event-desc', 'event-location', 'event-type',
103 'event-nofinish', 'event-ignore', 'event-id',
104 'question-id', 'question-multiple', 'question-voters', 'question-end-time',
105 'has-categories', 'has-media',
106 'delivery_queue_count', 'delivery_queue_done', 'delivery_queue_failed'
109 // Field list that is used to deliver items via the protocols
110 const DELIVER_FIELDLIST = ['uid', 'id', 'parent', 'uri-id', 'uri', 'thr-parent', 'parent-uri', 'guid',
111 'parent-guid', 'conversation', 'received', 'created', 'edited', 'verb', 'object-type', 'object', 'target',
112 'private', 'title', 'body', 'raw-body', 'location', 'coord', 'app',
113 'inform', 'deleted', 'extid', 'post-type', 'post-reason', 'gravity',
114 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid',
115 'author-id', 'author-addr', 'author-link', 'author-name', 'author-avatar', 'owner-id', 'owner-link', 'contact-uid',
116 'signed_text', 'network', 'wall', 'contact-id', 'plink', 'origin',
117 'thr-parent-id', 'parent-uri-id', 'quote-uri', 'quote-uri-id', 'postopts', 'pubmail',
118 'event-created', 'event-edited', 'event-start', 'event-finish',
119 'event-summary', 'event-desc', 'event-location', 'event-type',
120 'event-nofinish', 'event-ignore', 'event-id'];
122 // All fields in the item table
123 const ITEM_FIELDLIST = ['id', 'uid', 'parent', 'uri', 'parent-uri', 'thr-parent',
124 'guid', 'uri-id', 'parent-uri-id', 'thr-parent-id', 'conversation', 'vid',
125 'quote-uri', 'quote-uri-id', 'contact-id', 'wall', 'gravity', 'extid', 'psid',
126 'created', 'edited', 'commented', 'received', 'changed', 'verb',
127 'postopts', 'plink', 'resource-id', 'event-id', 'inform',
128 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid', 'post-type', 'post-reason',
129 'private', 'pubmail', 'visible', 'starred',
130 'unseen', 'deleted', 'origin', 'mention', 'global', 'network',
131 'title', 'content-warning', 'body', 'location', 'coord', 'app',
132 'rendered-hash', 'rendered-html', 'object-type', 'object', 'target-type', 'target',
133 'author-id', 'author-link', 'author-name', 'author-avatar', 'author-network',
134 'owner-id', 'owner-link', 'owner-name', 'owner-avatar', 'causer-id'];
136 // List of all verbs that don't need additional content data.
137 // Never reorder or remove entries from this list. Just add new ones at the end, if needed.
139 Activity::LIKE, Activity::DISLIKE,
140 Activity::ATTEND, Activity::ATTENDNO, Activity::ATTENDMAYBE,
149 // Item weight for query ordering
150 const GRAVITY_PARENT = 0;
151 const GRAVITY_ACTIVITY = 3;
152 const GRAVITY_COMMENT = 6;
153 const GRAVITY_UNKNOWN = 9;
156 * Update existing item entries
158 * @param array $fields The fields that are to be changed
159 * @param array $condition The condition for finding the item entries
161 * In the future we may have to change permissions as well.
162 * Then we had to add the user id as third parameter.
164 * A return value of "0" doesn't mean an error - but that 0 rows had been changed.
166 * @return integer|boolean number of affected rows - or "false" if there was an error
167 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
169 public static function update(array $fields, array $condition)
171 if (empty($condition) || empty($fields)) {
175 if (isset($fields['extid'])) {
176 $fields['external-id'] = ItemURI::getIdByURI($fields['extid']);
179 if (!empty($fields['verb'])) {
180 $fields['vid'] = Verb::getID($fields['verb']);
183 if (!empty($fields['edited'])) {
184 $previous = Post::selectFirst(['edited'], $condition);
187 $rows = Post::update($fields, $condition);
188 if (is_bool($rows)) {
192 // We only need to call the line by line update for specific fields
193 if (empty($fields['body']) && empty($fields['file']) &&
194 empty($fields['attach']) && empty($fields['edited'])) {
198 Logger::info('Updating per single row method', ['fields' => $fields, 'condition' => $condition]);
200 $items = Post::select(['id', 'origin', 'uri-id', 'uid', 'author-network', 'quote-uri-id'], $condition);
204 while ($item = DBA::fetch($items)) {
205 if (!empty($fields['body'])) {
206 if (!empty($item['quote-uri-id'])) {
207 $fields['body'] = BBCode::removeSharedData($fields['body']);
209 if (!empty($fields['raw-body'])) {
210 $fields['raw-body'] = BBCode::removeSharedData($fields['raw-body']);
214 Post\Media::insertFromAttachmentData($item['uri-id'], $fields['body']);
216 $content_fields = ['raw-body' => trim($fields['raw-body'] ?? $fields['body'])];
218 // Remove all media attachments from the body and store them in the post-media table
219 // @todo On shared postings (Diaspora style and commented reshare) don't fetch content from the shared part
220 $content_fields['raw-body'] = Post\Media::insertFromBody($item['uri-id'], $content_fields['raw-body']);
221 $content_fields['raw-body'] = self::setHashtags($content_fields['raw-body']);
223 Post\Media::insertFromRelevantUrl($item['uri-id'], $content_fields['raw-body']);
224 Post\Content::update($item['uri-id'], $content_fields);
227 if (!empty($fields['file'])) {
228 Post\Category::storeTextByURIId($item['uri-id'], $item['uid'], $fields['file']);
231 if (!empty($fields['attach'])) {
232 Post\Media::insertFromAttachment($item['uri-id'], $fields['attach']);
235 // We only need to notfiy others when it is an original entry from us.
236 // Only call the notifier when the item had been edited and records had been changed.
237 if ($item['origin'] && !empty($fields['edited']) && ($previous['edited'] != $fields['edited'])) {
238 $notify_items[] = $item['id'];
244 foreach ($notify_items as $notify_item) {
245 $post = Post::selectFirst(['uri-id', 'uid'], ['id' => $notify_item]);
246 Worker::add(Worker::PRIORITY_HIGH, 'Notifier', Delivery::POST, (int)$post['uri-id'], (int)$post['uid']);
253 * Delete an item and notify others about it - if it was ours
255 * @param array $condition The condition for finding the item entries
256 * @param integer $priority Priority for the notification
258 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
260 public static function markForDeletion(array $condition, int $priority = Worker::PRIORITY_HIGH)
262 $items = Post::select(['id'], $condition);
263 while ($item = Post::fetch($items)) {
264 self::markForDeletionById($item['id'], $priority);
270 * Delete an item for an user and notify others about it - if it was ours
272 * @param array $condition The condition for finding the item entries
273 * @param integer $uid User who wants to delete this item
275 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
277 public static function deleteForUser(array $condition, int $uid)
283 $items = Post::select(['id', 'uid', 'uri-id'], $condition);
284 while ($item = Post::fetch($items)) {
285 if (in_array($item['uid'], [$uid, 0])) {
286 Post\User::update($item['uri-id'], $uid, ['hidden' => true], true);
287 Post\ThreadUser::update($item['uri-id'], $uid, ['hidden' => true], true);
290 if ($item['uid'] == $uid) {
291 self::markForDeletionById($item['id'], Worker::PRIORITY_HIGH);
292 } elseif ($item['uid'] != 0) {
293 Logger::warning('Wrong ownership. Not deleting item', ['id' => $item['id']]);
300 * Mark an item for deletion, delete related data and notify others about it - if it was ours
302 * @param integer $item_id
303 * @param integer $priority Priority for the notification
304 * @return boolean success
305 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
307 public static function markForDeletionById(int $item_id, int $priority = Worker::PRIORITY_HIGH): bool
309 Logger::info('Mark item for deletion by id', ['id' => $item_id, 'callstack' => System::callstack()]);
310 // locate item to be deleted
311 $fields = ['id', 'uri', 'uri-id', 'uid', 'parent', 'parent-uri-id', 'origin',
312 'deleted', 'resource-id', 'event-id',
313 'verb', 'object-type', 'object', 'target', 'contact-id', 'psid', 'gravity'];
314 $item = Post::selectFirst($fields, ['id' => $item_id]);
315 if (!DBA::isResult($item)) {
316 Logger::info('Item not found.', ['id' => $item_id]);
320 if ($item['deleted']) {
321 Logger::info('Item has already been marked for deletion.', ['id' => $item_id]);
325 $parent = Post::selectFirst(['origin'], ['id' => $item['parent']]);
326 if (!DBA::isResult($parent)) {
327 $parent = ['origin' => false];
330 // clean up categories and tags so they don't end up as orphans
331 Post\Category::deleteByURIId($item['uri-id'], $item['uid']);
334 * If item is a link to a photo resource, nuke all the associated photos
335 * (visitors will not have photo resources)
336 * This only applies to photos uploaded from the photos page. Photos inserted into a post do not
337 * generate a resource-id and therefore aren't intimately linked to the item.
339 /// @TODO: this should first check if photo is used elsewhere
340 if (strlen($item['resource-id'])) {
341 Photo::delete(['resource-id' => $item['resource-id'], 'uid' => $item['uid']]);
344 // If item is a link to an event, delete the event.
345 if (intval($item['event-id'])) {
346 Event::delete($item['event-id']);
349 // If item has attachments, drop them
350 $attachments = Post\Media::getByURIId($item['uri-id'], [Post\Media::DOCUMENT]);
351 foreach($attachments as $attachment) {
352 if (preg_match('|attach/(\d+)|', $attachment['url'], $matches)) {
353 Attach::delete(['id' => $matches[1], 'uid' => $item['uid']]);
357 // Set the item to "deleted"
358 $item_fields = ['deleted' => true, 'edited' => DateTimeFormat::utcNow(), 'changed' => DateTimeFormat::utcNow()];
359 Post::update($item_fields, ['id' => $item['id']]);
361 Post\Category::storeTextByURIId($item['uri-id'], $item['uid'], '');
363 if (!Post::exists(["`uri-id` = ? AND `uid` != 0 AND NOT `deleted`", $item['uri-id']])) {
364 self::markForDeletion(['uri-id' => $item['uri-id'], 'uid' => 0, 'deleted' => false], $priority);
367 Post\DeliveryData::delete($item['uri-id']);
369 // If it's the parent of a comment thread, kill all the kids
370 if ($item['gravity'] == self::GRAVITY_PARENT) {
371 self::markForDeletion(['parent' => $item['parent'], 'deleted' => false], $priority);
374 // Is it our comment and/or our thread?
375 if (($item['origin'] || $parent['origin']) && ($item['uid'] != 0)) {
376 // When we delete the original post we will delete all existing copies on the server as well
377 self::markForDeletion(['uri-id' => $item['uri-id'], 'deleted' => false], $priority);
379 // send the notification upstream/downstream
381 Worker::add(['priority' => $priority, 'dont_fork' => true], 'Notifier', Delivery::DELETION, (int)$item['uri-id'], (int)$item['uid']);
383 } elseif ($item['uid'] != 0) {
384 Post\User::update($item['uri-id'], $item['uid'], ['hidden' => true]);
385 Post\ThreadUser::update($item['uri-id'], $item['uid'], ['hidden' => true]);
388 Logger::info('Item has been marked for deletion.', ['id' => $item_id]);
394 * Get guid from given item record
396 * @param array $item Item record
397 * @param bool Whether to notify (?)
398 * @return string Guid
400 public static function guid(array $item, bool $notify): string
402 if (!empty($item['guid'])) {
403 return trim($item['guid']);
407 // We have to avoid duplicates. So we create the GUID in form of a hash of the plink or uri.
408 // We add the hash of our own host because our host is the original creator of the post.
409 $prefix_host = DI::baseUrl()->getHostname();
413 // We are only storing the post so we create a GUID from the original hostname.
414 if (!empty($item['author-link'])) {
415 $parsed = parse_url($item['author-link']);
416 if (!empty($parsed['host'])) {
417 $prefix_host = $parsed['host'];
421 if (empty($prefix_host) && !empty($item['plink'])) {
422 $parsed = parse_url($item['plink']);
423 if (!empty($parsed['host'])) {
424 $prefix_host = $parsed['host'];
428 if (empty($prefix_host) && !empty($item['uri'])) {
429 $parsed = parse_url($item['uri']);
430 if (!empty($parsed['host'])) {
431 $prefix_host = $parsed['host'];
435 // Is it in the format data@host.tld? - Used for mail contacts
436 if (empty($prefix_host) && !empty($item['author-link']) && strstr($item['author-link'], '@')) {
437 $mailparts = explode('@', $item['author-link']);
438 $prefix_host = array_pop($mailparts);
442 if (!empty($item['plink'])) {
443 $guid = self::guidFromUri($item['plink'], $prefix_host);
444 } elseif (!empty($item['uri'])) {
445 $guid = self::guidFromUri($item['uri'], $prefix_host);
447 $guid = System::createUUID(hash('crc32', $prefix_host));
454 * Returns contact id from given item record
456 * @param array $item Item record
457 * @return int Contact id
459 private static function contactId(array $item): int
461 if ($item['uid'] == 0) {
462 return $item['author-id'];
465 if ($item['origin']) {
466 $owner = User::getOwnerDataById($item['uid']);
470 if (!empty($item['causer-id']) && Contact::isSharing($item['causer-id'], $item['uid'], true)) {
471 $cdata = Contact::getPublicAndUserContactID($item['causer-id'], $item['uid']);
472 if (!empty($cdata['user'])) {
473 return $cdata['user'];
477 if ($item['gravity'] == self::GRAVITY_PARENT) {
478 if (Contact::isSharingByURL($item['owner-link'], $item['uid'], true)) {
479 $contact_id = Contact::getIdForURL($item['owner-link'], $item['uid']);
481 $contact_id = Contact::getIdForURL($item['owner-link']);
483 if (!empty($contact_id)) {
488 if (Contact::isSharingByURL($item['author-link'], $item['uid'], true)) {
489 $contact_id = Contact::getIdForURL($item['author-link'], $item['uid']);
491 $contact_id = Contact::getIdForURL($item['author-link']);
494 if (!empty($contact_id)) {
498 Logger::warning('contact-id could not be fetched, using self contact instead.', ['uid' => $item['uid'], 'item' => $item]);
499 $self = Contact::selectFirst(['id'], ['self' => true, 'uid' => $item['uid']]);
504 * Write an item array into a spool file to be inserted later.
505 * This command is called whenever there are issues storing an item.
507 * @param array $item The item fields that are to be inserted
510 private static function spool(array $item)
512 // Now we store the data in the spool directory
513 // We use "microtime" to keep the arrival order and "mt_rand" to avoid duplicates
514 $file = 'item-' . round(microtime(true) * 10000) . '-' . mt_rand() . '.msg';
516 $spoolpath = System::getSpoolPath();
517 if ($spoolpath != '') {
518 $spool = $spoolpath . '/' . $file;
520 file_put_contents($spool, json_encode($item));
521 Logger::warning("Item wasn't stored - Item was spooled into file", ['file' => $file]);
526 * Check if the item array is a duplicate
528 * @param array $item Item record
529 * @return boolean is it a duplicate?
531 private static function isDuplicate(array $item): bool
533 // Checking if there is already an item with the same guid
534 $condition = ['guid' => $item['guid'], 'network' => $item['network'], 'uid' => $item['uid']];
535 if (Post::exists($condition)) {
536 Logger::notice('Found already existing item', $condition);
540 $condition = ['uri-id' => $item['uri-id'], 'uid' => $item['uid'],
541 'network' => [$item['network'], Protocol::DFRN]];
542 if (Post::exists($condition)) {
543 Logger::notice('duplicated item with the same uri found.', $condition);
547 // On Friendica and Diaspora the GUID is unique
548 if (in_array($item['network'], [Protocol::DFRN, Protocol::DIASPORA])) {
549 $condition = ['guid' => $item['guid'], 'uid' => $item['uid']];
550 if (Post::exists($condition)) {
551 Logger::notice('duplicated item with the same guid found.', $condition);
554 } elseif ($item['network'] == Protocol::OSTATUS) {
555 // Check for an existing post with the same content. There seems to be a problem with OStatus.
556 $condition = ["`body` = ? AND `network` = ? AND `created` = ? AND `contact-id` = ? AND `uid` = ?",
557 $item['body'], $item['network'], $item['created'], $item['contact-id'], $item['uid']];
558 if (Post::exists($condition)) {
559 Logger::notice('duplicated item with the same body found.', $item);
565 * Check for already added items.
566 * There is a timing issue here that sometimes creates double postings.
567 * An unique index would help - but the limitations of MySQL (maximum size of index values) prevent this.
569 if (($item['uid'] == 0) && Post::exists(['uri-id' => $item['uri-id'], 'uid' => 0])) {
570 Logger::notice('Global item already stored.', ['uri-id' => $item['uri-id'], 'network' => $item['network']]);
578 * Check if the item array is valid
580 * @param array $item Item record
581 * @return boolean item is valid
583 public static function isValid(array $item): bool
585 // When there is no content then we don't post it
586 if (($item['body'] . $item['title'] == '') && empty($item['quote-uri-id']) && (empty($item['uri-id']) || !Post\Media::existsByURIId($item['uri-id']))) {
587 Logger::notice('No body, no title.');
591 if (!empty($item['uid'])) {
592 $owner = User::getOwnerDataById($item['uid'], false);
594 Logger::warning('Missing item user owner data', ['uid' => $item['uid']]);
598 if ($owner['account_expired'] || $owner['account_removed']) {
599 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']]);
604 if (!empty($item['author-id']) && Contact::isBlocked($item['author-id'])) {
605 Logger::notice('Author is blocked node-wide', ['author-link' => $item['author-link'], 'item-uri' => $item['uri']]);
609 if (!empty($item['author-link']) && Network::isUrlBlocked($item['author-link'])) {
610 Logger::notice('Author server is blocked', ['author-link' => $item['author-link'], 'item-uri' => $item['uri']]);
614 if (!empty($item['owner-id']) && Contact::isBlocked($item['owner-id'])) {
615 Logger::notice('Owner is blocked node-wide', ['owner-link' => $item['owner-link'], 'item-uri' => $item['uri']]);
619 if (!empty($item['owner-link']) && Network::isUrlBlocked($item['owner-link'])) {
620 Logger::notice('Owner server is blocked', ['owner-link' => $item['owner-link'], 'item-uri' => $item['uri']]);
624 if (!empty($item['uid']) && !self::isAllowedByUser($item, $item['uid'])) {
628 if ($item['verb'] == Activity::FOLLOW) {
629 if (!$item['origin'] && ($item['author-id'] == Contact::getPublicIdByUserId($item['uid']))) {
630 // Our own follow request can be relayed to us. We don't store it to avoid notification chaos.
631 Logger::info("Follow: Don't store not origin follow request", ['parent-uri' => $item['parent-uri']]);
635 $condition = ['verb' => Activity::FOLLOW, 'uid' => $item['uid'],
636 'parent-uri' => $item['parent-uri'], 'author-id' => $item['author-id']];
637 if (Post::exists($condition)) {
638 // It happens that we receive multiple follow requests by the same author - we only store one.
639 Logger::info('Follow: Found existing follow request from author', ['author-id' => $item['author-id'], 'parent-uri' => $item['parent-uri']]);
648 * Check if the item array is too old
650 * @param array $item Item record
651 * @return boolean item is too old
653 public static function isTooOld(array $item): bool
655 // check for create date and expire time
656 $expire_interval = DI::config()->get('system', 'dbclean-expire-days', 0);
658 $user = DBA::selectFirst('user', ['expire'], ['uid' => $item['uid']]);
659 if (DBA::isResult($user) && ($user['expire'] > 0) && (($user['expire'] < $expire_interval) || ($expire_interval == 0))) {
660 $expire_interval = $user['expire'];
663 if (($expire_interval > 0) && !empty($item['created'])) {
664 $expire_date = time() - ($expire_interval * 86400);
665 $created_date = strtotime($item['created']);
666 if ($created_date < $expire_date) {
667 Logger::notice('Item created before expiration interval.', [
668 'created' => date('c', $created_date),
669 'expired' => date('c', $expire_date),
680 * Return the id of the given item array if it has been stored before
682 * @param array $item Item record
683 * @return integer Item id or zero on error
685 private static function getDuplicateID(array $item): int
687 if (empty($item['network']) || in_array($item['network'], Protocol::FEDERATED)) {
688 $condition = ['`uri-id` = ? AND `uid` = ? AND `network` IN (?, ?, ?, ?)',
691 Protocol::ACTIVITYPUB,
696 $existing = Post::selectFirst(['id', 'network'], $condition);
697 if (DBA::isResult($existing)) {
698 // We only log the entries with a different user id than 0. Otherwise we would have too many false positives
699 if ($item['uid'] != 0) {
700 Logger::notice('Item already existed for user', [
701 'uri-id' => $item['uri-id'],
702 'uid' => $item['uid'],
703 'network' => $item['network'],
704 'existing_id' => $existing['id'],
705 'existing_network' => $existing['network']
709 return $existing['id'];
716 * Fetch the uri-id of the parent for the given uri-id
718 * @param integer $uriid
721 public static function getParent(int $uriid): int
723 $thread_parent = Post::selectFirstPost(['thr-parent-id', 'gravity'], ['uri-id' => $uriid]);
724 if (empty($thread_parent)) {
728 if ($thread_parent['gravity'] == Item::GRAVITY_PARENT) {
732 return self::getParent($thread_parent['thr-parent-id']);
736 * Fetch top-level parent data for the given item array
739 * @return array item array with parent data
742 private static function getTopLevelParent(array $item): array
744 $fields = ['uid', 'uri', 'parent-uri', 'id', 'deleted',
745 'uri-id', 'parent-uri-id',
746 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid',
747 'wall', 'private', 'origin', 'author-id'];
748 $condition = ['uri-id' => [$item['thr-parent-id'], $item['parent-uri-id']], 'uid' => $item['uid']];
749 $params = ['order' => ['id' => false]];
750 $parent = Post::selectFirst($fields, $condition, $params);
752 if (!DBA::isResult($parent) && Post::exists(['uri-id' => [$item['thr-parent-id'], $item['parent-uri-id']], 'uid' => 0])) {
753 $stored = Item::storeForUserByUriId($item['thr-parent-id'], $item['uid'], ['post-reason' => Item::PR_COMPLETION]);
754 if (!$stored && ($item['thr-parent-id'] != $item['parent-uri-id'])) {
755 $stored = Item::storeForUserByUriId($item['parent-uri-id'], $item['uid'], ['post-reason' => Item::PR_COMPLETION]);
758 Logger::info('Stored thread parent item for user', ['uri-id' => $item['thr-parent-id'], 'uid' => $item['uid'], 'stored' => $stored]);
759 $parent = Post::selectFirst($fields, $condition, $params);
763 if (!DBA::isResult($parent)) {
764 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)]);
768 if ($parent['uri-id'] == $parent['parent-uri-id']) {
772 $condition = ['uri-id' => $parent['parent-uri-id'],
773 'parent-uri-id' => $parent['parent-uri-id'],
774 'uid' => $parent['uid']];
775 $params = ['order' => ['id' => false]];
776 $toplevel_parent = Post::selectFirst($fields, $condition, $params);
778 if (!DBA::isResult($toplevel_parent) && $item['origin']) {
779 $stored = Item::storeForUserByUriId($item['parent-uri-id'], $item['uid'], ['post-reason' => Item::PR_COMPLETION]);
780 Logger::info('Stored parent item for user', ['uri-id' => $item['parent-uri-id'], 'uid' => $item['uid'], 'stored' => $stored]);
781 $toplevel_parent = Post::selectFirst($fields, $condition, $params);
784 if (!DBA::isResult($toplevel_parent)) {
785 Logger::notice('item top level parent was not found - ignoring item', ['parent-uri-id' => $parent['parent-uri-id'], 'uid' => $parent['uid']]);
789 return $toplevel_parent;
793 * Get the gravity for the given item array
796 * @return integer gravity
798 private static function getGravity(array $item): int
800 $activity = DI::activity();
802 if (isset($item['gravity'])) {
803 return intval($item['gravity']);
804 } elseif ($item['parent-uri-id'] === $item['uri-id']) {
805 return self::GRAVITY_PARENT;
806 } elseif ($activity->match($item['verb'], Activity::POST)) {
807 return self::GRAVITY_COMMENT;
808 } elseif ($activity->match($item['verb'], Activity::FOLLOW)) {
809 return self::GRAVITY_ACTIVITY;
810 } elseif ($activity->match($item['verb'], Activity::ANNOUNCE)) {
811 return self::GRAVITY_ACTIVITY;
814 Logger::info('Unknown gravity for verb', ['verb' => $item['verb']]);
815 return self::GRAVITY_UNKNOWN; // Should not happen
819 * Inserts item record
821 * @param array $item Item array to be inserted
822 * @param int $notify Notification (type?)
823 * @param bool $post_local (???)
824 * @return int Zero means error, otherwise primary key (id) is being returned
826 public static function insert(array $item, int $notify = 0, bool $post_local = true): int
830 $priority = Worker::PRIORITY_HIGH;
832 // If it is a posting where users should get notifications, then define it as wall posting
836 $item['network'] = Protocol::DFRN;
837 $item['protocol'] = Conversation::PARCEL_DIRECT;
838 $item['direction'] = Conversation::PUSH;
840 if (is_int($notify) && in_array($notify, Worker::PRIORITIES)) {
844 $item['network'] = trim(($item['network'] ?? '') ?: Protocol::PHANTOM);
847 $uid = intval($item['uid']);
849 $item['guid'] = self::guid($item, $notify);
850 $item['uri'] = substr(trim($item['uri'] ?? '') ?: self::newURI($item['guid']), 0, 255);
853 $item['uri-id'] = ItemURI::insert(['uri' => $item['uri'], 'guid' => $item['guid']]);
855 // Backward compatibility: parent-uri used to be the direct parent uri.
856 // If it is provided without a thr-parent, it probably is the old behavior.
857 if (empty($item['thr-parent']) || empty($item['parent-uri'])) {
858 $item['thr-parent'] = trim($item['thr-parent'] ?? $item['parent-uri'] ?? $item['uri']);
859 $item['parent-uri'] = $item['thr-parent'];
862 $item['thr-parent-id'] = ItemURI::getIdByURI($item['thr-parent']);
863 $item['parent-uri-id'] = ItemURI::getIdByURI($item['parent-uri']);
865 // Store conversation data
866 $source = $item['source'] ?? '';
867 unset($item['conversation-uri']);
868 unset($item['conversation-href']);
869 unset($item['source']);
872 * Do we already have this item?
873 * We have to check several networks since Friendica posts could be repeated
874 * via OStatus (maybe Diasporsa as well)
876 $duplicate = self::getDuplicateID($item);
881 // Additional duplicate checks
882 /// @todo Check why the first duplication check returns the item number and the second a 0
883 if (self::isDuplicate($item)) {
887 if (!isset($item['post-type'])) {
888 $item['post-type'] = empty($item['title']) ? self::PT_NOTE : self::PT_ARTICLE;
891 $item['wall'] = intval($item['wall'] ?? 0);
892 $item['extid'] = trim($item['extid'] ?? '');
893 $item['author-name'] = trim($item['author-name'] ?? '');
894 $item['author-link'] = trim($item['author-link'] ?? '');
895 $item['author-avatar'] = trim($item['author-avatar'] ?? '');
896 $item['owner-name'] = trim($item['owner-name'] ?? '');
897 $item['owner-link'] = trim($item['owner-link'] ?? '');
898 $item['owner-avatar'] = trim($item['owner-avatar'] ?? '');
899 $item['received'] = (isset($item['received']) ? DateTimeFormat::utc($item['received']) : DateTimeFormat::utcNow());
900 $item['created'] = (isset($item['created']) ? DateTimeFormat::utc($item['created']) : $item['received']);
901 $item['edited'] = (isset($item['edited']) ? DateTimeFormat::utc($item['edited']) : $item['created']);
902 $item['changed'] = (isset($item['changed']) ? DateTimeFormat::utc($item['changed']) : $item['created']);
903 $item['commented'] = (isset($item['commented']) ? DateTimeFormat::utc($item['commented']) : $item['created']);
904 $item['title'] = substr(trim($item['title'] ?? ''), 0, 255);
905 $item['location'] = trim($item['location'] ?? '');
906 $item['coord'] = trim($item['coord'] ?? '');
907 $item['visible'] = (isset($item['visible']) ? intval($item['visible']) : 1);
908 $item['deleted'] = 0;
909 $item['verb'] = trim($item['verb'] ?? '');
910 $item['object-type'] = trim($item['object-type'] ?? '');
911 $item['object'] = trim($item['object'] ?? '');
912 $item['target-type'] = trim($item['target-type'] ?? '');
913 $item['target'] = trim($item['target'] ?? '');
914 $item['plink'] = substr(trim($item['plink'] ?? ''), 0, 255);
915 $item['allow_cid'] = trim($item['allow_cid'] ?? '');
916 $item['allow_gid'] = trim($item['allow_gid'] ?? '');
917 $item['deny_cid'] = trim($item['deny_cid'] ?? '');
918 $item['deny_gid'] = trim($item['deny_gid'] ?? '');
919 $item['private'] = intval($item['private'] ?? self::PUBLIC);
920 $item['body'] = trim($item['body'] ?? '');
921 $item['raw-body'] = trim($item['raw-body'] ?? $item['body']);
922 $item['app'] = trim($item['app'] ?? '');
923 $item['origin'] = intval($item['origin'] ?? 0);
924 $item['postopts'] = trim($item['postopts'] ?? '');
925 $item['resource-id'] = trim($item['resource-id'] ?? '');
926 $item['event-id'] = intval($item['event-id'] ?? 0);
927 $item['inform'] = trim($item['inform'] ?? '');
928 $item['file'] = trim($item['file'] ?? '');
930 // Communities aren't working with the Diaspora protoccol
931 if (($uid != 0) && ($item['network'] == Protocol::DIASPORA)) {
932 $user = User::getById($uid, ['account-type']);
933 if ($user['account-type'] == Contact::TYPE_COMMUNITY) {
934 Logger::info('Community posts are not supported via Diaspora');
939 // Items cannot be stored before they happen ...
940 if ($item['created'] > DateTimeFormat::utcNow()) {
941 $item['created'] = DateTimeFormat::utcNow();
944 // We haven't invented time travel by now.
945 if ($item['edited'] > DateTimeFormat::utcNow()) {
946 $item['edited'] = DateTimeFormat::utcNow();
949 $item['plink'] = ($item['plink'] ?? '') ?: DI::baseUrl() . '/display/' . urlencode($item['guid']);
951 $item['gravity'] = self::getGravity($item);
953 $default = ['url' => $item['author-link'], 'name' => $item['author-name'],
954 'photo' => $item['author-avatar'], 'network' => $item['network']];
955 $item['author-id'] = ($item['author-id'] ?? 0) ?: Contact::getIdForURL($item['author-link'], 0, null, $default);
957 $default = ['url' => $item['owner-link'], 'name' => $item['owner-name'],
958 'photo' => $item['owner-avatar'], 'network' => $item['network']];
959 $item['owner-id'] = ($item['owner-id'] ?? 0) ?: Contact::getIdForURL($item['owner-link'], 0, null, $default);
961 $item['post-reason'] = self::getPostReason($item);
963 // Ensure that there is an avatar cache
964 Contact::checkAvatarCache($item['author-id']);
965 Contact::checkAvatarCache($item['owner-id']);
967 $item['contact-id'] = self::contactId($item);
969 if (!empty($item['direction']) && in_array($item['direction'], [Conversation::PUSH, Conversation::RELAY]) &&
970 empty($item['origin']) && self::isTooOld($item)) {
971 Logger::info('Item is too old', ['item' => $item]);
975 if (!self::isValid($item)) {
979 if ($item['gravity'] !== self::GRAVITY_PARENT) {
980 $toplevel_parent = self::getTopLevelParent($item);
981 if (empty($toplevel_parent)) {
985 // If the thread originated from this node, we check the permission against the thread starter
986 $condition = ['uri-id' => $toplevel_parent['uri-id'], 'wall' => true];
987 $localTopLevelParent = Post::selectFirst(['uid'], $condition);
988 if (!empty($localTopLevelParent['uid']) && !self::isAllowedByUser($item, $localTopLevelParent['uid'])) {
992 $parent_id = $toplevel_parent['id'];
993 $item['parent-uri'] = $toplevel_parent['uri'];
994 $item['parent-uri-id'] = $toplevel_parent['uri-id'];
995 $item['deleted'] = $toplevel_parent['deleted'];
997 // Reshares have to keep their permissions to allow forums to work
998 if (!$item['origin'] || ($item['verb'] != Activity::ANNOUNCE)) {
999 $item['allow_cid'] = $toplevel_parent['allow_cid'];
1000 $item['allow_gid'] = $toplevel_parent['allow_gid'];
1001 $item['deny_cid'] = $toplevel_parent['deny_cid'];
1002 $item['deny_gid'] = $toplevel_parent['deny_gid'];
1005 $parent_origin = $toplevel_parent['origin'];
1007 // Don't federate received participation messages
1008 if ($item['verb'] != Activity::FOLLOW) {
1009 $item['wall'] = $toplevel_parent['wall'];
1011 $item['wall'] = false;
1012 // Participations are technical messages, so they are set to "seen" automatically
1013 $item['unseen'] = false;
1017 * If the parent is private, force privacy for the entire conversation
1018 * This differs from the above settings as it subtly allows comments from
1019 * email correspondents to be private even if the overall thread is not.
1021 if ($toplevel_parent['private']) {
1022 $item['private'] = $toplevel_parent['private'];
1025 // If its a post that originated here then tag the thread as "mention"
1026 if ($item['origin'] && $item['uid']) {
1027 DBA::update('post-thread-user', ['mention' => true], ['uri-id' => $item['parent-uri-id'], 'uid' => $item['uid']]);
1028 Logger::info('tagged thread as mention', ['parent' => $parent_id, 'parent-uri-id' => $item['parent-uri-id'], 'uid' => $item['uid']]);
1031 // Update the contact relations
1032 Contact\Relation::store($toplevel_parent['author-id'], $item['author-id'], $item['created']);
1035 $parent_origin = $item['origin'];
1037 if ($item['wall'] && empty($item['conversation'])) {
1038 $item['conversation'] = $item['parent-uri'] . '#context';
1042 $item['parent-uri-id'] = ItemURI::getIdByURI($item['parent-uri']);
1043 $item['thr-parent-id'] = ItemURI::getIdByURI($item['thr-parent']);
1045 if (!empty($item['conversation']) && empty($item['conversation-id'])) {
1046 $item['conversation-id'] = ItemURI::getIdByURI($item['conversation']);
1049 // Is this item available in the global items (with uid=0)?
1050 if ($item['uid'] == 0) {
1051 $item['global'] = true;
1053 // Set the global flag on all items if this was a global item entry
1054 Post::update(['global' => true], ['uri-id' => $item['uri-id']]);
1056 $item['global'] = Post::exists(['uid' => 0, 'uri-id' => $item['uri-id']]);
1060 if (!empty($item['allow_cid'] . $item['allow_gid'] . $item['deny_cid'] . $item['deny_gid'])) {
1061 $item['private'] = self::PRIVATE;
1064 if ($notify && $post_local) {
1065 $item['edit'] = false;
1066 $item['parent'] = $parent_id;
1068 // Trigger automatic reactions for addons
1069 if (!isset($item['api_source'])) {
1070 $item['api_source'] = true;
1073 // We have to tell the hooks who we are - this really should be improved
1074 if (!DI::userSession()->getLocalUserId()) {
1075 $_SESSION['authenticated'] = true;
1076 $_SESSION['uid'] = $uid;
1077 $dummy_session = true;
1079 $dummy_session = false;
1082 Hook::callAll('post_local', $item);
1084 if ($dummy_session) {
1085 unset($_SESSION['authenticated']);
1086 unset($_SESSION['uid']);
1088 } elseif (!$notify) {
1089 Hook::callAll('post_remote', $item);
1092 if (!empty($item['cancel'])) {
1093 Logger::notice('post cancelled by addon.');
1097 if (empty($item['vid']) && !empty($item['verb'])) {
1098 $item['vid'] = Verb::getID($item['verb']);
1101 // Creates or assigns the permission set
1102 $item['psid'] = DI::permissionSet()->selectOrCreate(
1103 DI::permissionSetFactory()->createFromString(
1111 if (!empty($item['extid'])) {
1112 $item['external-id'] = ItemURI::getIdByURI($item['extid']);
1115 if ($item['verb'] == Activity::ANNOUNCE) {
1116 self::setOwnerforResharedItem($item);
1119 if (isset($item['attachments'])) {
1120 foreach ($item['attachments'] as $attachment) {
1121 $attachment['uri-id'] = $item['uri-id'];
1122 Post\Media::insert($attachment);
1124 unset($item['attachments']);
1127 if (empty($item['quote-uri-id'])) {
1128 $quote_id = self::getQuoteUriId($item['body']);
1129 if (!empty($quote_id)) {
1130 // This is one of these "should not happen" situations.
1131 // The protocol implementations should already have done this job.
1132 Logger::notice('Quote-uri-id detected in post', ['id' => $quote_id, 'guid' => $item['guid'], 'uri-id' => $item['uri-id'], 'callstack' => System::callstack(20)]);
1133 $item['quote-uri-id'] = $quote_id;
1137 if (!empty($item['quote-uri-id'])) {
1138 $item['raw-body'] = BBCode::removeSharedData($item['raw-body']);
1139 $item['body'] = BBCode::removeSharedData($item['body']);
1142 Post\Media::insertFromAttachmentData($item['uri-id'], $item['body']);
1144 // Remove all media attachments from the body and store them in the post-media table
1145 $item['raw-body'] = Post\Media::insertFromBody($item['uri-id'], $item['raw-body']);
1146 $item['raw-body'] = self::setHashtags($item['raw-body']);
1148 Post\Media::insertFromRelevantUrl($item['uri-id'], $item['raw-body']);
1150 // Check for hashtags in the body and repair or add hashtag links
1151 $item['body'] = self::setHashtags($item['body']);
1153 $item['language'] = self::getLanguage($item);
1155 $notify_type = Delivery::POST;
1157 // Filling item related side tables
1158 if (!empty($item['attach'])) {
1159 Post\Media::insertFromAttachment($item['uri-id'], $item['attach']);
1162 if (empty($item['event-id'])) {
1163 unset($item['event-id']);
1165 $ev = Event::fromBBCode($item['body']);
1166 if ((!empty($ev['desc']) || !empty($ev['summary'])) && !empty($ev['start'])) {
1167 Logger::info('Event found.');
1168 $ev['cid'] = $item['contact-id'];
1169 $ev['uid'] = $item['uid'];
1170 $ev['uri'] = $item['uri'];
1171 $ev['edited'] = $item['edited'];
1172 $ev['private'] = $item['private'];
1173 $ev['guid'] = $item['guid'];
1174 $ev['plink'] = $item['plink'];
1175 $ev['network'] = $item['network'];
1176 $ev['protocol'] = $item['protocol'] ?? Conversation::PARCEL_UNKNOWN;
1177 $ev['direction'] = $item['direction'] ?? Conversation::UNKNOWN;
1178 $ev['source'] = $item['source'] ?? '';
1180 $event = DBA::selectFirst('event', ['id'], ['uri' => $item['uri'], 'uid' => $item['uid']]);
1181 if (DBA::isResult($event)) {
1182 $ev['id'] = $event['id'];
1185 $event_id = Event::store($ev);
1186 $item = Event::getItemArrayForImportedId($event_id, $item);
1188 Logger::info('Event was stored', ['id' => $event_id]);
1192 if (empty($item['causer-id'])) {
1193 unset($item['causer-id']);
1196 if (in_array($item['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN])) {
1197 $content_warning = BBCode::getAbstract($item['body'], Protocol::ACTIVITYPUB);
1198 if (!empty($content_warning) && empty($item['content-warning'])) {
1199 $item['content-warning'] = BBCode::toPlaintext($content_warning);
1203 Post::insert($item['uri-id'], $item);
1205 if ($item['gravity'] == self::GRAVITY_PARENT) {
1206 Post\Thread::insert($item['uri-id'], $item);
1209 if (!in_array($item['verb'], self::ACTIVITIES)) {
1210 Post\Content::insert($item['uri-id'], $item);
1213 // Create Diaspora signature
1214 if ($item['origin'] && empty($item['diaspora_signed_text']) && ($item['gravity'] != self::GRAVITY_PARENT)) {
1215 $signed = Diaspora::createCommentSignature($item);
1216 if (!empty($signed)) {
1217 $item['diaspora_signed_text'] = json_encode($signed);
1221 if (!empty($item['diaspora_signed_text'])) {
1222 DBA::replace('diaspora-interaction', ['uri-id' => $item['uri-id'], 'interaction' => $item['diaspora_signed_text']]);
1225 // Attached file links
1226 if (!empty($item['file'])) {
1227 Post\Category::storeTextByURIId($item['uri-id'], $item['uid'], $item['file']);
1230 // Delivery relevant data
1231 $delivery_data = Post\DeliveryData::extractFields($item);
1233 if (!empty($item['origin']) || !empty($item['wall']) || !empty($delivery_data['postopts']) || !empty($delivery_data['inform'])) {
1234 Post\DeliveryData::insert($item['uri-id'], $delivery_data);
1237 // Store tags from the body if this hadn't been handled previously in the protocol classes
1238 if (!Tag::existsForPost($item['uri-id'])) {
1239 Tag::storeFromBody($item['uri-id'], $item['body']);
1242 $condition = ['uri-id' => $item['uri-id'], 'uid' => $item['uid']];
1243 if (Post::exists($condition)) {
1244 Logger::notice('Item is already inserted - aborting', $condition);
1248 $post_user_id = Post\User::insert($item['uri-id'], $item['uid'], $item);
1249 if (!$post_user_id) {
1250 Logger::notice('Post-User is already inserted - aborting', ['uid' => $item['uid'], 'uri-id' => $item['uri-id']]);
1254 if ($item['gravity'] == self::GRAVITY_PARENT) {
1255 $item['post-user-id'] = $post_user_id;
1256 Post\ThreadUser::insert($item['uri-id'], $item['uid'], $item);
1259 Logger::notice('created item', ['post-id' => $post_user_id, 'uid' => $item['uid'], 'network' => $item['network'], 'uri-id' => $item['uri-id'], 'guid' => $item['guid']]);
1261 $posted_item = Post::selectFirst(self::ITEM_FIELDLIST, ['post-user-id' => $post_user_id]);
1262 if (!DBA::isResult($posted_item)) {
1263 // On failure store the data into a spool file so that the "SpoolPost" worker can try again later.
1264 Logger::warning('Could not store item. it will be spooled', ['id' => $post_user_id]);
1265 self::spool($orig_item);
1269 // update the commented timestamp on the parent
1270 if (DI::config()->get('system', 'like_no_comment')) {
1271 // Update when it is a comment
1272 $update_commented = in_array($posted_item['gravity'], [self::GRAVITY_PARENT, self::GRAVITY_COMMENT]);
1274 // Update when it isn't a follow or tag verb
1275 $update_commented = !in_array($posted_item['verb'], [Activity::FOLLOW, Activity::TAG]);
1278 if ($update_commented) {
1279 $fields = ['commented' => DateTimeFormat::utcNow(), 'changed' => DateTimeFormat::utcNow()];
1281 $fields = ['changed' => DateTimeFormat::utcNow()];
1284 Post::update($fields, ['uri-id' => $posted_item['parent-uri-id'], 'uid' => $posted_item['uid']]);
1286 // In that function we check if this is a forum post. Additionally we delete the item under certain circumstances
1287 if (self::tagDeliver($posted_item['uid'], $post_user_id)) {
1288 // Get the user information for the logging
1289 $user = User::getById($uid);
1291 Logger::notice('Item had been deleted', ['id' => $post_user_id, 'user' => $uid, 'account-type' => $user['account-type']]);
1296 if (!\Friendica\Content\Feature::isEnabled($posted_item['uid'], 'explicit_mentions') && ($posted_item['gravity'] == self::GRAVITY_COMMENT)) {
1297 Tag::createImplicitMentions($posted_item['uri-id'], $posted_item['thr-parent-id']);
1299 Hook::callAll('post_local_end', $posted_item);
1301 Hook::callAll('post_remote_end', $posted_item);
1304 if ($posted_item['gravity'] === self::GRAVITY_PARENT) {
1305 self::addShadow($post_user_id);
1307 self::addShadowPost($post_user_id);
1310 self::updateContact($posted_item);
1312 Post\UserNotification::setNotification($posted_item['uri-id'], $posted_item['uid']);
1314 // Distribute items to users who subscribed to their tags
1315 self::distributeByTags($posted_item);
1317 // Automatically reshare the item if the "remote_self" option is selected
1318 self::autoReshare($posted_item);
1320 $transmit = $notify || ($posted_item['visible'] && ($parent_origin || $posted_item['origin']));
1323 // Don't relay participation messages
1324 if (($posted_item['verb'] == Activity::FOLLOW) &&
1325 (!$posted_item['origin'] || ($posted_item['author-id'] != Contact::getPublicIdByUserId($uid)))) {
1326 Logger::info('Participation messages will not be relayed', ['item' => $posted_item['id'], 'uri' => $posted_item['uri'], 'verb' => $posted_item['verb']]);
1332 if (!empty($source)) {
1333 Post\Activity::insert($item['uri-id'], $source);
1335 Worker::add(['priority' => $priority, 'dont_fork' => true], 'Notifier', $notify_type, (int)$posted_item['uri-id'], (int)$posted_item['uid']);
1338 // Fill the cache with the rendered content.
1339 if (in_array($posted_item['gravity'], [self::GRAVITY_PARENT, self::GRAVITY_COMMENT]) && ($posted_item['uid'] == 0)) {
1340 self::updateDisplayCache($posted_item['uri-id']);
1343 return $post_user_id;
1347 * Fetch the post reason for a given item array
1349 * @param array $item
1353 public static function getPostReason(array $item): int
1355 $actor = ($item['gravity'] == self::GRAVITY_PARENT) ? $item['owner-id'] : $item['author-id'];
1356 if (empty($item['origin']) && ($item['uid'] != 0) && Contact::isSharing($actor, $item['uid'])) {
1357 return self::PR_FOLLOWER;
1360 if (!empty($item['origin']) && empty($item['post-reason'])) {
1361 return self::PR_LOCAL;
1364 return $item['post-reason'] ?? self::PR_NONE;
1368 * Update the display cache
1370 * @param integer $uri_id
1373 public static function updateDisplayCache(int $uri_id)
1375 $item = Post::selectFirst(self::DISPLAY_FIELDLIST, ['uri-id' => $uri_id]);
1376 self::prepareBody($item, false, false, true);
1380 * Change the owner of a parent item if it had been shared by a forum
1382 * (public) forum posts in the new format consist of the regular post by the author
1383 * followed by an announce message sent from the forum account.
1384 * Changing the owner helps in grouping forum posts.
1386 * @param array $item
1389 private static function setOwnerforResharedItem(array $item)
1391 $parent = Post::selectFirst(['id', 'causer-id', 'owner-id', 'author-id', 'author-link', 'origin', 'post-reason'],
1392 ['uri-id' => $item['thr-parent-id'], 'uid' => $item['uid']]);
1393 if (!DBA::isResult($parent)) {
1394 Logger::error('Parent not found', ['uri-id' => $item['thr-parent-id'], 'uid' => $item['uid']]);
1398 $author = Contact::selectFirst(['url', 'contact-type', 'network'], ['id' => $item['author-id']]);
1399 if (!DBA::isResult($author)) {
1400 Logger::error('Author not found', ['id' => $item['author-id']]);
1404 $self_contact = Contact::selectFirst(['id'], ['uid' => $item['uid'], 'self' => true]);
1405 $self = !empty($self_contact) ? $self_contact['id'] : 0;
1407 $cid = Contact::getIdForURL($author['url'], $item['uid']);
1408 if (empty($cid) || (!Contact::isSharing($cid, $item['uid']) && ($cid != $self))) {
1409 Logger::info('The resharer is not a following contact: quit', ['resharer' => $author['url'], 'uid' => $item['uid'], 'cid' => $cid]);
1413 if ($author['contact-type'] != Contact::TYPE_COMMUNITY) {
1414 if ($parent['post-reason'] == self::PR_ANNOUNCEMENT) {
1415 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']]);
1419 if (Contact::isSharing($parent['owner-id'], $item['uid'])) {
1420 Logger::info('The resharer is no forum: quit', ['resharer' => $item['author-id'], 'owner' => $parent['owner-id'], 'author' => $parent['author-id'], 'uid' => $item['uid']]);
1425 self::update(['post-reason' => self::PR_ANNOUNCEMENT, 'causer-id' => $item['author-id']], ['id' => $parent['id']]);
1426 Logger::info('Set announcement post-reason', ['uri-id' => $item['uri-id'], 'thr-parent-id' => $item['thr-parent-id'], 'uid' => $item['uid']]);
1430 * Distribute the given item to users who subscribed to their tags
1432 * @param array $item Processed item
1434 private static function distributeByTags(array $item)
1436 if (($item['uid'] != 0) || ($item['gravity'] != self::GRAVITY_PARENT) || !in_array($item['network'], Protocol::FEDERATED)) {
1440 $uids = Tag::getUIDListByURIId($item['uri-id']);
1441 foreach ($uids as $uid) {
1442 $stored = self::storeForUserByUriId($item['uri-id'], $uid, ['post-reason' => self::PR_TAG]);
1443 Logger::info('Stored item for users', ['uri-id' => $item['uri-id'], 'uid' => $uid, 'stored' => $stored]);
1448 * Distributes public items to the receivers
1450 * @param integer $itemid Item ID that should be added
1451 * @param string $signed_text Original text (for Diaspora signatures), JSON encoded.
1452 * @throws \Exception
1454 public static function distribute(int $itemid, string $signed_text = '')
1456 $condition = ["`id` IN (SELECT `parent` FROM `post-user-view` WHERE `id` = ?)", $itemid];
1457 $parent = Post::selectFirst(['owner-id'], $condition);
1458 if (!DBA::isResult($parent)) {
1459 Logger::warning('Item not found', ['condition' => $condition]);
1463 // Only distribute public items from native networks
1464 $condition = ['id' => $itemid, 'uid' => 0,
1465 'network' => array_merge(Protocol::FEDERATED ,['']),
1466 'visible' => true, 'deleted' => false, 'private' => [self::PUBLIC, self::UNLISTED]];
1467 $item = Post::selectFirst(array_merge(self::ITEM_FIELDLIST, ['protocol']), $condition);
1468 if (!DBA::isResult($item)) {
1469 Logger::warning('Item not found', ['condition' => $condition]);
1473 $origin = $item['origin'];
1477 /// @todo add a field "pcid" in the contact table that referrs to the public contact id.
1478 $owner = DBA::selectFirst('contact', ['url', 'nurl', 'alias'], ['id' => $parent['owner-id']]);
1479 if (!DBA::isResult($owner)) {
1483 $condition = ['nurl' => $owner['nurl'], 'rel' => [Contact::SHARING, Contact::FRIEND]];
1484 $contacts = DBA::select('contact', ['uid'], $condition);
1485 while ($contact = DBA::fetch($contacts)) {
1486 if ($contact['uid'] == 0) {
1490 $users[$contact['uid']] = $contact['uid'];
1492 DBA::close($contacts);
1494 $condition = ['alias' => $owner['url'], 'rel' => [Contact::SHARING, Contact::FRIEND]];
1495 $contacts = DBA::select('contact', ['uid'], $condition);
1496 while ($contact = DBA::fetch($contacts)) {
1497 if ($contact['uid'] == 0) {
1501 $users[$contact['uid']] = $contact['uid'];
1503 DBA::close($contacts);
1505 if (!empty($owner['alias'])) {
1506 $condition = ['nurl' => Strings::normaliseLink($owner['alias']), 'rel' => [Contact::SHARING, Contact::FRIEND]];
1507 $contacts = DBA::select('contact', ['uid'], $condition);
1508 while ($contact = DBA::fetch($contacts)) {
1509 if ($contact['uid'] == 0) {
1513 $users[$contact['uid']] = $contact['uid'];
1515 DBA::close($contacts);
1520 if ($item['uri-id'] != $item['parent-uri-id']) {
1521 $parents = Post::select(['uid', 'origin'], ["`uri-id` = ? AND `uid` != 0", $item['parent-uri-id']]);
1522 while ($parent = Post::fetch($parents)) {
1523 $users[$parent['uid']] = $parent['uid'];
1524 if ($parent['origin'] && !$origin) {
1525 $origin_uid = $parent['uid'];
1528 DBA::close($parents);
1531 foreach ($users as $uid) {
1532 if ($origin_uid == $uid) {
1533 $item['diaspora_signed_text'] = $signed_text;
1535 $item['post-reason'] = self::PR_DISTRIBUTE;
1536 self::storeForUser($item, $uid);
1541 * Store a public item defined by their URI-ID for the given users
1543 * @param integer $uri_id URI-ID of the given item
1544 * @param integer $uid The user that will receive the item entry
1545 * @param array $fields Additional fields to be stored
1546 * @param integer $source_uid User id of the source post
1547 * @return integer stored item id
1549 public static function storeForUserByUriId(int $uri_id, int $uid, array $fields = [], int $source_uid = 0): int
1551 if ($uid == $source_uid) {
1552 Logger::warning('target UID must not be be equal to the source UID', ['uri-id' => $uri_id, 'uid' => $uid]);
1556 $item = Post::selectFirst(array_merge(self::ITEM_FIELDLIST, ['protocol']), ['uri-id' => $uri_id, 'uid' => $source_uid]);
1557 if (!DBA::isResult($item)) {
1558 Logger::warning('Item could not be fetched', ['uri-id' => $uri_id, 'uid' => $source_uid]);
1562 if (($uid != 0) && ($item['gravity'] == self::GRAVITY_PARENT)) {
1563 $owner = User::getOwnerDataById($uid);
1564 if (($owner['contact-type'] == User::ACCOUNT_TYPE_COMMUNITY) && !Tag::isMentioned($uri_id, $owner['url'])) {
1565 Logger::info('Target user is a forum but is not mentioned here, thread will not be stored', ['uid' => $uid, 'uri-id' => $uri_id]);
1570 if (($source_uid == 0) && (($item['private'] == self::PRIVATE) || !in_array($item['network'], Protocol::FEDERATED))) {
1571 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']]);
1575 $item['post-reason'] = self::PR_STORED;
1577 $item = array_merge($item, $fields);
1579 if (($uid != 0) && Contact::isSharing(($item['gravity'] == Item::GRAVITY_PARENT) ? $item['owner-id'] : $item['author-id'], $uid)) {
1580 $item['post-reason'] = self::PR_FOLLOWER;
1583 $is_reshare = ($item['gravity'] == self::GRAVITY_ACTIVITY) && ($item['verb'] == Activity::ANNOUNCE);
1585 if (($uid != 0) && (($item['gravity'] == self::GRAVITY_PARENT) || $is_reshare) &&
1586 DI::pConfig()->get($uid, 'system', 'accept_only_sharer') == self::COMPLETION_NONE &&
1587 !in_array($item['post-reason'], [self::PR_FOLLOWER, self::PR_TAG, self::PR_TO, self::PR_CC])) {
1588 Logger::info('Contact is not a follower, thread will not be stored', ['author' => $item['author-link'], 'uid' => $uid, 'uri-id' => $uri_id, 'post-reason' => $item['post-reason']]);
1592 $causer = $item['causer-id'] ?: $item['author-id'];
1594 if (($uri_id != $item['parent-uri-id']) && ($item['gravity'] == self::GRAVITY_COMMENT) && !Post::exists(['uri-id' => $item['parent-uri-id'], 'uid' => $uid])) {
1595 if (!self::fetchParent($item['parent-uri-id'], $uid, $causer)) {
1596 Logger::info('Parent post had not been added', ['uri-id' => $item['parent-uri-id'], 'uid' => $uid, 'causer' => $causer]);
1599 Logger::info('Fetched parent post', ['uri-id' => $item['parent-uri-id'], 'uid' => $uid, 'causer' => $causer]);
1600 } elseif (($uri_id != $item['thr-parent-id']) && $is_reshare && !Post::exists(['uri-id' => $item['thr-parent-id'], 'uid' => $uid])) {
1601 if (!self::fetchParent($item['thr-parent-id'], $uid, $causer)) {
1602 Logger::info('Thread parent had not been added', ['uri-id' => $item['thr-parent-id'], 'uid' => $uid, 'causer' => $causer]);
1605 Logger::info('Fetched thread parent', ['uri-id' => $item['thr-parent-id'], 'uid' => $uid, 'causer' => $causer]);
1608 $stored = self::storeForUser($item, $uid);
1609 Logger::info('Item stored for user', ['uri-id' => $item['uri-id'], 'uid' => $uid, 'causer' => $causer, 'source-uid' => $source_uid, 'stored' => $stored]);
1614 * Fetch the parent with the given uri-id
1616 * @param integer $uri_id
1617 * @param integer $uid
1618 * @param integer $causer
1622 private static function fetchParent(int $uri_id, int $uid, int $causer): int
1624 // Fetch the origin user for the post
1625 $origin_uid = self::GetOriginUidForUriId($uri_id, $uid);
1626 if (is_null($origin_uid)) {
1627 Logger::info('Origin item was not found', ['uid' => $uid, 'uri-id' => $uri_id]);
1631 return self::storeForUserByUriId($uri_id, $uid, ['causer-id' => $causer, 'post-reason' => self::PR_FETCHED], $origin_uid);
1635 * Returns the origin uid of a post if the given user is allowed to see it.
1641 private static function GetOriginUidForUriId(int $uriid, int $uid)
1643 if (Post::exists(['uri-id' => $uriid, 'uid' => $uid])) {
1647 $post = Post::selectFirst(['uid', 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid', 'private'], ['uri-id' => $uriid, 'origin' => true]);
1648 if (!empty($post)) {
1649 if (in_array($post['private'], [Item::PUBLIC, Item::UNLISTED])) {
1650 return $post['uid'];
1653 $pcid = Contact::getPublicIdByUserId($uid);
1658 foreach (Item::enumeratePermissions($post, true) as $receiver) {
1659 if ($receiver == $pcid) {
1660 return $post['uid'];
1667 if (Post::exists(['uri-id' => $uriid, 'uid' => 0])) {
1671 // When the post belongs to a a forum then all forum users are allowed to access it
1672 foreach (Tag::getByURIId($uriid, [Tag::MENTION, Tag::EXCLUSIVE_MENTION]) as $tag) {
1673 if (DBA::exists('contact', ['uid' => $uid, 'nurl' => Strings::normaliseLink($tag['url']), 'contact-type' => Contact::TYPE_COMMUNITY])) {
1674 $target_uid = User::getIdForURL($tag['url']);
1675 if (!empty($target_uid)) {
1685 * Store a public item array for the given users
1687 * @param array $item The item entry that will be stored
1688 * @param integer $uid The user that will receive the item entry
1689 * @return integer stored item id
1690 * @throws \Exception
1692 private static function storeForUser(array $item, int $uid): int
1694 $post = Post::selectFirst(['id'], ['uri-id' => $item['uri-id'], 'uid' => $uid]);
1695 if (!empty($post['id'])) {
1696 if (!empty($item['event-id'])) {
1697 $event_post = Post::selectFirst(['event-id'], ['uri-id' => $item['uri-id'], 'uid' => $uid]);
1698 if (!empty($event_post['event-id'])) {
1699 $event = DBA::selectFirst('event', ['edited', 'start', 'finish', 'summary', 'desc', 'location', 'nofinish', 'adjust'], ['id' => $item['event-id']]);
1700 if (!empty($event)) {
1701 // We aren't using "Event::store" here, since we don't want to trigger any further action
1702 $ret = DBA::update('event', $event, ['id' => $event_post['event-id']]);
1703 Logger::info('Event updated', ['uid' => $uid, 'source-event' => $item['event-id'], 'target-event' => $event_post['event-id'], 'ret' => $ret]);
1707 Logger::info('Item already exists', ['uri-id' => $item['uri-id'], 'uid' => $uid, 'id' => $post['id']]);
1711 // Data from the "post-user" table
1713 unset($item['mention']);
1714 unset($item['starred']);
1715 unset($item['unseen']);
1716 unset($item['psid']);
1717 unset($item['pinned']);
1718 unset($item['ignored']);
1719 unset($item['pubmail']);
1720 unset($item['event-id']);
1721 unset($item['hidden']);
1722 unset($item['notification-type']);
1724 // Data from the "post-delivery-data" table
1725 unset($item['postopts']);
1726 unset($item['inform']);
1728 $item['uid'] = $uid;
1729 $item['origin'] = 0;
1732 $item['contact-id'] = self::contactId($item);
1735 if ($item['gravity'] == self::GRAVITY_PARENT) {
1736 $contact = DBA::selectFirst('contact', [], ['id' => $item['contact-id'], 'self' => false]);
1737 if (DBA::isResult($contact)) {
1738 $notify = self::isRemoteSelf($contact, $item);
1742 $distributed = self::insert($item, $notify);
1744 if (!$distributed) {
1745 Logger::info("Distributed item wasn't stored", ['uri-id' => $item['uri-id'], 'user' => $uid]);
1747 Logger::info('Distributed item was stored', ['uri-id' => $item['uri-id'], 'user' => $uid, 'stored' => $distributed]);
1749 return $distributed;
1753 * Add a shadow entry for a given item id that is a thread starter
1755 * We store every public item entry additionally with the user id "0".
1756 * This is used for the community page and for the search.
1757 * It is planned that in the future we will store public item entries only once.
1759 * @param integer $itemid Item ID that should be added
1760 * @throws \Exception
1762 private static function addShadow(int $itemid)
1764 $fields = ['uid', 'private', 'visible', 'deleted', 'network', 'uri-id'];
1765 $condition = ['id' => $itemid, 'gravity' => self::GRAVITY_PARENT];
1766 $item = Post::selectFirst($fields, $condition);
1768 if (!DBA::isResult($item)) {
1772 // is it already a copy?
1773 if (($itemid == 0) || ($item['uid'] == 0)) {
1777 // Is it a visible public post?
1778 if (!$item["visible"] || $item["deleted"] || ($item["private"] == self::PRIVATE)) {
1782 // is it an entry from a connector? Only add an entry for natively connected networks
1783 if (!in_array($item["network"], array_merge(Protocol::FEDERATED ,['']))) {
1787 if (Post::exists(['uri-id' => $item['uri-id'], 'uid' => 0])) {
1791 $item = Post::selectFirst(array_merge(self::ITEM_FIELDLIST, ['protocol']), ['id' => $itemid]);
1793 if (DBA::isResult($item)) {
1794 // Preparing public shadow (removing user specific data)
1797 unset($item['parent']);
1798 unset($item['wall']);
1799 unset($item['mention']);
1800 unset($item['origin']);
1801 unset($item['starred']);
1802 unset($item['postopts']);
1803 unset($item['inform']);
1804 unset($item['post-reason']);
1805 if ($item['uri-id'] == $item['parent-uri-id']) {
1806 $item['contact-id'] = $item['owner-id'];
1808 $item['contact-id'] = $item['author-id'];
1811 $public_shadow = self::insert($item);
1813 Logger::info('Stored public shadow', ['thread' => $itemid, 'id' => $public_shadow]);
1818 * Add a shadow entry for a given item id that is a comment
1820 * This function does the same like the function above - but for comments
1822 * @param integer $itemid Item ID that should be added
1823 * @throws \Exception
1825 private static function addShadowPost(int $itemid)
1827 $item = Post::selectFirst(array_merge(self::ITEM_FIELDLIST, ['protocol']), ['id' => $itemid]);
1828 if (!DBA::isResult($item)) {
1832 // Is it a toplevel post?
1833 if ($item['gravity'] == self::GRAVITY_PARENT) {
1834 self::addShadow($itemid);
1838 // Is this a shadow entry?
1839 if ($item['uid'] == 0) {
1843 // Is there a shadow parent?
1844 if (!Post::exists(['uri-id' => $item['parent-uri-id'], 'uid' => 0])) {
1848 // Is there already a shadow entry?
1849 if (Post::exists(['uri-id' => $item['uri-id'], 'uid' => 0])) {
1853 // Save "origin" and "parent" state
1854 $origin = $item['origin'];
1855 $parent = $item['parent'];
1857 // Preparing public shadow (removing user specific data)
1860 unset($item['parent']);
1861 unset($item['wall']);
1862 unset($item['mention']);
1863 unset($item['origin']);
1864 unset($item['starred']);
1865 unset($item['postopts']);
1866 unset($item['inform']);
1867 unset($item['post-reason']);
1868 $item['contact-id'] = Contact::getIdForURL($item['author-link']);
1870 $public_shadow = self::insert($item);
1872 Logger::info('Stored public shadow', ['uri-id' => $item['uri-id'], 'id' => $public_shadow]);
1874 // If this was a comment to a Diaspora post we don't get our comment back.
1875 // This means that we have to distribute the comment by ourselves.
1876 if ($origin && Post::exists(['id' => $parent, 'network' => Protocol::DIASPORA])) {
1877 self::distribute($public_shadow);
1882 * Adds a language specification in a "language" element of given $arr.
1883 * Expects "body" element to exist in $arr.
1885 * @param array $item
1886 * @return string detected language
1887 * @throws \Text_LanguageDetect_Exception
1889 private static function getLanguage(array $item): string
1891 if (!empty($item['language'])) {
1892 return $item['language'];
1895 if (!in_array($item['gravity'], [self::GRAVITY_PARENT, self::GRAVITY_COMMENT]) || empty($item['body'])) {
1899 $languages = self::getLanguageArray(trim($item['title'] . "\n" . $item['body']), 3);
1900 if (empty($languages)) {
1904 return json_encode($languages);
1908 * Get a language array from a given text
1910 * @param string $body
1911 * @param integer $count
1914 public static function getLanguageArray(string $body, int $count): array
1916 // Convert attachments to links
1917 $naked_body = BBCode::removeAttachment($body);
1918 if (empty($naked_body)) {
1922 // Remove links and pictures
1923 $naked_body = BBCode::removeLinks($naked_body);
1925 // Convert the title and the body to plain text
1926 $naked_body = BBCode::toPlaintext($naked_body);
1928 // Remove possibly remaining links
1929 $naked_body = preg_replace(Strings::autoLinkRegEx(), '', $naked_body);
1931 if (empty($naked_body)) {
1935 $naked_body = self::getDominantLanguage($naked_body);
1937 $availableLanguages = DI::l10n()->getAvailableLanguages();
1938 // See https://github.com/friendica/friendica/issues/10511
1939 // Persian is manually added to language detection until a persian translation is provided for the interface, at
1940 // which point it will be automatically available through `getAvailableLanguages()` and this should be removed.
1941 $availableLanguages['fa'] = 'fa';
1943 $ld = new Language(array_keys($availableLanguages));
1944 return $ld->detect($naked_body)->limit(0, $count)->close() ?: [];
1948 * Check if latin or non latin are dominant in the body and only return the dominant one
1950 * @param string $body
1953 private static function getDominantLanguage(string $body): string
1957 for ($i = 0; $i < mb_strlen($body); $i++) {
1958 $character = mb_substr($body, $i, 1);
1959 $ord = mb_ord($character);
1961 // We add the most common characters to both strings.
1962 if (($ord <= 64) || ($ord >= 91 && $ord <= 96) || ($ord >= 123 && $ord <= 191) || in_array($ord, [215, 247]) || ($ord >= 697 && $ord <= 735) || ($ord > 65535)) {
1963 $latin .= $character;
1964 $non_latin .= $character;
1965 } elseif ($ord < 768) {
1966 $latin .= $character;
1968 $non_latin .= $character;
1971 return (mb_strlen($latin) > mb_strlen($non_latin)) ? $latin : $non_latin;
1974 public static function getLanguageMessage(array $item): string
1976 $iso639 = new \Matriphe\ISO639\ISO639;
1978 $used_languages = '';
1979 foreach (json_decode($item['language'], true) as $language => $reliability) {
1980 $used_languages .= $iso639->languageByCode1($language) . ' (' . $language . "): " . number_format($reliability, 5) . '\n';
1982 $used_languages = DI::l10n()->t('Detected languages in this post:\n%s', $used_languages);
1983 return $used_languages;
1987 * Creates an unique guid out of a given uri.
1988 * This function is used for messages outside the fediverse (Connector posts, feeds, Mails, ...)
1989 * Posts that are created on this system are using System::createUUID.
1990 * Received ActivityPub posts are using Processor::getGUIDByURL.
1992 * @param string $uri uri of an item entry
1993 * @param string|null $host hostname for the GUID prefix
1994 * @return string Unique guid
1996 public static function guidFromUri(string $uri, string $host = null): string
1998 // Our regular guid routine is using this kind of prefix as well
1999 // We have to avoid that different routines could accidentally create the same value
2000 $parsed = parse_url($uri);
2002 // Remove the scheme to make sure that "https" and "http" doesn't make a difference
2003 unset($parsed['scheme']);
2005 // Glue it together to be able to make a hash from it
2006 $host_id = implode('/', $parsed);
2008 // Use a mixture of several hashes to provide some GUID like experience
2009 return hash('crc32', $host) . '-'. hash('joaat', $host_id) . '-'. hash('fnv164', $host_id);
2013 * generate an unique URI
2015 * @param string $guid An existing GUID (Otherwise it will be generated)
2018 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2020 public static function newURI(string $guid = ''): string
2023 $guid = System::createUUID();
2026 return DI::baseUrl()->get() . '/objects/' . $guid;
2030 * Set "success_update" and "last-item" to the date of the last time we heard from this contact
2032 * This can be used to filter for inactive contacts.
2033 * Only do this for public postings to avoid privacy problems, since poco data is public.
2034 * Don't set this value if it isn't from the owner (could be an author that we don't know)
2036 * @param array $arr Contains the just posted item record
2037 * @throws \Exception
2039 private static function updateContact(array $arr)
2041 // Unarchive the author
2042 $contact = DBA::selectFirst('contact', [], ['id' => $arr["author-id"]]);
2043 if (DBA::isResult($contact)) {
2044 Contact::unmarkForArchival($contact);
2047 // Unarchive the contact if it's not our own contact
2048 $contact = DBA::selectFirst('contact', [], ['id' => $arr["contact-id"], 'self' => false]);
2049 if (DBA::isResult($contact)) {
2050 Contact::unmarkForArchival($contact);
2053 /// @todo On private posts we could obfuscate the date
2054 $update = ($arr['private'] != self::PRIVATE) || in_array($arr['network'], Protocol::FEDERATED);
2056 // Is it a forum? Then we don't care about the rules from above
2057 if (!$update && in_array($arr["network"], [Protocol::ACTIVITYPUB, Protocol::DFRN]) && ($arr["parent-uri-id"] === $arr["uri-id"])) {
2058 if (DBA::exists('contact', ['id' => $arr['contact-id'], 'forum' => true])) {
2064 // The "self" contact id is used (for example in the connectors) when the contact is unknown
2065 // So we have to ensure to only update the last item when it had been our own post,
2066 // or it had been done by a "regular" contact.
2067 if (!empty($arr['wall'])) {
2068 $condition = ['id' => $arr['contact-id']];
2070 $condition = ['id' => $arr['contact-id'], 'self' => false];
2072 Contact::update(['failed' => false, 'local-data' => true, 'success_update' => $arr['received'], 'last-item' => $arr['received']], $condition);
2074 // Now do the same for the system wide contacts with uid=0
2075 if ($arr['private'] != self::PRIVATE) {
2076 Contact::update(['failed' => false, 'local-data' => true, 'success_update' => $arr['received'], 'last-item' => $arr['received']],
2077 ['id' => $arr['owner-id']]);
2079 if ($arr['owner-id'] != $arr['author-id']) {
2080 Contact::update(['failed' => false, 'local-data' => true, 'success_update' => $arr['received'], 'last-item' => $arr['received']],
2081 ['id' => $arr['author-id']]);
2086 public static function setHashtags(string $body): string
2088 $body = BBCode::performWithEscapedTags($body, ['noparse', 'pre', 'code', 'img'], function ($body) {
2089 $tags = BBCode::getTags($body);
2092 if (!count($tags)) {
2096 // This sorting is important when there are hashtags that are part of other hashtags
2097 // Otherwise there could be problems with hashtags like #test and #test2
2098 // Because of this we are sorting from the longest to the shortest tag.
2099 usort($tags, function ($a, $b) {
2100 return strlen($b) <=> strlen($a);
2103 $URLSearchString = "^\[\]";
2105 // All hashtags should point to the home server if "local_tags" is activated
2106 if (DI::config()->get('system', 'local_tags')) {
2107 $body = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
2108 "#[url=" . DI::baseUrl() . "/search?tag=$2]$2[/url]", $body);
2111 // mask hashtags inside of url, bookmarks and attachments to avoid urls in urls
2112 $body = preg_replace_callback("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
2114 return ("[url=" . str_replace("#", "#", $match[1]) . "]" . str_replace("#", "#", $match[2]) . "[/url]");
2117 $body = preg_replace_callback("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism",
2119 return ("[bookmark=" . str_replace("#", "#", $match[1]) . "]" . str_replace("#", "#", $match[2]) . "[/bookmark]");
2122 $body = preg_replace_callback("/\[attachment (.*?)\](.*?)\[\/attachment\]/ism",
2124 return ("[attachment " . str_replace("#", "#", $match[1]) . "]" . $match[2] . "[/attachment]");
2127 // Repair recursive urls
2128 $body = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
2131 foreach ($tags as $tag) {
2132 if ((strpos($tag, '#') !== 0) || strpos($tag, '[url=') || strlen($tag) < 2 || $tag[1] == '#') {
2136 $basetag = str_replace('_', ' ', substr($tag, 1));
2137 $newtag = '#[url=' . DI::baseUrl() . '/search?tag=' . $basetag . ']' . $basetag . '[/url]';
2139 $body = str_replace($tag, $newtag, $body);
2142 // Convert back the masked hashtags
2143 $body = str_replace("#", "#", $body);
2152 * look for mention tags and setup a second delivery chain for forum/community posts if appropriate
2155 * @param int $item_id
2156 * @return boolean true if item was deleted, else false
2157 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2158 * @throws \ImagickException
2160 private static function tagDeliver(int $uid, int $item_id): bool
2164 $owner = User::getOwnerDataById($uid);
2165 if (!DBA::isResult($owner)) {
2166 Logger::warning('User not found, quitting here.', ['uid' => $uid]);
2170 if ($owner['contact-type'] != User::ACCOUNT_TYPE_COMMUNITY) {
2171 Logger::debug('Owner is no community, quitting here.', ['uid' => $uid, 'id' => $item_id]);
2175 $item = Post::selectFirst(self::ITEM_FIELDLIST, ['id' => $item_id, 'gravity' => [self::GRAVITY_PARENT, self::GRAVITY_COMMENT], 'origin' => false]);
2176 if (!DBA::isResult($item)) {
2177 Logger::debug('Post is an activity or origin or not found at all, quitting here.', ['id' => $item_id]);
2181 if ($item['gravity'] == self::GRAVITY_PARENT) {
2182 if (Tag::isMentioned($item['uri-id'], $owner['url'])) {
2183 Logger::info('Mention found in tag.', ['uri' => $item['uri'], 'uid' => $uid, 'id' => $item_id, 'uri-id' => $item['uri-id'], 'guid' => $item['guid']]);
2185 Logger::info('Top-level post without mention is deleted.', ['uri' => $item['uri'], $uid, 'id' => $item_id, 'uri-id' => $item['uri-id'], 'guid' => $item['guid']]);
2186 Post\User::delete(['uri-id' => $item['uri-id'], 'uid' => $item['uid']]);
2190 $arr = ['item' => $item, 'user' => $owner];
2192 Hook::callAll('tagged', $arr);
2194 if (Tag::isMentioned($item['parent-uri-id'], $owner['url'])) {
2195 Logger::info('Mention found in parent tag.', ['uri' => $item['uri'], 'uid' => $uid, 'id' => $item_id, 'uri-id' => $item['uri-id'], 'guid' => $item['guid']]);
2197 Logger::debug('No mentions found in parent, quitting here.', ['id' => $item_id, 'uri-id' => $item['uri-id'], 'guid' => $item['guid']]);
2202 Logger::info('Community post will be distributed', ['uri' => $item['uri'], 'uid' => $uid, 'id' => $item_id, 'uri-id' => $item['uri-id'], 'guid' => $item['guid']]);
2204 if ($owner['page-flags'] == User::PAGE_FLAGS_PRVGROUP) {
2206 $allow_gid = '<' . Group::FOLLOWERS . '>';
2209 self::performActivity($item['id'], 'announce', $uid, $allow_cid, $allow_gid, $deny_cid, $deny_gid);
2211 self::performActivity($item['id'], 'announce', $uid);
2214 Logger::info('Community post had been distributed', ['uri' => $item['uri'], 'uid' => $uid, 'id' => $item_id, 'uri-id' => $item['uri-id'], 'guid' => $item['guid']]);
2219 * Automatically reshare the item if the "remote_self" option is selected
2221 * @param array $item
2224 private static function autoReshare(array $item)
2226 if ($item['gravity'] != self::GRAVITY_PARENT) {
2230 if (!DBA::exists('contact', ['id' => $item['contact-id'], 'remote_self' => Contact::MIRROR_NATIVE_RESHARE])) {
2234 if (!in_array($item['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN])) {
2238 Logger::info('Automatically reshare item', ['uid' => $item['uid'], 'id' => $item['id'], 'guid' => $item['guid'], 'uri-id' => $item['uri-id']]);
2240 self::performActivity($item['id'], 'announce', $item['uid']);
2243 public static function isRemoteSelf(array $contact, array &$datarray): bool
2245 if (!$contact['remote_self']) {
2249 // Prevent the forwarding of posts that are forwarded
2250 if (!empty($datarray["extid"]) && ($datarray["extid"] == Protocol::DFRN)) {
2251 Logger::info('Already forwarded');
2255 // Prevent to forward already forwarded posts
2256 if ($datarray["app"] == DI::baseUrl()->getHostname()) {
2257 Logger::info('Already forwarded (second test)');
2261 // Only forward posts
2262 if ($datarray["verb"] != Activity::POST) {
2263 Logger::info('No post');
2267 if (($contact['network'] != Protocol::FEED) && ($datarray['private'] == self::PRIVATE)) {
2268 Logger::info('Not public');
2272 $datarray2 = $datarray;
2273 Logger::info('remote-self start', ['contact' => $contact['url'], 'remote_self'=> $contact['remote_self'], 'item' => $datarray]);
2274 if ($contact['remote_self'] == Contact::MIRROR_OWN_POST) {
2275 $self = DBA::selectFirst('contact', ['id', 'name', 'url', 'thumb'],
2276 ['uid' => $contact['uid'], 'self' => true]);
2277 if (DBA::isResult($self)) {
2278 $datarray['contact-id'] = $self["id"];
2280 $datarray['owner-name'] = $self["name"];
2281 $datarray['owner-link'] = $self["url"];
2282 $datarray['owner-avatar'] = $self["thumb"];
2284 $datarray['author-name'] = $datarray['owner-name'];
2285 $datarray['author-link'] = $datarray['owner-link'];
2286 $datarray['author-avatar'] = $datarray['owner-avatar'];
2288 unset($datarray['edited']);
2290 unset($datarray['network']);
2291 unset($datarray['owner-id']);
2292 unset($datarray['author-id']);
2295 if ($contact['network'] != Protocol::FEED) {
2296 $old_uri_id = $datarray["uri-id"] ?? 0;
2297 $datarray["guid"] = System::createUUID();
2298 unset($datarray["plink"]);
2299 $datarray["uri"] = self::newURI($datarray["guid"]);
2300 $datarray["uri-id"] = ItemURI::getIdByURI($datarray["uri"]);
2301 $datarray["extid"] = Protocol::DFRN;
2302 $urlpart = parse_url($datarray2['author-link']);
2303 $datarray["app"] = $urlpart["host"];
2304 if (!empty($old_uri_id)) {
2305 Post\Media::copy($old_uri_id, $datarray["uri-id"]);
2308 unset($datarray["parent-uri"]);
2309 unset($datarray["thr-parent"]);
2311 $datarray['private'] = self::PUBLIC;
2315 if ($contact['network'] != Protocol::FEED) {
2316 // Store the original post
2317 $result = self::insert($datarray2);
2318 Logger::info('remote-self post original item', ['contact' => $contact['url'], 'result'=> $result, 'item' => $datarray2]);
2320 $datarray["app"] = "Feed";
2324 return (bool)$result;
2331 * @param array $item
2334 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2335 * @throws \ImagickException
2337 public static function fixPrivatePhotos(string $s, int $uid, array $item = null, int $cid = 0): string
2339 if (DI::config()->get('system', 'disable_embedded')) {
2343 Logger::info('check for photos');
2344 $site = substr(DI::baseUrl(), strpos(DI::baseUrl(), '://'));
2349 $img_start = strpos($orig_body, '[img');
2350 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
2351 $img_len = ($img_start !== false ? strpos(substr($orig_body, $img_start + $img_st_close + 1), '[/img]') : false);
2353 while (($img_st_close !== false) && ($img_len !== false)) {
2354 $img_st_close++; // make it point to AFTER the closing bracket
2355 $image = substr($orig_body, $img_start + $img_st_close, $img_len);
2357 Logger::info('found photo', ['image' => $image]);
2359 if (stristr($image, $site . '/photo/')) {
2360 // Only embed locally hosted photos
2362 $i = basename($image);
2363 $i = str_replace(['.jpg', '.png', '.gif'], ['', '', ''], $i);
2364 $x = strpos($i, '-');
2367 $res = substr($i, $x + 1);
2368 $i = substr($i, 0, $x);
2369 $photo = Photo::getPhotoForUser($uid, $i, $res);
2370 if (DBA::isResult($photo)) {
2372 * Check to see if we should replace this photo link with an embedded image
2373 * 1. No need to do so if the photo is public
2374 * 2. If there's a contact-id provided, see if they're in the access list
2375 * for the photo. If so, embed it.
2376 * 3. Otherwise, if we have an item, see if the item permissions match the photo
2377 * permissions, regardless of order but first check to see if they're an exact
2378 * match to save some processing overhead.
2380 if (self::hasPermissions($photo)) {
2382 $recips = self::enumeratePermissions($photo);
2383 if (in_array($cid, $recips)) {
2387 if (self::samePermissions($uid, $item, $photo)) {
2393 $photo_img = Photo::getImageForPhoto($photo);
2394 // If a custom width and height were specified, apply before embedding
2395 if (preg_match("/\[img\=([0-9]*)x([0-9]*)\]/is", substr($orig_body, $img_start, $img_st_close), $match)) {
2396 Logger::info('scaling photo');
2398 $width = intval($match[1]);
2399 $height = intval($match[2]);
2401 $photo_img->scaleDown(max($width, $height));
2404 $data = $photo_img->asString();
2405 $type = $photo_img->getType();
2407 Logger::info('replacing photo');
2408 $image = 'data:' . $type . ';base64,' . base64_encode($data);
2409 Logger::debug('replaced', ['image' => $image]);
2415 $new_body = $new_body . substr($orig_body, 0, $img_start + $img_st_close) . $image . '[/img]';
2416 $orig_body = substr($orig_body, $img_start + $img_st_close + $img_len + strlen('[/img]'));
2417 if ($orig_body === false) {
2421 $img_start = strpos($orig_body, '[img');
2422 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
2423 $img_len = ($img_start !== false ? strpos(substr($orig_body, $img_start + $img_st_close + 1), '[/img]') : false);
2426 $new_body = $new_body . $orig_body;
2431 private static function hasPermissions(array $obj)
2433 return !empty($obj['allow_cid']) || !empty($obj['allow_gid']) ||
2434 !empty($obj['deny_cid']) || !empty($obj['deny_gid']);
2437 // @TODO $uid is unused parameter
2438 private static function samePermissions($uid, array $obj1, array $obj2): bool
2440 // first part is easy. Check that these are exactly the same.
2441 if (($obj1['allow_cid'] == $obj2['allow_cid'])
2442 && ($obj1['allow_gid'] == $obj2['allow_gid'])
2443 && ($obj1['deny_cid'] == $obj2['deny_cid'])
2444 && ($obj1['deny_gid'] == $obj2['deny_gid'])) {
2448 // This is harder. Parse all the permissions and compare the resulting set.
2449 $recipients1 = self::enumeratePermissions($obj1);
2450 $recipients2 = self::enumeratePermissions($obj2);
2454 /// @TODO Comparison of arrays, maybe use array_diff_assoc() here?
2455 return ($recipients1 == $recipients2);
2459 * Returns an array of contact-ids that are allowed to see this object
2461 * @param array $obj Item array with at least uid, allow_cid, allow_gid, deny_cid and deny_gid
2462 * @param bool $check_dead Prunes unavailable contacts from the result
2464 * @throws \Exception
2466 public static function enumeratePermissions(array $obj, bool $check_dead = false): array
2468 $aclFormater = DI::aclFormatter();
2470 $allow_people = $aclFormater->expand($obj['allow_cid']);
2471 $allow_groups = Group::expand($obj['uid'], $aclFormater->expand($obj['allow_gid']), $check_dead);
2472 $deny_people = $aclFormater->expand($obj['deny_cid']);
2473 $deny_groups = Group::expand($obj['uid'], $aclFormater->expand($obj['deny_gid']), $check_dead);
2474 $recipients = array_unique(array_merge($allow_people, $allow_groups));
2475 $deny = array_unique(array_merge($deny_people, $deny_groups));
2476 $recipients = array_diff($recipients, $deny);
2480 public static function expire(int $uid, int $days, string $network = "", bool $force = false)
2482 if (!$uid || ($days < 1)) {
2486 $condition = ["`uid` = ? AND NOT `deleted` AND `gravity` = ?",
2487 $uid, self::GRAVITY_PARENT];
2490 * $expire_network_only = save your own wall posts
2491 * and just expire conversations started by others
2493 $expire_network_only = DI::pConfig()->get($uid, 'expire', 'network_only', false);
2495 if ($expire_network_only) {
2496 $condition[0] .= " AND NOT `wall`";
2499 if ($network != "") {
2500 $condition[0] .= " AND `network` = ?";
2501 $condition[] = $network;
2504 $condition[0] .= " AND `received` < ?";
2505 $condition[] = DateTimeFormat::utc('now - ' . $days . ' day');
2507 $items = Post::select(['resource-id', 'starred', 'id', 'post-type', 'uid', 'uri-id'], $condition);
2509 if (!DBA::isResult($items)) {
2513 $expire_items = (bool)DI::pConfig()->get($uid, 'expire', 'items', true);
2515 // Forcing expiring of items - but not notes and marked items
2517 $expire_items = true;
2520 $expire_notes = (bool)DI::pConfig()->get($uid, 'expire', 'notes', true);
2521 $expire_starred = (bool)DI::pConfig()->get($uid, 'expire', 'starred', true);
2522 $expire_photos = (bool)DI::pConfig()->get($uid, 'expire', 'photos', false);
2526 $priority = DI::config()->get('system', 'expire-notify-priority');
2528 while ($item = Post::fetch($items)) {
2529 // don't expire filed items
2530 if (DBA::exists('post-category', ['uri-id' => $item['uri-id'], 'uid' => $item['uid'], 'type' => Post\Category::FILE])) {
2534 // Only expire posts, not photos and photo comments
2536 if (!$expire_photos && !empty($item['resource-id'])) {
2538 } elseif (!$expire_starred && intval($item['starred'])) {
2540 } elseif (!$expire_notes && ($item['post-type'] == self::PT_PERSONAL_NOTE)) {
2542 } elseif (!$expire_items && ($item['post-type'] != self::PT_PERSONAL_NOTE)) {
2546 self::markForDeletionById($item['id'], $priority);
2551 Logger::notice('Expired', ['user' => $uid, 'days' => $days, 'network' => $network, 'force' => $force, 'expired' => $expired, 'expire items' => $expire_items, 'expire notes' => $expire_notes, 'expire starred' => $expire_starred, 'expire photos' => $expire_photos, 'condition' => $condition]);
2554 public static function firstPostDate(int $uid, bool $wall = false)
2556 $user = User::getById($uid, ['register_date']);
2561 $condition = ["`uid` = ? AND `wall` = ? AND NOT `deleted` AND `visible` AND `received` >= ?",
2562 $uid, $wall, $user['register_date']];
2563 $params = ['order' => ['received' => false]];
2564 $thread = Post::selectFirstThread(['received'], $condition, $params);
2565 if (DBA::isResult($thread)) {
2566 $postdate = substr(DateTimeFormat::local($thread['received']), 0, 10);
2573 * add/remove activity to an item
2575 * Toggle activities as like,dislike,attend of an item
2577 * @param int $item_id
2578 * @param string $verb
2579 * Activity verb. One of
2580 * like, unlike, dislike, undislike, attendyes, unattendyes,
2581 * attendno, unattendno, attendmaybe, unattendmaybe,
2582 * announce, unannouce
2584 * @param string $allow_cid
2585 * @param string $allow_gid
2586 * @param string $deny_cid
2587 * @param string $deny_gid
2589 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2590 * @throws \ImagickException
2591 * @hook 'post_local_end'
2593 * 'post_id' => ID of posted item
2595 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
2601 Logger::notice('Start create activity', ['verb' => $verb, 'item' => $item_id, 'user' => $uid]);
2603 $item = Post::selectFirst(self::ITEM_FIELDLIST, ['id' => $item_id]);
2604 if (!DBA::isResult($item)) {
2605 Logger::warning('Post had not been fetched', ['id' => $item_id]);
2609 $uri_id = $item['uri-id'];
2611 if (!in_array($item['uid'], [0, $uid])) {
2615 if (!Post::exists(['uri-id' => $item['parent-uri-id'], 'uid' => $uid])) {
2616 $stored = self::storeForUserByUriId($item['parent-uri-id'], $uid, ['post-reason' => Item::PR_ACTIVITY]);
2617 if (($item['parent-uri-id'] == $item['uri-id']) && !empty($stored)) {
2618 $item = Post::selectFirst(self::ITEM_FIELDLIST, ['id' => $stored]);
2619 if (!DBA::isResult($item)) {
2620 Logger::info('Could not fetch just created item - should not happen', ['stored' => $stored, 'uid' => $uid, 'uri-id' => $uri_id]);
2626 // Retrieves the local post owner
2627 $owner = User::getOwnerDataById($uid);
2628 if (empty($owner)) {
2629 Logger::info('Empty owner for user', ['uid' => $uid]);
2633 // Retrieve the current logged in user's public contact
2634 $author_id = Contact::getPublicIdByUserId($uid);
2635 if (empty($author_id)) {
2636 Logger::info('Empty public contact');
2644 $activity = Activity::LIKE;
2648 $activity = Activity::DISLIKE;
2652 $activity = Activity::ATTEND;
2656 $activity = Activity::ATTENDNO;
2659 case 'unattendmaybe':
2660 $activity = Activity::ATTENDMAYBE;
2664 $activity = Activity::FOLLOW;
2668 $activity = Activity::ANNOUNCE;
2671 Logger::warning('unknown verb', ['verb' => $verb, 'item' => $item_id]);
2675 $mode = Strings::startsWith($verb, 'un') ? 'delete' : 'create';
2677 // Enable activity toggling instead of on/off
2678 $event_verb_flag = $activity === Activity::ATTEND || $activity === Activity::ATTENDNO || $activity === Activity::ATTENDMAYBE;
2680 // Look for an existing verb row
2681 // Event participation activities are mutually exclusive, only one of them can exist at all times.
2682 if ($event_verb_flag) {
2683 $verbs = [Activity::ATTEND, Activity::ATTENDNO, Activity::ATTENDMAYBE];
2685 // Translate to the index based activity index
2687 foreach ($verbs as $verb) {
2688 $vids[] = Verb::getID($verb);
2691 $vids = Verb::getID($activity);
2694 $condition = ['vid' => $vids, 'deleted' => false, 'gravity' => self::GRAVITY_ACTIVITY,
2695 'author-id' => $author_id, 'uid' => $item['uid'], 'thr-parent-id' => $uri_id];
2696 $like_item = Post::selectFirst(['id', 'guid', 'verb'], $condition);
2698 if (DBA::isResult($like_item)) {
2700 * Truth table for existing activities
2702 * | Inputs || Outputs |
2703 * |----------------------------||-------------------|
2704 * | Mode | Event | Same verb || Delete? | Return? |
2705 * |--------|-------|-----------||---------|---------|
2706 * | create | Yes | Yes || No | Yes |
2707 * | create | Yes | No || Yes | No |
2708 * | create | No | Yes || No | Yes |
2709 * | create | No | No || N/A†|
2710 * | delete | Yes | Yes || Yes | N/A‡ |
2711 * | delete | Yes | No || No | N/A‡ |
2712 * | delete | No | Yes || Yes | N/A‡ |
2713 * | delete | No | No || N/A†|
2714 * |--------|-------|-----------||---------|---------|
2715 * | A | B | C || A xor C | !B or C |
2717 * †Can't happen: It's impossible to find an existing non-event activity without
2718 * the same verb because we are only looking for this single verb.
2720 * ‡ The "mode = delete" is returning early whether an existing activity was found or not.
2722 if ($mode == 'create' xor $like_item['verb'] == $activity) {
2723 self::markForDeletionById($like_item['id']);
2726 if (!$event_verb_flag || $like_item['verb'] == $activity) {
2731 // No need to go further if we aren't creating anything
2732 if ($mode == 'delete') {
2736 $objtype = $item['resource-id'] ? Activity\ObjectType::IMAGE : Activity\ObjectType::NOTE;
2739 'guid' => System::createUUID(),
2740 'uri' => self::newURI(),
2742 'contact-id' => $owner['id'],
2743 'wall' => $item['wall'],
2745 'network' => Protocol::DFRN,
2746 'protocol' => Conversation::PARCEL_DIRECT,
2747 'direction' => Conversation::PUSH,
2748 'gravity' => self::GRAVITY_ACTIVITY,
2749 'parent' => $item['id'],
2750 'thr-parent' => $item['uri'],
2751 'owner-id' => $author_id,
2752 'author-id' => $author_id,
2753 'body' => $activity,
2754 'verb' => $activity,
2755 'object-type' => $objtype,
2756 'allow_cid' => $allow_cid ?? $item['allow_cid'],
2757 'allow_gid' => $allow_gid ?? $item['allow_gid'],
2758 'deny_cid' => $deny_cid ?? $item['deny_cid'],
2759 'deny_gid' => $deny_gid ?? $item['deny_gid'],
2764 if (in_array($activity, [Activity::LIKE, Activity::DISLIKE])) {
2765 $signed = Diaspora::createLikeSignature($uid, $new_item);
2766 if (!empty($signed)) {
2767 $new_item['diaspora_signed_text'] = json_encode($signed);
2771 self::insert($new_item, true);
2773 // If the parent item isn't visible then set it to visible
2774 // @todo Check if this is still needed
2775 if (!$item['visible']) {
2776 self::update(['visible' => true], ['id' => $item['id']]);
2782 * Fetch the SQL condition for the given user id
2784 * @param integer $owner_id User ID for which the permissions should be fetched
2785 * @return array condition
2787 public static function getPermissionsConditionArrayByUserId(int $owner_id): array
2789 $local_user = DI::userSession()->getLocalUserId();
2790 $remote_user = DI::userSession()->getRemoteContactID($owner_id);
2792 // default permissions - anonymous user
2793 $condition = ["`private` != ?", self::PRIVATE];
2795 if ($local_user && ($local_user == $owner_id)) {
2796 // Profile owner - everything is visible
2798 } elseif ($remote_user) {
2799 // Authenticated visitor - fetch the matching permissionsets
2800 $permissionSets = DI::permissionSet()->selectByContactId($remote_user, $owner_id);
2802 $condition = ["(`private` != ? OR (`private` = ? AND `wall`
2803 AND `psid` IN (" . implode(', ', array_fill(0, count($set), '?')) . ")))",
2804 self::PRIVATE, self::PRIVATE];
2805 $condition = array_merge($condition, $permissionSets->column('id'));
2813 * Get a permission SQL string for the given user
2815 * @param int $owner_id
2816 * @param string $table
2819 public static function getPermissionsSQLByUserId(int $owner_id, string $table = ''): string
2821 $local_user = DI::userSession()->getLocalUserId();
2822 $remote_user = DI::userSession()->getRemoteContactID($owner_id);
2824 if (!empty($table)) {
2825 $table = DBA::quoteIdentifier($table) . '.';
2829 * Construct permissions
2831 * default permissions - anonymous user
2833 $sql = sprintf(" AND " . $table . "`private` != %d", self::PRIVATE);
2835 // Profile owner - everything is visible
2836 if ($local_user && ($local_user == $owner_id)) {
2838 } elseif ($remote_user) {
2840 * Authenticated visitor. Unless pre-verified,
2841 * check that the contact belongs to this $owner_id
2842 * and load the groups the visitor belongs to.
2843 * If pre-verified, the caller is expected to have already
2844 * done this and passed the groups into this function.
2846 $permissionSets = DI::permissionSet()->selectByContactId($remote_user, $owner_id);
2849 $sql_set = sprintf(" OR (" . $table . "`private` = %d AND " . $table . "`wall` AND " . $table . "`psid` IN (", self::PRIVATE) . implode(',', $permissionSets->column('id')) . "))";
2854 $sql = sprintf(" AND (" . $table . "`private` != %d", self::PRIVATE) . $sql_set . ")";
2861 * get translated item type
2863 * @param array $item
2864 * @param \Friendica\Core\L10n $l10n
2867 public static function postType(array $item, \Friendica\Core\L10n $l10n): string
2869 if (!empty($item['event-id'])) {
2870 return $l10n->t('event');
2871 } elseif (!empty($item['resource-id'])) {
2872 return $l10n->t('photo');
2873 } elseif ($item['gravity'] == self::GRAVITY_ACTIVITY) {
2874 return $l10n->t('activity');
2875 } elseif ($item['gravity'] == self::GRAVITY_COMMENT) {
2876 return $l10n->t('comment');
2879 return $l10n->t('post');
2883 * Sets the "rendered-html" field of the provided item
2885 * Body is preserved to avoid side-effects as we modify it just-in-time for spoilers and private image links
2887 * @param array $item
2889 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2890 * @todo Remove reference, simply return "rendered-html" and "rendered-hash"
2892 private static function putInCache(&$item)
2894 // Save original body to prevent addons to modify it
2895 $body = $item['body'];
2897 $rendered_hash = $item['rendered-hash'] ?? '';
2898 $rendered_html = $item['rendered-html'] ?? '';
2900 if ($rendered_hash == ''
2901 || $rendered_html == ''
2902 || $rendered_hash != hash('md5', BBCode::VERSION . '::' . $body)
2903 || DI::config()->get('system', 'ignore_cache')
2905 $item['rendered-html'] = BBCode::convertForUriId($item['uri-id'], $item['body']);
2906 $item['rendered-hash'] = hash('md5', BBCode::VERSION . '::' . $body);
2908 $hook_data = ['item' => $item, 'rendered-html' => $item['rendered-html'], 'rendered-hash' => $item['rendered-hash']];
2909 Hook::callAll('put_item_in_cache', $hook_data);
2910 $item['rendered-html'] = $hook_data['rendered-html'];
2911 $item['rendered-hash'] = $hook_data['rendered-hash'];
2914 // Update if the generated values differ from the existing ones
2915 if ((($rendered_hash != $item['rendered-hash']) || ($rendered_html != $item['rendered-html'])) && !empty($item['id'])) {
2918 'rendered-html' => $item['rendered-html'],
2919 'rendered-hash' => $item['rendered-hash']
2921 ['id' => $item['id']]
2926 $item['body'] = $body;
2930 * Given an item array, convert the body element from bbcode to html and add smilie icons.
2931 * If attach is true, also add icons for item attachments.
2933 * @param array $item Record from item table
2934 * @param boolean $attach If true, add icons for item attachments as well
2935 * @param boolean $is_preview Whether this is a preview
2936 * @param boolean $only_cache Whether only cached HTML should be updated
2937 * @return string item body html
2938 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2939 * @throws \ImagickException
2940 * @hook prepare_body_init item array before any work
2941 * @hook prepare_body_content_filter ('item'=>item array, 'filter_reasons'=>string array) before first bbcode to html
2942 * @hook prepare_body ('item'=>item array, 'html'=>body string, 'is_preview'=>boolean, 'filter_reasons'=>string array) after first bbcode to html
2943 * @hook prepare_body_final ('item'=>item array, 'html'=>body string) after attach icons and blockquote special case handling (spoiler, author)
2945 public static function prepareBody(array &$item, bool $attach = false, bool $is_preview = false, bool $only_cache = false): string
2948 Hook::callAll('prepare_body_init', $item);
2950 // In order to provide theme developers more possibilities, event items
2951 // are treated differently.
2952 if ($item['object-type'] === Activity\ObjectType::EVENT && isset($item['event-id'])) {
2953 $ev = Event::getItemHTML($item);
2957 $tags = Tag::populateFromItem($item);
2959 $item['tags'] = $tags['tags'];
2960 $item['hashtags'] = $tags['hashtags'];
2961 $item['mentions'] = $tags['mentions'];
2963 $body = $item['body'] ?? '';
2965 $fields = ['uri-id', 'uri', 'body', 'title', 'author-name', 'author-link', 'author-avatar', 'guid', 'created', 'plink', 'network', 'has-media'];
2970 $shared = DI::contentItem()->getSharedPost($item, $fields);
2971 if (!empty($shared['post'])) {
2972 $shared_item = $shared['post'];
2973 $quote_uri_id = $shared['post']['uri-id'];
2974 $shared_links[] = strtolower($shared['post']['uri']);
2975 $item['body'] = BBCode::removeSharedData($item['body']);
2976 } elseif (empty($shared_item['uri-id']) && empty($item['quote-uri-id'])) {
2977 $media = Post\Media::getByURIId($item['uri-id'], [Post\Media::ACTIVITY]);
2978 if (!empty($media)) {
2979 $shared_item = Post::selectFirst($fields, ['plink' => $media[0]['url'], 'uid' => [$item['uid'], 0]]);
2981 if (empty($shared_item['uri-id'])) {
2982 $shared_item = Post::selectFirst($fields, ['uri' => $media[0]['url'], 'uid' => [$item['uid'], 0]]);
2983 $shared_links[] = strtolower($media[0]['url']);
2986 $quote_uri_id = $shared_item['uri-id'] ?? 0;
2990 if (!empty($quote_uri_id)) {
2991 $item['body'] .= "\n" . DI::contentItem()->createSharedBlockByArray($shared_item);
2994 if (!empty($shared_item['uri-id'])) {
2995 $shared_uri_id = $shared_item['uri-id'];
2996 $shared_links[] = strtolower($shared_item['plink']);
2997 $shared_attachments = Post\Media::splitAttachments($shared_uri_id, $shared_item['guid'], [], $shared_item['has-media']);
2998 $shared_links = array_merge($shared_links, array_column($shared_attachments['visual'], 'url'));
2999 $shared_links = array_merge($shared_links, array_column($shared_attachments['link'], 'url'));
3000 $shared_links = array_merge($shared_links, array_column($shared_attachments['additional'], 'url'));
3001 $item['body'] = self::replaceVisualAttachments($shared_attachments, $item['body']);
3004 $attachments = Post\Media::splitAttachments($item['uri-id'], $item['guid'] ?? '', $shared_links, $item['has-media'] ?? false);
3005 $item['body'] = self::replaceVisualAttachments($attachments, $item['body'] ?? '');
3007 $item['body'] = preg_replace("/\s*\[attachment .*?\].*?\[\/attachment\]\s*/ism", "\n", $item['body']);
3008 self::putInCache($item);
3009 $item['body'] = $body;
3010 $s = $item["rendered-html"];
3016 // Compile eventual content filter reasons
3017 $filter_reasons = [];
3018 if (!$is_preview && DI::userSession()->getPublicContactId() != $item['author-id']) {
3019 if (!empty($item['content-warning']) && (!DI::userSession()->getLocalUserId() || !DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'system', 'disable_cw', false))) {
3020 $filter_reasons[] = DI::l10n()->t('Content warning: %s', $item['content-warning']);
3023 $item['attachments'] = $attachments;
3027 'filter_reasons' => $filter_reasons
3029 Hook::callAll('prepare_body_content_filter', $hook_data);
3030 $filter_reasons = $hook_data['filter_reasons'];
3037 'preview' => $is_preview,
3038 'filter_reasons' => $filter_reasons
3040 Hook::callAll('prepare_body', $hook_data);
3041 $s = $hook_data['html'];
3045 // Replace the blockquotes with quotes that are used in mails.
3046 $mailquote = '<blockquote type="cite" class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex;">';
3047 $s = str_replace(['<blockquote>', '<blockquote class="spoiler">', '<blockquote class="author">'], [$mailquote, $mailquote, $mailquote], $s);
3051 if (!empty($shared_attachments)) {
3052 $s = self::addVisualAttachments($shared_attachments, $item, $s, true);
3053 $s = self::addLinkAttachment($shared_uri_id ?: $item['uri-id'], $shared_attachments, $body, $s, true, []);
3054 $s = self::addNonVisualAttachments($shared_attachments, $item, $s, true);
3055 $body = BBCode::removeSharedData($body);
3058 $s = self::addVisualAttachments($attachments, $item, $s, false);
3059 $s = self::addLinkAttachment($item['uri-id'], $attachments, $body, $s, false, $shared_links);
3060 $s = self::addNonVisualAttachments($attachments, $item, $s, false);
3061 $s = self::addQuestions($item, $s);
3064 if (strpos($s, '<div class="map">') !== false && !empty($item['coord'])) {
3065 $x = Map::byCoordinates(trim($item['coord']));
3067 $s = preg_replace('/\<div class\=\"map\"\>/', '$0' . $x, $s);
3071 // Replace friendica image url size with theme preference.
3072 if (!empty($a->getThemeInfoValue('item_image_size'))) {
3073 $ps = $a->getThemeInfoValue('item_image_size');
3074 $s = preg_replace('|(<img[^>]+src="[^"]+/photo/[0-9a-f]+)-[0-9]|', "$1-" . $ps, $s);
3077 $s = HTML::applyContentFilter($s, $filter_reasons);
3079 $hook_data = ['item' => $item, 'html' => $s];
3080 Hook::callAll('prepare_body_final', $hook_data);
3082 return $hook_data['html'];
3086 * Check if the body contains a link
3088 * @param string $body
3089 * @param string $url
3093 public static function containsLink(string $body, string $url, int $type = 0): bool
3095 // Make sure that for example site parameters aren't used when testing if the link is contained in the body
3096 $urlparts = parse_url($url);
3097 if (!empty($urlparts)) {
3098 unset($urlparts['query']);
3099 unset($urlparts['fragment']);
3100 $url = (string)Uri::fromParts($urlparts);
3105 // Remove media links to only search in embedded content
3106 // @todo Check images for image link, audio for audio links, ...
3107 if (in_array($type, [Post\Media::AUDIO, Post\Media::VIDEO, Post\Media::IMAGE])) {
3108 $body = preg_replace("/\[url=[^\[\]]*\](.*)\[\/url\]/Usi", ' $1 ', $body);
3111 if (strpos($body, $url)) {
3114 foreach ([0, 1, 2] as $size) {
3115 if (preg_match('#/photo/.*-' . $size . '\.#ism', $url) &&
3116 strpos(preg_replace('#(/photo/.*)-[012]\.#ism', '$1-' . $size . '.', $body), $url)) {
3124 * Replace visual attachments in the body
3126 * @param array $attachments
3127 * @param string $body
3128 * @return string modified body
3130 private static function replaceVisualAttachments(array $attachments, string $body): string
3132 DI::profiler()->startRecording('rendering');
3134 foreach ($attachments['visual'] as $attachment) {
3135 if (!empty($attachment['preview'])) {
3136 $proxy = Post\Media::getPreviewUrlForId($attachment['id'], Proxy::SIZE_LARGE);
3137 $search = ['[img=' . $attachment['preview'] . ']', ']' . $attachment['preview'] . '[/img]'];
3138 $replace = ['[img=' . $proxy . ']', ']' . $proxy . '[/img]'];
3140 $body = str_replace($search, $replace, $body);
3141 } elseif ($attachment['filetype'] == 'image') {
3142 $proxy = Post\Media::getUrlForId($attachment['id']);
3143 $search = ['[img=' . $attachment['url'] . ']', ']' . $attachment['url'] . '[/img]'];
3144 $replace = ['[img=' . $proxy . ']', ']' . $proxy . '[/img]'];
3146 $body = str_replace($search, $replace, $body);
3149 DI::profiler()->stopRecording();
3154 * Add visual attachments to the content
3156 * @param array $attachments
3157 * @param array $item
3158 * @param string $content
3159 * @return string modified content
3161 private static function addVisualAttachments(array $attachments, array $item, string $content, bool $shared): string
3163 DI::profiler()->startRecording('rendering');
3167 // @todo In the future we should make a single for the template engine with all media in it. This allows more flexibilty.
3168 foreach ($attachments['visual'] as $attachment) {
3169 if (self::containsLink($item['body'], $attachment['preview'] ?? $attachment['url'], $attachment['type'])) {
3173 if (!empty($attachment['preview'])) {
3174 $preview_url = Post\Media::getPreviewUrlForId($attachment['id'], Proxy::SIZE_LARGE);
3179 if (($attachment['filetype'] == 'video')) {
3180 /// @todo Move the template to /content as well
3181 $media = Renderer::replaceMacros(Renderer::getMarkupTemplate('video_top.tpl'), [
3183 'id' => $attachment['id'],
3184 'src' => $attachment['url'],
3185 'name' => $attachment['name'] ?: $attachment['url'],
3186 'preview' => $preview_url,
3187 'mime' => $attachment['mimetype'],
3190 if (($item['post-type'] ?? null) == Item::PT_VIDEO) {
3193 $trailing .= $media;
3195 } elseif ($attachment['filetype'] == 'audio') {
3196 $media = Renderer::replaceMacros(Renderer::getMarkupTemplate('content/audio.tpl'), [
3198 'id' => $attachment['id'],
3199 'src' => $attachment['url'],
3200 'name' => $attachment['name'] ?: $attachment['url'],
3201 'mime' => $attachment['mimetype'],
3204 if (($item['post-type'] ?? null) == Item::PT_AUDIO) {
3207 $trailing .= $media;
3209 } elseif ($attachment['filetype'] == 'image') {
3210 $media = Renderer::replaceMacros(Renderer::getMarkupTemplate('content/image.tpl'), [
3212 'src' => Post\Media::getUrlForId($attachment['id']),
3213 'preview' => Post\Media::getPreviewUrlForId($attachment['id'], ($attachment['width'] > $attachment['height']) ? Proxy::SIZE_MEDIUM : Proxy::SIZE_LARGE),
3214 'attachment' => $attachment,
3217 // On Diaspora posts the attached pictures are leading
3218 if ($item['network'] == Protocol::DIASPORA) {
3221 $trailing .= $media;
3227 $content = str_replace(BBCode::TOP_ANCHOR, '<div class="body-attach">' . $leading . '<div class="clear"></div></div>' . BBCode::TOP_ANCHOR, $content);
3228 $content = str_replace(BBCode::BOTTOM_ANCHOR, '<div class="body-attach">' . $trailing . '<div class="clear"></div></div>' . BBCode::BOTTOM_ANCHOR, $content);
3230 if ($leading != '') {
3231 $content = '<div class="body-attach">' . $leading . '<div class="clear"></div></div>' . $content;
3234 if ($trailing != '') {
3235 $content .= '<div class="body-attach">' . $trailing . '<div class="clear"></div></div>';
3239 DI::profiler()->stopRecording();
3244 * Add link attachment to the content
3246 * @param array $attachments
3247 * @param string $body
3248 * @param string $content
3249 * @param bool $shared
3250 * @param array $ignore_links A list of URLs to ignore
3251 * @return string modified content
3253 private static function addLinkAttachment(int $uriid, array $attachments, string $body, string $content, bool $shared, array $ignore_links): string
3255 DI::profiler()->startRecording('rendering');
3256 // Don't show a preview when there is a visual attachment (audio or video)
3257 $types = array_column($attachments['visual'], 'type');
3258 $preview = !in_array(Post\Media::IMAGE, $types) && !in_array(Post\Media::VIDEO, $types);
3260 if (!empty($attachments['link'])) {
3261 foreach ($attachments['link'] as $link) {
3263 foreach ($ignore_links as $ignore_link) {
3264 if (Strings::compareLink($link['url'], $ignore_link)) {
3268 // @todo Judge between the links to use the one with most information
3269 if (!$found && (empty($attachment) || !empty($link['author-name']) ||
3270 (empty($attachment['name']) && !empty($link['name'])) ||
3271 (empty($attachment['description']) && !empty($link['description'])) ||
3272 (empty($attachment['preview']) && !empty($link['preview'])))) {
3273 $attachment = $link;
3278 if (!empty($attachment)) {
3281 'author_name' => $attachment['author-name'] ?? '',
3282 'author_url' => $attachment['author-url'] ?? '',
3283 'description' => $attachment['description'] ?? '',
3286 'provider_name' => $attachment['publisher-name'] ?? '',
3287 'provider_url' => $attachment['publisher-url'] ?? '',
3289 'title' => $attachment['name'] ?? '',
3291 'url' => $attachment['url']];
3293 if ($preview && !empty($attachment['preview'])) {
3294 if ($attachment['preview-width'] >= 500) {
3295 $data['image'] = Post\Media::getPreviewUrlForId($attachment['id'], Proxy::SIZE_MEDIUM);
3297 $data['preview'] = Post\Media::getPreviewUrlForId($attachment['id'], Proxy::SIZE_MEDIUM);
3301 if (!empty($data['description']) && !empty($content)) {
3302 similar_text($data['description'], $content, $percent);
3307 if (!empty($data['description']) && (($data['title'] == $data['description']) || ($percent > 95) || (strpos($content, $data['description']) !== false))) {
3308 $data['description'] = '';
3311 if (($data['author_name'] ?? '') == ($data['provider_name'] ?? '')) {
3312 $data['author_name'] = '';
3315 if (($data['author_url'] ?? '') == ($data['provider_url'] ?? '')) {
3316 $data['author_url'] = '';
3318 } elseif (preg_match("/.*(\[attachment.*?\].*?\[\/attachment\]).*/ism", $body, $match)) {
3319 $data = BBCode::getAttachmentData($match[1]);
3321 DI::profiler()->stopRecording();
3323 if (isset($data['url']) && !in_array(strtolower($data['url']), $ignore_links)) {
3324 if (!empty($data['description']) || !empty($data['image']) || !empty($data['preview'])) {
3325 $parts = parse_url($data['url']);
3326 if (!empty($parts['scheme']) && !empty($parts['host'])) {
3327 if (empty($data['provider_name'])) {
3328 $data['provider_name'] = $parts['host'];
3330 if (empty($data['provider_url']) || empty(parse_url($data['provider_url'], PHP_URL_SCHEME))) {
3331 $data['provider_url'] = $parts['scheme'] . '://' . $parts['host'];
3333 if (!empty($parts['port'])) {
3334 $data['provider_url'] .= ':' . $parts['port'];
3339 // @todo Use a template
3340 $rendered = BBCode::convertAttachment('', BBCode::INTERNAL, false, $data, $uriid);
3341 } elseif (!self::containsLink($content, $data['url'], Post\Media::HTML)) {
3342 $rendered = Renderer::replaceMacros(Renderer::getMarkupTemplate('content/link.tpl'), [
3343 '$url' => $data['url'],
3344 '$title' => $data['title'],
3351 return str_replace(BBCode::BOTTOM_ANCHOR, BBCode::BOTTOM_ANCHOR . $rendered, $content);
3353 return $content . $rendered;
3360 * Add non visual attachments to the content
3362 * @param array $attachments
3363 * @param array $item
3364 * @param string $content
3365 * @return string modified content
3367 private static function addNonVisualAttachments(array $attachments, array $item, string $content): string
3369 DI::profiler()->startRecording('rendering');
3371 foreach ($attachments['additional'] as $attachment) {
3372 if (strpos($item['body'], $attachment['url'])) {
3376 $author = ['uid' => 0, 'id' => $item['author-id'],
3377 'network' => $item['author-network'], 'url' => $item['author-link']];
3378 $the_url = Contact::magicLinkByContact($author, $attachment['url']);
3380 $title = Strings::escapeHtml(trim(($attachment['description'] ?? '') ?: $attachment['url']));
3382 if (!empty($attachment['size'])) {
3383 $title .= ' ' . $attachment['size'] . ' ' . DI::l10n()->t('bytes');
3386 /// @todo Use a template
3387 $icon = '<div class="attachtype icon s22 type-' . $attachment['filetype'] . ' subtype-' . $attachment['subtype'] . '"></div>';
3388 $trailing .= '<a href="' . strip_tags($the_url) . '" title="' . $title . '" class="attachlink" target="_blank" rel="noopener noreferrer" >' . $icon . '</a>';
3391 if ($trailing != '') {
3392 $content .= '<div class="body-attach">' . $trailing . '<div class="clear"></div></div>';
3395 DI::profiler()->stopRecording();
3399 private static function addQuestions(array $item, string $content): string
3401 DI::profiler()->startRecording('rendering');
3402 if (!empty($item['question-id'])) {
3404 'id' => $item['question-id'],
3405 'multiple' => $item['question-multiple'],
3406 'voters' => $item['question-voters'],
3407 'endtime' => $item['question-end-time']
3410 $options = Post\QuestionOption::getByURIId($item['uri-id']);
3411 foreach ($options as $key => $option) {
3412 if ($question['voters'] > 0) {
3413 $percent = $option['replies'] / $question['voters'] * 100;
3414 $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));
3416 $options[$key]['vote'] = DI::l10n()->tt('%2$s (%1$d vote)', '%2$s (%1$d votes)', $option['replies'], $option['name']);
3420 if (!empty($question['voters']) && !empty($question['endtime'])) {
3421 $summary = DI::l10n()->tt('%d voter. Poll end: %s', '%d voters. Poll end: %s', $question['voters'], Temporal::getRelativeDate($question['endtime']));
3422 } elseif (!empty($question['voters'])) {
3423 $summary = DI::l10n()->tt('%d voter.', '%d voters.', $question['voters']);
3424 } elseif (!empty($question['endtime'])) {
3425 $summary = DI::l10n()->t('Poll end: %s', Temporal::getRelativeDate($question['endtime']));
3430 $content .= Renderer::replaceMacros(Renderer::getMarkupTemplate('content/question.tpl'), [
3431 '$question' => $question,
3432 '$options' => $options,
3433 '$summary' => $summary,
3436 DI::profiler()->stopRecording();
3441 * get private link for item
3443 * @param array $item
3444 * @return boolean|array False if item has not plink, otherwise array('href'=>plink url, 'title'=>translated title)
3445 * @throws \Exception
3447 public static function getPlink(array $item)
3449 if (!empty($item['plink']) && Network::isValidHttpUrl($item['plink'])) {
3450 $plink = $item['plink'];
3451 } elseif (!empty($item['uri']) && Network::isValidHttpUrl($item['uri']) && !Network::isLocalLink($item['uri'])) {
3452 $plink = $item['uri'];
3455 if (DI::userSession()->getLocalUserId()) {
3457 'href' => "display/" . $item['guid'],
3458 'orig' => "display/" . $item['guid'],
3459 'title' => DI::l10n()->t('View on separate page'),
3460 'orig_title' => DI::l10n()->t('View on separate page'),
3463 if (!empty($plink) && ($item['private'] == self::PRIVATE)) {
3464 $author = ['uid' => 0, 'id' => $item['author-id'],
3465 'network' => $item['author-network'], 'url' => $item['author-link']];
3466 $plink = Contact::magicLinkByContact($author, $plink);
3469 if (!empty($plink)) {
3470 $ret['href'] = DI::baseUrl()->remove($plink);
3471 $ret['title'] = DI::l10n()->t('Link to source');
3473 } elseif (!empty($plink) && ($item['private'] != self::PRIVATE)) {
3477 'title' => DI::l10n()->t('Link to source'),
3478 'orig_title' => DI::l10n()->t('Link to source'),
3488 * Does the given uri-id belongs to a post that is sent as starting post to a forum?
3490 * @param int $uri_id
3492 * @return boolean "true" when it is a forum post
3494 public static function isForumPost(int $uri_id): bool
3496 foreach (Tag::getByURIId($uri_id, [Tag::EXCLUSIVE_MENTION]) as $tag) {
3497 if (DBA::exists('contact', ['uid' => 0, 'nurl' => Strings::normaliseLink($tag['url']), 'contact-type' => Contact::TYPE_COMMUNITY])) {
3505 * Search item id for given URI or plink
3507 * @param string $uri
3508 * @param integer $uid
3510 * @return integer item id
3512 public static function searchByLink(string $uri, int $uid = 0): int
3514 $ssl_uri = str_replace('http://', 'https://', $uri);
3515 $uris = [$uri, $ssl_uri, Strings::normaliseLink($uri)];
3517 $item = Post::selectFirst(['id'], ['uri' => $uris, 'uid' => $uid]);
3518 if (DBA::isResult($item)) {
3522 $item = Post::selectFirst(['id'], ['plink' => $uris, 'uid' => $uid]);
3523 if (DBA::isResult($item)) {
3531 * Return the URI for a link to the post
3533 * @param string $uri URI or link to post
3535 * @return string URI
3537 public static function getURIByLink(string $uri): string
3539 $ssl_uri = str_replace('http://', 'https://', $uri);
3540 $uris = [$uri, $ssl_uri, Strings::normaliseLink($uri)];
3542 $item = Post::selectFirst(['uri'], ['uri' => $uris]);
3543 if (DBA::isResult($item)) {
3544 return $item['uri'];
3547 $item = Post::selectFirst(['uri'], ['plink' => $uris]);
3548 if (DBA::isResult($item)) {
3549 return $item['uri'];
3556 * Fetches item for given URI or plink
3558 * @param string $uri
3559 * @param integer $uid
3561 * @return integer item id
3563 public static function fetchByLink(string $uri, int $uid = 0): int
3565 Logger::info('Trying to fetch link', ['uid' => $uid, 'uri' => $uri]);
3566 $item_id = self::searchByLink($uri, $uid);
3567 if (!empty($item_id)) {
3568 Logger::info('Link found', ['uid' => $uid, 'uri' => $uri, 'id' => $item_id]);
3578 Hook::callAll('item_by_link', $hookData);
3580 if (isset($hookData['item_id'])) {
3581 return is_numeric($hookData['item_id']) ? $hookData['item_id'] : 0;
3584 $fetched_uri = ActivityPub\Processor::fetchMissingActivity($uri);
3587 $item_id = self::searchByLink($fetched_uri, $uid);
3589 $item_id = Diaspora::fetchByURL($uri);
3592 if (!empty($item_id)) {
3593 Logger::info('Link fetched', ['uid' => $uid, 'uri' => $uri, 'id' => $item_id]);
3597 Logger::info('Link not found', ['uid' => $uid, 'uri' => $uri]);
3602 * Check a prospective item array against user-level permissions
3604 * @param array $item Expected keys: uri, gravity, and
3605 * author-link if is author-id is set,
3606 * owner-link if is owner-id is set,
3607 * causer-link if is causer-id is set.
3608 * @param int $user_id Local user ID
3610 * @throws \Exception
3612 protected static function isAllowedByUser(array $item, int $user_id): bool
3614 if (!empty($item['author-id']) && Contact\User::isBlocked($item['author-id'], $user_id)) {
3615 Logger::notice('Author is blocked by user', ['author-link' => $item['author-link'], 'uid' => $user_id, 'item-uri' => $item['uri']]);
3619 if (!empty($item['owner-id']) && Contact\User::isBlocked($item['owner-id'], $user_id)) {
3620 Logger::notice('Owner is blocked by user', ['owner-link' => $item['owner-link'], 'uid' => $user_id, 'item-uri' => $item['uri']]);
3624 // The causer is set during a thread completion, for example because of a reshare. It countains the responsible actor.
3625 if (!empty($item['causer-id']) && Contact\User::isBlocked($item['causer-id'], $user_id)) {
3626 Logger::notice('Causer is blocked by user', ['causer-link' => $item['causer-link'] ?? $item['causer-id'], 'uid' => $user_id, 'item-uri' => $item['uri']]);
3630 if (!empty($item['causer-id']) && ($item['gravity'] === self::GRAVITY_PARENT) && Contact\User::isIgnored($item['causer-id'], $user_id)) {
3631 Logger::notice('Causer is ignored by user', ['causer-link' => $item['causer-link'] ?? $item['causer-id'], 'uid' => $user_id, 'item-uri' => $item['uri']]);
3639 * Fetch the uri-id of a quote
3641 * @param string $body
3644 public static function getQuoteUriId(string $body, int $uid = 0): int
3646 $shared = BBCode::fetchShareAttributes($body);
3647 if (empty($shared['guid']) && empty($shared['message_id'])) {
3651 if (empty($shared['link']) && empty($shared['message_id'])) {
3652 Logger::notice('Invalid share block.', ['share' => $shared]);
3656 if (!empty($shared['guid'])) {
3657 $shared_item = Post::selectFirst(['uri-id'], ['guid' => $shared['guid'], 'uid' => [0, $uid]]);
3658 if (!empty($shared_item['uri-id'])) {
3659 Logger::debug('Found post by guid', ['guid' => $shared['guid'], 'uid' => $uid]);
3660 return $shared_item['uri-id'];
3664 if (!empty($shared['message_id'])) {
3665 $shared_item = Post::selectFirst(['uri-id'], ['uri' => $shared['message_id'], 'uid' => [0, $uid]]);
3666 if (!empty($shared_item['uri-id'])) {
3667 Logger::debug('Found post by message_id', ['message_id' => $shared['message_id'], 'uid' => $uid]);
3668 return $shared_item['uri-id'];
3672 if (!empty($shared['link'])) {
3673 $shared_item = Post::selectFirst(['uri-id'], ['plink' => $shared['link'], 'uid' => [0, $uid]]);
3674 if (!empty($shared_item['uri-id'])) {
3675 Logger::debug('Found post by link', ['link' => $shared['link'], 'uid' => $uid]);
3676 return $shared_item['uri-id'];
3680 $url = $shared['message_id'] ?: $shared['link'];
3681 $id = self::fetchByLink($url);
3683 Logger::notice('Post could not be fetched.', ['url' => $url, 'uid' => $uid]);
3687 $shared_item = Post::selectFirst(['uri-id'], ['id' => $id]);
3688 if (!empty($shared_item['uri-id'])) {
3689 Logger::debug('Fetched shared post', ['id' => $id, 'url' => $url, 'uid' => $uid]);
3690 return $shared_item['uri-id'];
3693 Logger::warning('Post does not exist although it was supposed to had been fetched.', ['id' => $id, 'url' => $url, 'uid' => $uid]);