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-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,
148 // Item weight for query ordering
149 const GRAVITY_PARENT = 0;
150 const GRAVITY_ACTIVITY = 3;
151 const GRAVITY_COMMENT = 6;
152 const GRAVITY_UNKNOWN = 9;
155 * Update existing item entries
157 * @param array $fields The fields that are to be changed
158 * @param array $condition The condition for finding the item entries
160 * In the future we may have to change permissions as well.
161 * Then we had to add the user id as third parameter.
163 * A return value of "0" doesn't mean an error - but that 0 rows had been changed.
165 * @return integer|boolean number of affected rows - or "false" if there was an error
166 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
168 public static function update(array $fields, array $condition)
170 if (empty($condition) || empty($fields)) {
174 if (isset($fields['extid'])) {
175 $fields['external-id'] = ItemURI::getIdByURI($fields['extid']);
178 if (!empty($fields['verb'])) {
179 $fields['vid'] = Verb::getID($fields['verb']);
182 if (!empty($fields['edited'])) {
183 $previous = Post::selectFirst(['edited'], $condition);
186 $rows = Post::update($fields, $condition);
187 if (is_bool($rows)) {
191 // We only need to call the line by line update for specific fields
192 if (empty($fields['body']) && empty($fields['file']) &&
193 empty($fields['attach']) && empty($fields['edited'])) {
197 Logger::info('Updating per single row method', ['fields' => $fields, 'condition' => $condition]);
199 $items = Post::select(['id', 'origin', 'uri-id', 'uid', 'author-network'], $condition);
203 while ($item = DBA::fetch($items)) {
204 if (!empty($fields['body'])) {
205 Post\Media::insertFromAttachmentData($item['uri-id'], $fields['body']);
207 $content_fields = ['raw-body' => trim($fields['raw-body'] ?? $fields['body'])];
209 // Remove all media attachments from the body and store them in the post-media table
210 // @todo On shared postings (Diaspora style and commented reshare) don't fetch content from the shared part
211 $content_fields['raw-body'] = Post\Media::insertFromBody($item['uri-id'], $content_fields['raw-body']);
212 $content_fields['raw-body'] = self::setHashtags($content_fields['raw-body']);
214 if ($item['author-network'] != Protocol::DFRN) {
215 Post\Media::insertFromRelevantUrl($item['uri-id'], $content_fields['raw-body']);
218 Post\Content::update($item['uri-id'], $content_fields);
221 if (!empty($fields['file'])) {
222 Post\Category::storeTextByURIId($item['uri-id'], $item['uid'], $fields['file']);
225 if (!empty($fields['attach'])) {
226 Post\Media::insertFromAttachment($item['uri-id'], $fields['attach']);
229 // We only need to notfiy others when it is an original entry from us.
230 // Only call the notifier when the item had been edited and records had been changed.
231 if ($item['origin'] && !empty($fields['edited']) && ($previous['edited'] != $fields['edited'])) {
232 $notify_items[] = $item['id'];
238 foreach ($notify_items as $notify_item) {
239 $post = Post::selectFirst(['uri-id', 'uid'], ['id' => $notify_item]);
240 Worker::add(Worker::PRIORITY_HIGH, 'Notifier', Delivery::POST, (int)$post['uri-id'], (int)$post['uid']);
247 * Delete an item and notify others about it - if it was ours
249 * @param array $condition The condition for finding the item entries
250 * @param integer $priority Priority for the notification
252 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
254 public static function markForDeletion(array $condition, int $priority = Worker::PRIORITY_HIGH)
256 $items = Post::select(['id'], $condition);
257 while ($item = Post::fetch($items)) {
258 self::markForDeletionById($item['id'], $priority);
264 * Delete an item for an user and notify others about it - if it was ours
266 * @param array $condition The condition for finding the item entries
267 * @param integer $uid User who wants to delete this item
269 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
271 public static function deleteForUser(array $condition, int $uid)
277 $items = Post::select(['id', 'uid', 'uri-id'], $condition);
278 while ($item = Post::fetch($items)) {
279 if (in_array($item['uid'], [$uid, 0])) {
280 Post\User::update($item['uri-id'], $uid, ['hidden' => true], true);
281 Post\ThreadUser::update($item['uri-id'], $uid, ['hidden' => true], true);
284 if ($item['uid'] == $uid) {
285 self::markForDeletionById($item['id'], Worker::PRIORITY_HIGH);
286 } elseif ($item['uid'] != 0) {
287 Logger::warning('Wrong ownership. Not deleting item', ['id' => $item['id']]);
294 * Mark an item for deletion, delete related data and notify others about it - if it was ours
296 * @param integer $item_id
297 * @param integer $priority Priority for the notification
298 * @return boolean success
299 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
301 public static function markForDeletionById(int $item_id, int $priority = Worker::PRIORITY_HIGH): bool
303 Logger::info('Mark item for deletion by id', ['id' => $item_id, 'callstack' => System::callstack()]);
304 // locate item to be deleted
305 $fields = ['id', 'uri', 'uri-id', 'uid', 'parent', 'parent-uri-id', 'origin',
306 'deleted', 'resource-id', 'event-id',
307 'verb', 'object-type', 'object', 'target', 'contact-id', 'psid', 'gravity'];
308 $item = Post::selectFirst($fields, ['id' => $item_id]);
309 if (!DBA::isResult($item)) {
310 Logger::info('Item not found.', ['id' => $item_id]);
314 if ($item['deleted']) {
315 Logger::info('Item has already been marked for deletion.', ['id' => $item_id]);
319 $parent = Post::selectFirst(['origin'], ['id' => $item['parent']]);
320 if (!DBA::isResult($parent)) {
321 $parent = ['origin' => false];
324 // clean up categories and tags so they don't end up as orphans
325 Post\Category::deleteByURIId($item['uri-id'], $item['uid']);
328 * If item is a link to a photo resource, nuke all the associated photos
329 * (visitors will not have photo resources)
330 * This only applies to photos uploaded from the photos page. Photos inserted into a post do not
331 * generate a resource-id and therefore aren't intimately linked to the item.
333 /// @TODO: this should first check if photo is used elsewhere
334 if (strlen($item['resource-id'])) {
335 Photo::delete(['resource-id' => $item['resource-id'], 'uid' => $item['uid']]);
338 // If item is a link to an event, delete the event.
339 if (intval($item['event-id'])) {
340 Event::delete($item['event-id']);
343 // If item has attachments, drop them
344 $attachments = Post\Media::getByURIId($item['uri-id'], [Post\Media::DOCUMENT]);
345 foreach($attachments as $attachment) {
346 if (preg_match('|attach/(\d+)|', $attachment['url'], $matches)) {
347 Attach::delete(['id' => $matches[1], 'uid' => $item['uid']]);
351 // Set the item to "deleted"
352 $item_fields = ['deleted' => true, 'edited' => DateTimeFormat::utcNow(), 'changed' => DateTimeFormat::utcNow()];
353 Post::update($item_fields, ['id' => $item['id']]);
355 Post\Category::storeTextByURIId($item['uri-id'], $item['uid'], '');
357 if (!Post::exists(["`uri-id` = ? AND `uid` != 0 AND NOT `deleted`", $item['uri-id']])) {
358 self::markForDeletion(['uri-id' => $item['uri-id'], 'uid' => 0, 'deleted' => false], $priority);
361 Post\DeliveryData::delete($item['uri-id']);
363 // If it's the parent of a comment thread, kill all the kids
364 if ($item['gravity'] == self::GRAVITY_PARENT) {
365 self::markForDeletion(['parent' => $item['parent'], 'deleted' => false], $priority);
368 // Is it our comment and/or our thread?
369 if (($item['origin'] || $parent['origin']) && ($item['uid'] != 0)) {
370 // When we delete the original post we will delete all existing copies on the server as well
371 self::markForDeletion(['uri-id' => $item['uri-id'], 'deleted' => false], $priority);
373 // send the notification upstream/downstream
375 Worker::add(['priority' => $priority, 'dont_fork' => true], 'Notifier', Delivery::DELETION, (int)$item['uri-id'], (int)$item['uid']);
377 } elseif ($item['uid'] != 0) {
378 Post\User::update($item['uri-id'], $item['uid'], ['hidden' => true]);
379 Post\ThreadUser::update($item['uri-id'], $item['uid'], ['hidden' => true]);
382 Logger::info('Item has been marked for deletion.', ['id' => $item_id]);
388 * Get guid from given item record
390 * @param array $item Item record
391 * @param bool Whether to notify (?)
392 * @return string Guid
394 public static function guid(array $item, bool $notify): string
396 if (!empty($item['guid'])) {
397 return trim($item['guid']);
401 // We have to avoid duplicates. So we create the GUID in form of a hash of the plink or uri.
402 // We add the hash of our own host because our host is the original creator of the post.
403 $prefix_host = DI::baseUrl()->getHostname();
407 // We are only storing the post so we create a GUID from the original hostname.
408 if (!empty($item['author-link'])) {
409 $parsed = parse_url($item['author-link']);
410 if (!empty($parsed['host'])) {
411 $prefix_host = $parsed['host'];
415 if (empty($prefix_host) && !empty($item['plink'])) {
416 $parsed = parse_url($item['plink']);
417 if (!empty($parsed['host'])) {
418 $prefix_host = $parsed['host'];
422 if (empty($prefix_host) && !empty($item['uri'])) {
423 $parsed = parse_url($item['uri']);
424 if (!empty($parsed['host'])) {
425 $prefix_host = $parsed['host'];
429 // Is it in the format data@host.tld? - Used for mail contacts
430 if (empty($prefix_host) && !empty($item['author-link']) && strstr($item['author-link'], '@')) {
431 $mailparts = explode('@', $item['author-link']);
432 $prefix_host = array_pop($mailparts);
436 if (!empty($item['plink'])) {
437 $guid = self::guidFromUri($item['plink'], $prefix_host);
438 } elseif (!empty($item['uri'])) {
439 $guid = self::guidFromUri($item['uri'], $prefix_host);
441 $guid = System::createUUID(hash('crc32', $prefix_host));
448 * Returns contact id from given item record
450 * @param array $item Item record
451 * @return int Contact id
453 private static function contactId(array $item): int
455 if ($item['uid'] == 0) {
456 return $item['author-id'];
459 if ($item['origin']) {
460 $owner = User::getOwnerDataById($item['uid']);
464 if (!empty($item['causer-id']) && Contact::isSharing($item['causer-id'], $item['uid'], true)) {
465 $cdata = Contact::getPublicAndUserContactID($item['causer-id'], $item['uid']);
466 if (!empty($cdata['user'])) {
467 return $cdata['user'];
471 if ($item['gravity'] == self::GRAVITY_PARENT) {
472 if (Contact::isSharingByURL($item['owner-link'], $item['uid'], true)) {
473 $contact_id = Contact::getIdForURL($item['owner-link'], $item['uid']);
475 $contact_id = Contact::getIdForURL($item['owner-link']);
477 if (!empty($contact_id)) {
482 if (Contact::isSharingByURL($item['author-link'], $item['uid'], true)) {
483 $contact_id = Contact::getIdForURL($item['author-link'], $item['uid']);
485 $contact_id = Contact::getIdForURL($item['author-link']);
488 if (!empty($contact_id)) {
492 Logger::warning('contact-id could not be fetched, using self contact instead.', ['uid' => $item['uid'], 'item' => $item]);
493 $self = Contact::selectFirst(['id'], ['self' => true, 'uid' => $item['uid']]);
498 * Write an item array into a spool file to be inserted later.
499 * This command is called whenever there are issues storing an item.
501 * @param array $item The item fields that are to be inserted
504 private static function spool(array $item)
506 // Now we store the data in the spool directory
507 // We use "microtime" to keep the arrival order and "mt_rand" to avoid duplicates
508 $file = 'item-' . round(microtime(true) * 10000) . '-' . mt_rand() . '.msg';
510 $spoolpath = System::getSpoolPath();
511 if ($spoolpath != '') {
512 $spool = $spoolpath . '/' . $file;
514 file_put_contents($spool, json_encode($item));
515 Logger::warning("Item wasn't stored - Item was spooled into file", ['file' => $file]);
520 * Check if the item array is a duplicate
522 * @param array $item Item record
523 * @return boolean is it a duplicate?
525 private static function isDuplicate(array $item): bool
527 // Checking if there is already an item with the same guid
528 $condition = ['guid' => $item['guid'], 'network' => $item['network'], 'uid' => $item['uid']];
529 if (Post::exists($condition)) {
530 Logger::notice('Found already existing item', $condition);
534 $condition = ['uri-id' => $item['uri-id'], 'uid' => $item['uid'],
535 'network' => [$item['network'], Protocol::DFRN]];
536 if (Post::exists($condition)) {
537 Logger::notice('duplicated item with the same uri found.', $condition);
541 // On Friendica and Diaspora the GUID is unique
542 if (in_array($item['network'], [Protocol::DFRN, Protocol::DIASPORA])) {
543 $condition = ['guid' => $item['guid'], 'uid' => $item['uid']];
544 if (Post::exists($condition)) {
545 Logger::notice('duplicated item with the same guid found.', $condition);
548 } elseif ($item['network'] == Protocol::OSTATUS) {
549 // Check for an existing post with the same content. There seems to be a problem with OStatus.
550 $condition = ["`body` = ? AND `network` = ? AND `created` = ? AND `contact-id` = ? AND `uid` = ?",
551 $item['body'], $item['network'], $item['created'], $item['contact-id'], $item['uid']];
552 if (Post::exists($condition)) {
553 Logger::notice('duplicated item with the same body found.', $item);
559 * Check for already added items.
560 * There is a timing issue here that sometimes creates double postings.
561 * An unique index would help - but the limitations of MySQL (maximum size of index values) prevent this.
563 if (($item['uid'] == 0) && Post::exists(['uri-id' => $item['uri-id'], 'uid' => 0])) {
564 Logger::notice('Global item already stored.', ['uri-id' => $item['uri-id'], 'network' => $item['network']]);
572 * Check if the item array is valid
574 * @param array $item Item record
575 * @return boolean item is valid
577 public static function isValid(array $item): bool
579 // When there is no content then we don't post it
580 if (($item['body'] . $item['title'] == '') && (empty($item['uri-id']) || !Post\Media::existsByURIId($item['uri-id']))) {
581 Logger::notice('No body, no title.');
585 if (!empty($item['uid'])) {
586 $owner = User::getOwnerDataById($item['uid'], false);
588 Logger::warning('Missing item user owner data', ['uid' => $item['uid']]);
592 if ($owner['account_expired'] || $owner['account_removed']) {
593 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']]);
598 if (!empty($item['author-id']) && Contact::isBlocked($item['author-id'])) {
599 Logger::notice('Author is blocked node-wide', ['author-link' => $item['author-link'], 'item-uri' => $item['uri']]);
603 if (!empty($item['author-link']) && Network::isUrlBlocked($item['author-link'])) {
604 Logger::notice('Author server is blocked', ['author-link' => $item['author-link'], 'item-uri' => $item['uri']]);
608 if (!empty($item['owner-id']) && Contact::isBlocked($item['owner-id'])) {
609 Logger::notice('Owner is blocked node-wide', ['owner-link' => $item['owner-link'], 'item-uri' => $item['uri']]);
613 if (!empty($item['owner-link']) && Network::isUrlBlocked($item['owner-link'])) {
614 Logger::notice('Owner server is blocked', ['owner-link' => $item['owner-link'], 'item-uri' => $item['uri']]);
618 if (!empty($item['uid']) && !self::isAllowedByUser($item, $item['uid'])) {
622 if ($item['verb'] == Activity::FOLLOW) {
623 if (!$item['origin'] && ($item['author-id'] == Contact::getPublicIdByUserId($item['uid']))) {
624 // Our own follow request can be relayed to us. We don't store it to avoid notification chaos.
625 Logger::info("Follow: Don't store not origin follow request", ['parent-uri' => $item['parent-uri']]);
629 $condition = ['verb' => Activity::FOLLOW, 'uid' => $item['uid'],
630 'parent-uri' => $item['parent-uri'], 'author-id' => $item['author-id']];
631 if (Post::exists($condition)) {
632 // It happens that we receive multiple follow requests by the same author - we only store one.
633 Logger::info('Follow: Found existing follow request from author', ['author-id' => $item['author-id'], 'parent-uri' => $item['parent-uri']]);
642 * Check if the item array is too old
644 * @param array $item Item record
645 * @return boolean item is too old
647 public static function isTooOld(array $item): bool
649 // check for create date and expire time
650 $expire_interval = DI::config()->get('system', 'dbclean-expire-days', 0);
652 $user = DBA::selectFirst('user', ['expire'], ['uid' => $item['uid']]);
653 if (DBA::isResult($user) && ($user['expire'] > 0) && (($user['expire'] < $expire_interval) || ($expire_interval == 0))) {
654 $expire_interval = $user['expire'];
657 if (($expire_interval > 0) && !empty($item['created'])) {
658 $expire_date = time() - ($expire_interval * 86400);
659 $created_date = strtotime($item['created']);
660 if ($created_date < $expire_date) {
661 Logger::notice('Item created before expiration interval.', [
662 'created' => date('c', $created_date),
663 'expired' => date('c', $expire_date),
674 * Return the id of the given item array if it has been stored before
676 * @param array $item Item record
677 * @return integer Item id or zero on error
679 private static function getDuplicateID(array $item): int
681 if (empty($item['network']) || in_array($item['network'], Protocol::FEDERATED)) {
682 $condition = ['`uri-id` = ? AND `uid` = ? AND `network` IN (?, ?, ?, ?)',
685 Protocol::ACTIVITYPUB,
690 $existing = Post::selectFirst(['id', 'network'], $condition);
691 if (DBA::isResult($existing)) {
692 // We only log the entries with a different user id than 0. Otherwise we would have too many false positives
693 if ($item['uid'] != 0) {
694 Logger::notice('Item already existed for user', [
695 'uri-id' => $item['uri-id'],
696 'uid' => $item['uid'],
697 'network' => $item['network'],
698 'existing_id' => $existing['id'],
699 'existing_network' => $existing['network']
703 return $existing['id'];
710 * Fetch the uri-id of the parent for the given uri-id
712 * @param integer $uriid
715 public static function getParent(int $uriid): int
717 $thread_parent = Post::selectFirstPost(['thr-parent-id', 'gravity'], ['uri-id' => $uriid]);
718 if (empty($thread_parent)) {
722 if ($thread_parent['gravity'] == Item::GRAVITY_PARENT) {
726 return self::getParent($thread_parent['thr-parent-id']);
730 * Fetch top-level parent data for the given item array
733 * @return array item array with parent data
736 private static function getTopLevelParent(array $item): array
738 $fields = ['uid', 'uri', 'parent-uri', 'id', 'deleted',
739 'uri-id', 'parent-uri-id',
740 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid',
741 'wall', 'private', 'origin', 'author-id'];
742 $condition = ['uri-id' => [$item['thr-parent-id'], $item['parent-uri-id']], 'uid' => $item['uid']];
743 $params = ['order' => ['id' => false]];
744 $parent = Post::selectFirst($fields, $condition, $params);
746 if (!DBA::isResult($parent) && Post::exists(['uri-id' => [$item['thr-parent-id'], $item['parent-uri-id']], 'uid' => 0])) {
747 $stored = Item::storeForUserByUriId($item['thr-parent-id'], $item['uid'], ['post-reason' => Item::PR_COMPLETION]);
748 if (!$stored && ($item['thr-parent-id'] != $item['parent-uri-id'])) {
749 $stored = Item::storeForUserByUriId($item['parent-uri-id'], $item['uid'], ['post-reason' => Item::PR_COMPLETION]);
752 Logger::info('Stored thread parent item for user', ['uri-id' => $item['thr-parent-id'], 'uid' => $item['uid'], 'stored' => $stored]);
753 $parent = Post::selectFirst($fields, $condition, $params);
757 if (!DBA::isResult($parent)) {
758 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)]);
762 if ($parent['uri-id'] == $parent['parent-uri-id']) {
766 $condition = ['uri-id' => $parent['parent-uri-id'],
767 'parent-uri-id' => $parent['parent-uri-id'],
768 'uid' => $parent['uid']];
769 $params = ['order' => ['id' => false]];
770 $toplevel_parent = Post::selectFirst($fields, $condition, $params);
772 if (!DBA::isResult($toplevel_parent) && $item['origin']) {
773 $stored = Item::storeForUserByUriId($item['parent-uri-id'], $item['uid'], ['post-reason' => Item::PR_COMPLETION]);
774 Logger::info('Stored parent item for user', ['uri-id' => $item['parent-uri-id'], 'uid' => $item['uid'], 'stored' => $stored]);
775 $toplevel_parent = Post::selectFirst($fields, $condition, $params);
778 if (!DBA::isResult($toplevel_parent)) {
779 Logger::notice('item top level parent was not found - ignoring item', ['parent-uri-id' => $parent['parent-uri-id'], 'uid' => $parent['uid']]);
783 return $toplevel_parent;
787 * Get the gravity for the given item array
790 * @return integer gravity
792 private static function getGravity(array $item): int
794 $activity = DI::activity();
796 if (isset($item['gravity'])) {
797 return intval($item['gravity']);
798 } elseif ($item['parent-uri-id'] === $item['uri-id']) {
799 return self::GRAVITY_PARENT;
800 } elseif ($activity->match($item['verb'], Activity::POST)) {
801 return self::GRAVITY_COMMENT;
802 } elseif ($activity->match($item['verb'], Activity::FOLLOW)) {
803 return self::GRAVITY_ACTIVITY;
804 } elseif ($activity->match($item['verb'], Activity::ANNOUNCE)) {
805 return self::GRAVITY_ACTIVITY;
808 Logger::info('Unknown gravity for verb', ['verb' => $item['verb']]);
809 return self::GRAVITY_UNKNOWN; // Should not happen
813 * Inserts item record
815 * @param array $item Item array to be inserted
816 * @param int $notify Notification (type?)
817 * @param bool $post_local (???)
818 * @return int Zero means error, otherwise primary key (id) is being returned
820 public static function insert(array $item, int $notify = 0, bool $post_local = true): int
824 $priority = Worker::PRIORITY_HIGH;
826 // If it is a posting where users should get notifications, then define it as wall posting
830 $item['network'] = Protocol::DFRN;
831 $item['protocol'] = Conversation::PARCEL_DIRECT;
832 $item['direction'] = Conversation::PUSH;
834 if (is_int($notify) && in_array($notify, Worker::PRIORITIES)) {
838 $item['network'] = trim(($item['network'] ?? '') ?: Protocol::PHANTOM);
841 $uid = intval($item['uid']);
843 $item['guid'] = self::guid($item, $notify);
844 $item['uri'] = substr(trim($item['uri'] ?? '') ?: self::newURI($item['guid']), 0, 255);
847 $item['uri-id'] = ItemURI::insert(['uri' => $item['uri'], 'guid' => $item['guid']]);
849 // Backward compatibility: parent-uri used to be the direct parent uri.
850 // If it is provided without a thr-parent, it probably is the old behavior.
851 if (empty($item['thr-parent']) || empty($item['parent-uri'])) {
852 $item['thr-parent'] = trim($item['thr-parent'] ?? $item['parent-uri'] ?? $item['uri']);
853 $item['parent-uri'] = $item['thr-parent'];
856 $item['thr-parent-id'] = ItemURI::getIdByURI($item['thr-parent']);
857 $item['parent-uri-id'] = ItemURI::getIdByURI($item['parent-uri']);
859 // Store conversation data
860 $source = $item['source'] ?? '';
861 unset($item['conversation-uri']);
862 unset($item['conversation-href']);
863 unset($item['source']);
866 * Do we already have this item?
867 * We have to check several networks since Friendica posts could be repeated
868 * via OStatus (maybe Diasporsa as well)
870 $duplicate = self::getDuplicateID($item);
875 // Additional duplicate checks
876 /// @todo Check why the first duplication check returns the item number and the second a 0
877 if (self::isDuplicate($item)) {
881 if (!isset($item['post-type'])) {
882 $item['post-type'] = empty($item['title']) ? self::PT_NOTE : self::PT_ARTICLE;
885 $item['wall'] = intval($item['wall'] ?? 0);
886 $item['extid'] = trim($item['extid'] ?? '');
887 $item['author-name'] = trim($item['author-name'] ?? '');
888 $item['author-link'] = trim($item['author-link'] ?? '');
889 $item['author-avatar'] = trim($item['author-avatar'] ?? '');
890 $item['owner-name'] = trim($item['owner-name'] ?? '');
891 $item['owner-link'] = trim($item['owner-link'] ?? '');
892 $item['owner-avatar'] = trim($item['owner-avatar'] ?? '');
893 $item['received'] = (isset($item['received']) ? DateTimeFormat::utc($item['received']) : DateTimeFormat::utcNow());
894 $item['created'] = (isset($item['created']) ? DateTimeFormat::utc($item['created']) : $item['received']);
895 $item['edited'] = (isset($item['edited']) ? DateTimeFormat::utc($item['edited']) : $item['created']);
896 $item['changed'] = (isset($item['changed']) ? DateTimeFormat::utc($item['changed']) : $item['created']);
897 $item['commented'] = (isset($item['commented']) ? DateTimeFormat::utc($item['commented']) : $item['created']);
898 $item['title'] = substr(trim($item['title'] ?? ''), 0, 255);
899 $item['location'] = trim($item['location'] ?? '');
900 $item['coord'] = trim($item['coord'] ?? '');
901 $item['visible'] = (isset($item['visible']) ? intval($item['visible']) : 1);
902 $item['deleted'] = 0;
903 $item['verb'] = trim($item['verb'] ?? '');
904 $item['object-type'] = trim($item['object-type'] ?? '');
905 $item['object'] = trim($item['object'] ?? '');
906 $item['target-type'] = trim($item['target-type'] ?? '');
907 $item['target'] = trim($item['target'] ?? '');
908 $item['plink'] = substr(trim($item['plink'] ?? ''), 0, 255);
909 $item['allow_cid'] = trim($item['allow_cid'] ?? '');
910 $item['allow_gid'] = trim($item['allow_gid'] ?? '');
911 $item['deny_cid'] = trim($item['deny_cid'] ?? '');
912 $item['deny_gid'] = trim($item['deny_gid'] ?? '');
913 $item['private'] = intval($item['private'] ?? self::PUBLIC);
914 $item['body'] = trim($item['body'] ?? '');
915 $item['raw-body'] = trim($item['raw-body'] ?? $item['body']);
916 $item['app'] = trim($item['app'] ?? '');
917 $item['origin'] = intval($item['origin'] ?? 0);
918 $item['postopts'] = trim($item['postopts'] ?? '');
919 $item['resource-id'] = trim($item['resource-id'] ?? '');
920 $item['event-id'] = intval($item['event-id'] ?? 0);
921 $item['inform'] = trim($item['inform'] ?? '');
922 $item['file'] = trim($item['file'] ?? '');
924 // Communities aren't working with the Diaspora protoccol
925 if (($uid != 0) && ($item['network'] == Protocol::DIASPORA)) {
926 $user = User::getById($uid, ['account-type']);
927 if ($user['account-type'] == Contact::TYPE_COMMUNITY) {
928 Logger::info('Community posts are not supported via Diaspora');
933 // Items cannot be stored before they happen ...
934 if ($item['created'] > DateTimeFormat::utcNow()) {
935 $item['created'] = DateTimeFormat::utcNow();
938 // We haven't invented time travel by now.
939 if ($item['edited'] > DateTimeFormat::utcNow()) {
940 $item['edited'] = DateTimeFormat::utcNow();
943 $item['plink'] = ($item['plink'] ?? '') ?: DI::baseUrl() . '/display/' . urlencode($item['guid']);
945 $item['gravity'] = self::getGravity($item);
947 $default = ['url' => $item['author-link'], 'name' => $item['author-name'],
948 'photo' => $item['author-avatar'], 'network' => $item['network']];
949 $item['author-id'] = ($item['author-id'] ?? 0) ?: Contact::getIdForURL($item['author-link'], 0, null, $default);
951 $default = ['url' => $item['owner-link'], 'name' => $item['owner-name'],
952 'photo' => $item['owner-avatar'], 'network' => $item['network']];
953 $item['owner-id'] = ($item['owner-id'] ?? 0) ?: Contact::getIdForURL($item['owner-link'], 0, null, $default);
955 $item['post-reason'] = self::getPostReason($item);
957 // Ensure that there is an avatar cache
958 Contact::checkAvatarCache($item['author-id']);
959 Contact::checkAvatarCache($item['owner-id']);
961 $item['contact-id'] = self::contactId($item);
963 if (!empty($item['direction']) && in_array($item['direction'], [Conversation::PUSH, Conversation::RELAY]) &&
964 empty($item['origin']) && self::isTooOld($item)) {
965 Logger::info('Item is too old', ['item' => $item]);
969 if (!self::isValid($item)) {
973 if ($item['gravity'] !== self::GRAVITY_PARENT) {
974 $toplevel_parent = self::getTopLevelParent($item);
975 if (empty($toplevel_parent)) {
979 // If the thread originated from this node, we check the permission against the thread starter
980 $condition = ['uri-id' => $toplevel_parent['uri-id'], 'wall' => true];
981 $localTopLevelParent = Post::selectFirst(['uid'], $condition);
982 if (!empty($localTopLevelParent['uid']) && !self::isAllowedByUser($item, $localTopLevelParent['uid'])) {
986 $parent_id = $toplevel_parent['id'];
987 $item['parent-uri'] = $toplevel_parent['uri'];
988 $item['parent-uri-id'] = $toplevel_parent['uri-id'];
989 $item['deleted'] = $toplevel_parent['deleted'];
991 // Reshares have to keep their permissions to allow forums to work
992 if (!$item['origin'] || ($item['verb'] != Activity::ANNOUNCE)) {
993 $item['allow_cid'] = $toplevel_parent['allow_cid'];
994 $item['allow_gid'] = $toplevel_parent['allow_gid'];
995 $item['deny_cid'] = $toplevel_parent['deny_cid'];
996 $item['deny_gid'] = $toplevel_parent['deny_gid'];
999 $parent_origin = $toplevel_parent['origin'];
1001 // Don't federate received participation messages
1002 if ($item['verb'] != Activity::FOLLOW) {
1003 $item['wall'] = $toplevel_parent['wall'];
1005 $item['wall'] = false;
1006 // Participations are technical messages, so they are set to "seen" automatically
1007 $item['unseen'] = false;
1011 * If the parent is private, force privacy for the entire conversation
1012 * This differs from the above settings as it subtly allows comments from
1013 * email correspondents to be private even if the overall thread is not.
1015 if ($toplevel_parent['private']) {
1016 $item['private'] = $toplevel_parent['private'];
1019 // If its a post that originated here then tag the thread as "mention"
1020 if ($item['origin'] && $item['uid']) {
1021 DBA::update('post-thread-user', ['mention' => true], ['uri-id' => $item['parent-uri-id'], 'uid' => $item['uid']]);
1022 Logger::info('tagged thread as mention', ['parent' => $parent_id, 'parent-uri-id' => $item['parent-uri-id'], 'uid' => $item['uid']]);
1025 // Update the contact relations
1026 Contact\Relation::store($toplevel_parent['author-id'], $item['author-id'], $item['created']);
1029 $parent_origin = $item['origin'];
1031 if ($item['wall'] && empty($item['conversation'])) {
1032 $item['conversation'] = $item['parent-uri'] . '#context';
1036 $item['parent-uri-id'] = ItemURI::getIdByURI($item['parent-uri']);
1037 $item['thr-parent-id'] = ItemURI::getIdByURI($item['thr-parent']);
1039 if (!empty($item['conversation']) && empty($item['conversation-id'])) {
1040 $item['conversation-id'] = ItemURI::getIdByURI($item['conversation']);
1043 // Is this item available in the global items (with uid=0)?
1044 if ($item['uid'] == 0) {
1045 $item['global'] = true;
1047 // Set the global flag on all items if this was a global item entry
1048 Post::update(['global' => true], ['uri-id' => $item['uri-id']]);
1050 $item['global'] = Post::exists(['uid' => 0, 'uri-id' => $item['uri-id']]);
1054 if (!empty($item['allow_cid'] . $item['allow_gid'] . $item['deny_cid'] . $item['deny_gid'])) {
1055 $item['private'] = self::PRIVATE;
1058 if ($notify && $post_local) {
1059 $item['edit'] = false;
1060 $item['parent'] = $parent_id;
1062 // Trigger automatic reactions for addons
1063 if (!isset($item['api_source'])) {
1064 $item['api_source'] = true;
1067 // We have to tell the hooks who we are - this really should be improved
1068 if (!DI::userSession()->getLocalUserId()) {
1069 $_SESSION['authenticated'] = true;
1070 $_SESSION['uid'] = $uid;
1071 $dummy_session = true;
1073 $dummy_session = false;
1076 Hook::callAll('post_local', $item);
1078 if ($dummy_session) {
1079 unset($_SESSION['authenticated']);
1080 unset($_SESSION['uid']);
1082 } elseif (!$notify) {
1083 Hook::callAll('post_remote', $item);
1086 if (!empty($item['cancel'])) {
1087 Logger::notice('post cancelled by addon.');
1091 if (empty($item['vid']) && !empty($item['verb'])) {
1092 $item['vid'] = Verb::getID($item['verb']);
1095 // Creates or assigns the permission set
1096 $item['psid'] = DI::permissionSet()->selectOrCreate(
1097 DI::permissionSetFactory()->createFromString(
1105 if (!empty($item['extid'])) {
1106 $item['external-id'] = ItemURI::getIdByURI($item['extid']);
1109 if ($item['verb'] == Activity::ANNOUNCE) {
1110 self::setOwnerforResharedItem($item);
1113 if (isset($item['attachments'])) {
1114 foreach ($item['attachments'] as $attachment) {
1115 $attachment['uri-id'] = $item['uri-id'];
1116 Post\Media::insert($attachment);
1118 unset($item['attachments']);
1121 Post\Media::insertFromAttachmentData($item['uri-id'], $item['body']);
1123 // Remove all media attachments from the body and store them in the post-media table
1124 $item['raw-body'] = Post\Media::insertFromBody($item['uri-id'], $item['raw-body']);
1125 $item['raw-body'] = self::setHashtags($item['raw-body']);
1127 $quote_id = self::getQuoteUriId($item['body']);
1129 if (!empty($quote_id) && Post::exists(['uri-id' => $quote_id, 'network' => Protocol::FEDERATED])) {
1130 $item['quote-uri-id'] = $quote_id;
1131 $item['raw-body'] = BBCode::removeSharedData($item['raw-body']);
1134 if (!DBA::exists('contact', ['id' => $item['author-id'], 'network' => Protocol::DFRN])) {
1135 Post\Media::insertFromRelevantUrl($item['uri-id'], $item['raw-body']);
1138 // Check for hashtags in the body and repair or add hashtag links
1139 $item['body'] = self::setHashtags($item['body']);
1141 $item['language'] = self::getLanguage($item);
1143 $notify_type = Delivery::POST;
1145 // Filling item related side tables
1146 if (!empty($item['attach'])) {
1147 Post\Media::insertFromAttachment($item['uri-id'], $item['attach']);
1150 if (empty($item['event-id'])) {
1151 unset($item['event-id']);
1153 $ev = Event::fromBBCode($item['body']);
1154 if ((!empty($ev['desc']) || !empty($ev['summary'])) && !empty($ev['start'])) {
1155 Logger::info('Event found.');
1156 $ev['cid'] = $item['contact-id'];
1157 $ev['uid'] = $item['uid'];
1158 $ev['uri'] = $item['uri'];
1159 $ev['edited'] = $item['edited'];
1160 $ev['private'] = $item['private'];
1161 $ev['guid'] = $item['guid'];
1162 $ev['plink'] = $item['plink'];
1163 $ev['network'] = $item['network'];
1164 $ev['protocol'] = $item['protocol'] ?? Conversation::PARCEL_UNKNOWN;
1165 $ev['direction'] = $item['direction'] ?? Conversation::UNKNOWN;
1166 $ev['source'] = $item['source'] ?? '';
1168 $event = DBA::selectFirst('event', ['id'], ['uri' => $item['uri'], 'uid' => $item['uid']]);
1169 if (DBA::isResult($event)) {
1170 $ev['id'] = $event['id'];
1173 $event_id = Event::store($ev);
1174 $item = Event::getItemArrayForImportedId($event_id, $item);
1176 Logger::info('Event was stored', ['id' => $event_id]);
1180 if (empty($item['causer-id'])) {
1181 unset($item['causer-id']);
1184 if (in_array($item['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN])) {
1185 $content_warning = BBCode::getAbstract($item['body'], Protocol::ACTIVITYPUB);
1186 if (!empty($content_warning) && empty($item['content-warning'])) {
1187 $item['content-warning'] = BBCode::toPlaintext($content_warning);
1191 Post::insert($item['uri-id'], $item);
1193 if ($item['gravity'] == self::GRAVITY_PARENT) {
1194 Post\Thread::insert($item['uri-id'], $item);
1197 if (!in_array($item['verb'], self::ACTIVITIES)) {
1198 Post\Content::insert($item['uri-id'], $item);
1201 // Create Diaspora signature
1202 if ($item['origin'] && empty($item['diaspora_signed_text']) && ($item['gravity'] != self::GRAVITY_PARENT)) {
1203 $signed = Diaspora::createCommentSignature($item);
1204 if (!empty($signed)) {
1205 $item['diaspora_signed_text'] = json_encode($signed);
1209 if (!empty($item['diaspora_signed_text'])) {
1210 DBA::replace('diaspora-interaction', ['uri-id' => $item['uri-id'], 'interaction' => $item['diaspora_signed_text']]);
1213 // Attached file links
1214 if (!empty($item['file'])) {
1215 Post\Category::storeTextByURIId($item['uri-id'], $item['uid'], $item['file']);
1218 // Delivery relevant data
1219 $delivery_data = Post\DeliveryData::extractFields($item);
1221 if (!empty($item['origin']) || !empty($item['wall']) || !empty($delivery_data['postopts']) || !empty($delivery_data['inform'])) {
1222 Post\DeliveryData::insert($item['uri-id'], $delivery_data);
1225 // Store tags from the body if this hadn't been handled previously in the protocol classes
1226 if (!Tag::existsForPost($item['uri-id'])) {
1227 Tag::storeFromBody($item['uri-id'], $item['body']);
1230 $condition = ['uri-id' => $item['uri-id'], 'uid' => $item['uid']];
1231 if (Post::exists($condition)) {
1232 Logger::notice('Item is already inserted - aborting', $condition);
1236 $post_user_id = Post\User::insert($item['uri-id'], $item['uid'], $item);
1237 if (!$post_user_id) {
1238 Logger::notice('Post-User is already inserted - aborting', ['uid' => $item['uid'], 'uri-id' => $item['uri-id']]);
1242 if ($item['gravity'] == self::GRAVITY_PARENT) {
1243 $item['post-user-id'] = $post_user_id;
1244 Post\ThreadUser::insert($item['uri-id'], $item['uid'], $item);
1247 Logger::notice('created item', ['post-id' => $post_user_id, 'uid' => $item['uid'], 'network' => $item['network'], 'uri-id' => $item['uri-id'], 'guid' => $item['guid']]);
1249 $posted_item = Post::selectFirst(self::ITEM_FIELDLIST, ['post-user-id' => $post_user_id]);
1250 if (!DBA::isResult($posted_item)) {
1251 // On failure store the data into a spool file so that the "SpoolPost" worker can try again later.
1252 Logger::warning('Could not store item. it will be spooled', ['id' => $post_user_id]);
1253 self::spool($orig_item);
1257 // update the commented timestamp on the parent
1258 if (DI::config()->get('system', 'like_no_comment')) {
1259 // Update when it is a comment
1260 $update_commented = in_array($posted_item['gravity'], [self::GRAVITY_PARENT, self::GRAVITY_COMMENT]);
1262 // Update when it isn't a follow or tag verb
1263 $update_commented = !in_array($posted_item['verb'], [Activity::FOLLOW, Activity::TAG]);
1266 if ($update_commented) {
1267 $fields = ['commented' => DateTimeFormat::utcNow(), 'changed' => DateTimeFormat::utcNow()];
1269 $fields = ['changed' => DateTimeFormat::utcNow()];
1272 Post::update($fields, ['uri-id' => $posted_item['parent-uri-id'], 'uid' => $posted_item['uid']]);
1274 // In that function we check if this is a forum post. Additionally we delete the item under certain circumstances
1275 if (self::tagDeliver($posted_item['uid'], $post_user_id)) {
1276 // Get the user information for the logging
1277 $user = User::getById($uid);
1279 Logger::notice('Item had been deleted', ['id' => $post_user_id, 'user' => $uid, 'account-type' => $user['account-type']]);
1284 if (!\Friendica\Content\Feature::isEnabled($posted_item['uid'], 'explicit_mentions') && ($posted_item['gravity'] == self::GRAVITY_COMMENT)) {
1285 Tag::createImplicitMentions($posted_item['uri-id'], $posted_item['thr-parent-id']);
1287 Hook::callAll('post_local_end', $posted_item);
1289 Hook::callAll('post_remote_end', $posted_item);
1292 if ($posted_item['gravity'] === self::GRAVITY_PARENT) {
1293 self::addShadow($post_user_id);
1295 self::addShadowPost($post_user_id);
1298 self::updateContact($posted_item);
1300 Post\UserNotification::setNotification($posted_item['uri-id'], $posted_item['uid']);
1302 // Distribute items to users who subscribed to their tags
1303 self::distributeByTags($posted_item);
1305 // Automatically reshare the item if the "remote_self" option is selected
1306 self::autoReshare($posted_item);
1308 $transmit = $notify || ($posted_item['visible'] && ($parent_origin || $posted_item['origin']));
1311 // Don't relay participation messages
1312 if (($posted_item['verb'] == Activity::FOLLOW) &&
1313 (!$posted_item['origin'] || ($posted_item['author-id'] != Contact::getPublicIdByUserId($uid)))) {
1314 Logger::info('Participation messages will not be relayed', ['item' => $posted_item['id'], 'uri' => $posted_item['uri'], 'verb' => $posted_item['verb']]);
1320 if (!empty($source)) {
1321 Post\Activity::insert($item['uri-id'], $source);
1323 Worker::add(['priority' => $priority, 'dont_fork' => true], 'Notifier', $notify_type, (int)$posted_item['uri-id'], (int)$posted_item['uid']);
1326 // Fill the cache with the rendered content.
1327 if (in_array($posted_item['gravity'], [self::GRAVITY_PARENT, self::GRAVITY_COMMENT]) && ($posted_item['uid'] == 0)) {
1328 self::updateDisplayCache($posted_item['uri-id']);
1331 return $post_user_id;
1335 * Fetch the post reason for a given item array
1337 * @param array $item
1341 public static function getPostReason(array $item): int
1343 $actor = ($item['gravity'] == self::GRAVITY_PARENT) ? $item['owner-id'] : $item['author-id'];
1344 if (empty($item['origin']) && ($item['uid'] != 0) && Contact::isSharing($actor, $item['uid'])) {
1345 return self::PR_FOLLOWER;
1348 if (!empty($item['origin']) && empty($item['post-reason'])) {
1349 return self::PR_LOCAL;
1352 return $item['post-reason'] ?? self::PR_NONE;
1356 * Update the display cache
1358 * @param integer $uri_id
1361 public static function updateDisplayCache(int $uri_id)
1363 $item = Post::selectFirst(self::DISPLAY_FIELDLIST, ['uri-id' => $uri_id]);
1364 self::prepareBody($item, false, false, true);
1368 * Change the owner of a parent item if it had been shared by a forum
1370 * (public) forum posts in the new format consist of the regular post by the author
1371 * followed by an announce message sent from the forum account.
1372 * Changing the owner helps in grouping forum posts.
1374 * @param array $item
1377 private static function setOwnerforResharedItem(array $item)
1379 $parent = Post::selectFirst(['id', 'causer-id', 'owner-id', 'author-id', 'author-link', 'origin', 'post-reason'],
1380 ['uri-id' => $item['thr-parent-id'], 'uid' => $item['uid']]);
1381 if (!DBA::isResult($parent)) {
1382 Logger::error('Parent not found', ['uri-id' => $item['thr-parent-id'], 'uid' => $item['uid']]);
1386 $author = Contact::selectFirst(['url', 'contact-type', 'network'], ['id' => $item['author-id']]);
1387 if (!DBA::isResult($author)) {
1388 Logger::error('Author not found', ['id' => $item['author-id']]);
1392 $self_contact = Contact::selectFirst(['id'], ['uid' => $item['uid'], 'self' => true]);
1393 $self = !empty($self_contact) ? $self_contact['id'] : 0;
1395 $cid = Contact::getIdForURL($author['url'], $item['uid']);
1396 if (empty($cid) || (!Contact::isSharing($cid, $item['uid']) && ($cid != $self))) {
1397 Logger::info('The resharer is not a following contact: quit', ['resharer' => $author['url'], 'uid' => $item['uid'], 'cid' => $cid]);
1401 if ($author['contact-type'] != Contact::TYPE_COMMUNITY) {
1402 if ($parent['post-reason'] == self::PR_ANNOUNCEMENT) {
1403 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']]);
1407 if (Contact::isSharing($parent['owner-id'], $item['uid'])) {
1408 Logger::info('The resharer is no forum: quit', ['resharer' => $item['author-id'], 'owner' => $parent['owner-id'], 'author' => $parent['author-id'], 'uid' => $item['uid']]);
1413 self::update(['post-reason' => self::PR_ANNOUNCEMENT, 'causer-id' => $item['author-id']], ['id' => $parent['id']]);
1414 Logger::info('Set announcement post-reason', ['uri-id' => $item['uri-id'], 'thr-parent-id' => $item['thr-parent-id'], 'uid' => $item['uid']]);
1418 * Distribute the given item to users who subscribed to their tags
1420 * @param array $item Processed item
1422 private static function distributeByTags(array $item)
1424 if (($item['uid'] != 0) || ($item['gravity'] != self::GRAVITY_PARENT) || !in_array($item['network'], Protocol::FEDERATED)) {
1428 $uids = Tag::getUIDListByURIId($item['uri-id']);
1429 foreach ($uids as $uid) {
1430 $stored = self::storeForUserByUriId($item['uri-id'], $uid, ['post-reason' => self::PR_TAG]);
1431 Logger::info('Stored item for users', ['uri-id' => $item['uri-id'], 'uid' => $uid, 'stored' => $stored]);
1436 * Distributes public items to the receivers
1438 * @param integer $itemid Item ID that should be added
1439 * @param string $signed_text Original text (for Diaspora signatures), JSON encoded.
1440 * @throws \Exception
1442 public static function distribute(int $itemid, string $signed_text = '')
1444 $condition = ["`id` IN (SELECT `parent` FROM `post-user-view` WHERE `id` = ?)", $itemid];
1445 $parent = Post::selectFirst(['owner-id'], $condition);
1446 if (!DBA::isResult($parent)) {
1447 Logger::warning('Item not found', ['condition' => $condition]);
1451 // Only distribute public items from native networks
1452 $condition = ['id' => $itemid, 'uid' => 0,
1453 'network' => array_merge(Protocol::FEDERATED ,['']),
1454 'visible' => true, 'deleted' => false, 'private' => [self::PUBLIC, self::UNLISTED]];
1455 $item = Post::selectFirst(array_merge(self::ITEM_FIELDLIST, ['protocol']), $condition);
1456 if (!DBA::isResult($item)) {
1457 Logger::warning('Item not found', ['condition' => $condition]);
1461 $origin = $item['origin'];
1465 /// @todo add a field "pcid" in the contact table that referrs to the public contact id.
1466 $owner = DBA::selectFirst('contact', ['url', 'nurl', 'alias'], ['id' => $parent['owner-id']]);
1467 if (!DBA::isResult($owner)) {
1471 $condition = ['nurl' => $owner['nurl'], 'rel' => [Contact::SHARING, Contact::FRIEND]];
1472 $contacts = DBA::select('contact', ['uid'], $condition);
1473 while ($contact = DBA::fetch($contacts)) {
1474 if ($contact['uid'] == 0) {
1478 $users[$contact['uid']] = $contact['uid'];
1480 DBA::close($contacts);
1482 $condition = ['alias' => $owner['url'], 'rel' => [Contact::SHARING, Contact::FRIEND]];
1483 $contacts = DBA::select('contact', ['uid'], $condition);
1484 while ($contact = DBA::fetch($contacts)) {
1485 if ($contact['uid'] == 0) {
1489 $users[$contact['uid']] = $contact['uid'];
1491 DBA::close($contacts);
1493 if (!empty($owner['alias'])) {
1494 $condition = ['nurl' => Strings::normaliseLink($owner['alias']), '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);
1508 if ($item['uri-id'] != $item['parent-uri-id']) {
1509 $parents = Post::select(['uid', 'origin'], ["`uri-id` = ? AND `uid` != 0", $item['parent-uri-id']]);
1510 while ($parent = Post::fetch($parents)) {
1511 $users[$parent['uid']] = $parent['uid'];
1512 if ($parent['origin'] && !$origin) {
1513 $origin_uid = $parent['uid'];
1516 DBA::close($parents);
1519 foreach ($users as $uid) {
1520 if ($origin_uid == $uid) {
1521 $item['diaspora_signed_text'] = $signed_text;
1523 $item['post-reason'] = self::PR_DISTRIBUTE;
1524 self::storeForUser($item, $uid);
1529 * Store a public item defined by their URI-ID for the given users
1531 * @param integer $uri_id URI-ID of the given item
1532 * @param integer $uid The user that will receive the item entry
1533 * @param array $fields Additional fields to be stored
1534 * @param integer $source_uid User id of the source post
1535 * @return integer stored item id
1537 public static function storeForUserByUriId(int $uri_id, int $uid, array $fields = [], int $source_uid = 0): int
1539 if ($uid == $source_uid) {
1540 Logger::warning('target UID must not be be equal to the source UID', ['uri-id' => $uri_id, 'uid' => $uid]);
1544 $item = Post::selectFirst(array_merge(self::ITEM_FIELDLIST, ['protocol']), ['uri-id' => $uri_id, 'uid' => $source_uid]);
1545 if (!DBA::isResult($item)) {
1546 Logger::warning('Item could not be fetched', ['uri-id' => $uri_id, 'uid' => $source_uid]);
1550 if (($uid != 0) && ($item['gravity'] == self::GRAVITY_PARENT)) {
1551 $owner = User::getOwnerDataById($uid);
1552 if (($owner['contact-type'] == User::ACCOUNT_TYPE_COMMUNITY) && !Tag::isMentioned($uri_id, $owner['url'])) {
1553 Logger::info('Target user is a forum but is not mentioned here, thread will not be stored', ['uid' => $uid, 'uri-id' => $uri_id]);
1558 if (($source_uid == 0) && (($item['private'] == self::PRIVATE) || !in_array($item['network'], Protocol::FEDERATED))) {
1559 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']]);
1563 $item['post-reason'] = self::PR_STORED;
1565 $item = array_merge($item, $fields);
1567 if (($uid != 0) && Contact::isSharing(($item['gravity'] == Item::GRAVITY_PARENT) ? $item['owner-id'] : $item['author-id'], $uid)) {
1568 $item['post-reason'] = self::PR_FOLLOWER;
1571 $is_reshare = ($item['gravity'] == self::GRAVITY_ACTIVITY) && ($item['verb'] == Activity::ANNOUNCE);
1573 if (($uid != 0) && (($item['gravity'] == self::GRAVITY_PARENT) || $is_reshare) &&
1574 DI::pConfig()->get($uid, 'system', 'accept_only_sharer') == self::COMPLETION_NONE &&
1575 !in_array($item['post-reason'], [self::PR_FOLLOWER, self::PR_TAG, self::PR_TO, self::PR_CC])) {
1576 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']]);
1580 $causer = $item['causer-id'] ?: $item['author-id'];
1582 if (($uri_id != $item['parent-uri-id']) && ($item['gravity'] == self::GRAVITY_COMMENT) && !Post::exists(['uri-id' => $item['parent-uri-id'], 'uid' => $uid])) {
1583 if (!self::fetchParent($item['parent-uri-id'], $uid, $causer)) {
1584 Logger::info('Parent post had not been added', ['uri-id' => $item['parent-uri-id'], 'uid' => $uid, 'causer' => $causer]);
1587 Logger::info('Fetched parent post', ['uri-id' => $item['parent-uri-id'], 'uid' => $uid, 'causer' => $causer]);
1588 } elseif (($uri_id != $item['thr-parent-id']) && $is_reshare && !Post::exists(['uri-id' => $item['thr-parent-id'], 'uid' => $uid])) {
1589 if (!self::fetchParent($item['thr-parent-id'], $uid, $causer)) {
1590 Logger::info('Thread parent had not been added', ['uri-id' => $item['thr-parent-id'], 'uid' => $uid, 'causer' => $causer]);
1593 Logger::info('Fetched thread parent', ['uri-id' => $item['thr-parent-id'], 'uid' => $uid, 'causer' => $causer]);
1596 $stored = self::storeForUser($item, $uid);
1597 Logger::info('Item stored for user', ['uri-id' => $item['uri-id'], 'uid' => $uid, 'causer' => $causer, 'source-uid' => $source_uid, 'stored' => $stored]);
1602 * Fetch the parent with the given uri-id
1604 * @param integer $uri_id
1605 * @param integer $uid
1606 * @param integer $causer
1610 private static function fetchParent(int $uri_id, int $uid, int $causer): int
1612 // Fetch the origin user for the post
1613 $origin_uid = self::GetOriginUidForUriId($uri_id, $uid);
1614 if (is_null($origin_uid)) {
1615 Logger::info('Origin item was not found', ['uid' => $uid, 'uri-id' => $uri_id]);
1619 return self::storeForUserByUriId($uri_id, $uid, ['causer-id' => $causer, 'post-reason' => self::PR_FETCHED], $origin_uid);
1623 * Returns the origin uid of a post if the given user is allowed to see it.
1629 private static function GetOriginUidForUriId(int $uriid, int $uid)
1631 if (Post::exists(['uri-id' => $uriid, 'uid' => $uid])) {
1635 $post = Post::selectFirst(['uid', 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid', 'private'], ['uri-id' => $uriid, 'origin' => true]);
1636 if (!empty($post)) {
1637 if (in_array($post['private'], [Item::PUBLIC, Item::UNLISTED])) {
1638 return $post['uid'];
1641 $pcid = Contact::getPublicIdByUserId($uid);
1646 foreach (Item::enumeratePermissions($post, true) as $receiver) {
1647 if ($receiver == $pcid) {
1648 return $post['uid'];
1655 if (Post::exists(['uri-id' => $uriid, 'uid' => 0])) {
1659 // When the post belongs to a a forum then all forum users are allowed to access it
1660 foreach (Tag::getByURIId($uriid, [Tag::MENTION, Tag::EXCLUSIVE_MENTION]) as $tag) {
1661 if (DBA::exists('contact', ['uid' => $uid, 'nurl' => Strings::normaliseLink($tag['url']), 'contact-type' => Contact::TYPE_COMMUNITY])) {
1662 $target_uid = User::getIdForURL($tag['url']);
1663 if (!empty($target_uid)) {
1673 * Store a public item array for the given users
1675 * @param array $item The item entry that will be stored
1676 * @param integer $uid The user that will receive the item entry
1677 * @return integer stored item id
1678 * @throws \Exception
1680 private static function storeForUser(array $item, int $uid): int
1682 $post = Post::selectFirst(['id'], ['uri-id' => $item['uri-id'], 'uid' => $uid]);
1683 if (!empty($post['id'])) {
1684 if (!empty($item['event-id'])) {
1685 $event_post = Post::selectFirst(['event-id'], ['uri-id' => $item['uri-id'], 'uid' => $uid]);
1686 if (!empty($event_post['event-id'])) {
1687 $event = DBA::selectFirst('event', ['edited', 'start', 'finish', 'summary', 'desc', 'location', 'nofinish', 'adjust'], ['id' => $item['event-id']]);
1688 if (!empty($event)) {
1689 // We aren't using "Event::store" here, since we don't want to trigger any further action
1690 $ret = DBA::update('event', $event, ['id' => $event_post['event-id']]);
1691 Logger::info('Event updated', ['uid' => $uid, 'source-event' => $item['event-id'], 'target-event' => $event_post['event-id'], 'ret' => $ret]);
1695 Logger::info('Item already exists', ['uri-id' => $item['uri-id'], 'uid' => $uid, 'id' => $post['id']]);
1699 // Data from the "post-user" table
1701 unset($item['mention']);
1702 unset($item['starred']);
1703 unset($item['unseen']);
1704 unset($item['psid']);
1705 unset($item['pinned']);
1706 unset($item['ignored']);
1707 unset($item['pubmail']);
1708 unset($item['event-id']);
1709 unset($item['hidden']);
1710 unset($item['notification-type']);
1712 // Data from the "post-delivery-data" table
1713 unset($item['postopts']);
1714 unset($item['inform']);
1716 $item['uid'] = $uid;
1717 $item['origin'] = 0;
1720 $item['contact-id'] = self::contactId($item);
1723 if ($item['gravity'] == self::GRAVITY_PARENT) {
1724 $contact = DBA::selectFirst('contact', [], ['id' => $item['contact-id'], 'self' => false]);
1725 if (DBA::isResult($contact)) {
1726 $notify = self::isRemoteSelf($contact, $item);
1730 $distributed = self::insert($item, $notify);
1732 if (!$distributed) {
1733 Logger::info("Distributed item wasn't stored", ['uri-id' => $item['uri-id'], 'user' => $uid]);
1735 Logger::info('Distributed item was stored', ['uri-id' => $item['uri-id'], 'user' => $uid, 'stored' => $distributed]);
1737 return $distributed;
1741 * Add a shadow entry for a given item id that is a thread starter
1743 * We store every public item entry additionally with the user id "0".
1744 * This is used for the community page and for the search.
1745 * It is planned that in the future we will store public item entries only once.
1747 * @param integer $itemid Item ID that should be added
1748 * @throws \Exception
1750 private static function addShadow(int $itemid)
1752 $fields = ['uid', 'private', 'visible', 'deleted', 'network', 'uri-id'];
1753 $condition = ['id' => $itemid, 'gravity' => self::GRAVITY_PARENT];
1754 $item = Post::selectFirst($fields, $condition);
1756 if (!DBA::isResult($item)) {
1760 // is it already a copy?
1761 if (($itemid == 0) || ($item['uid'] == 0)) {
1765 // Is it a visible public post?
1766 if (!$item["visible"] || $item["deleted"] || ($item["private"] == self::PRIVATE)) {
1770 // is it an entry from a connector? Only add an entry for natively connected networks
1771 if (!in_array($item["network"], array_merge(Protocol::FEDERATED ,['']))) {
1775 if (Post::exists(['uri-id' => $item['uri-id'], 'uid' => 0])) {
1779 $item = Post::selectFirst(array_merge(self::ITEM_FIELDLIST, ['protocol']), ['id' => $itemid]);
1781 if (DBA::isResult($item)) {
1782 // Preparing public shadow (removing user specific data)
1785 unset($item['parent']);
1786 unset($item['wall']);
1787 unset($item['mention']);
1788 unset($item['origin']);
1789 unset($item['starred']);
1790 unset($item['postopts']);
1791 unset($item['inform']);
1792 unset($item['post-reason']);
1793 if ($item['uri-id'] == $item['parent-uri-id']) {
1794 $item['contact-id'] = $item['owner-id'];
1796 $item['contact-id'] = $item['author-id'];
1799 $public_shadow = self::insert($item);
1801 Logger::info('Stored public shadow', ['thread' => $itemid, 'id' => $public_shadow]);
1806 * Add a shadow entry for a given item id that is a comment
1808 * This function does the same like the function above - but for comments
1810 * @param integer $itemid Item ID that should be added
1811 * @throws \Exception
1813 private static function addShadowPost(int $itemid)
1815 $item = Post::selectFirst(array_merge(self::ITEM_FIELDLIST, ['protocol']), ['id' => $itemid]);
1816 if (!DBA::isResult($item)) {
1820 // Is it a toplevel post?
1821 if ($item['gravity'] == self::GRAVITY_PARENT) {
1822 self::addShadow($itemid);
1826 // Is this a shadow entry?
1827 if ($item['uid'] == 0) {
1831 // Is there a shadow parent?
1832 if (!Post::exists(['uri-id' => $item['parent-uri-id'], 'uid' => 0])) {
1836 // Is there already a shadow entry?
1837 if (Post::exists(['uri-id' => $item['uri-id'], 'uid' => 0])) {
1841 // Save "origin" and "parent" state
1842 $origin = $item['origin'];
1843 $parent = $item['parent'];
1845 // Preparing public shadow (removing user specific data)
1848 unset($item['parent']);
1849 unset($item['wall']);
1850 unset($item['mention']);
1851 unset($item['origin']);
1852 unset($item['starred']);
1853 unset($item['postopts']);
1854 unset($item['inform']);
1855 unset($item['post-reason']);
1856 $item['contact-id'] = Contact::getIdForURL($item['author-link']);
1858 $public_shadow = self::insert($item);
1860 Logger::info('Stored public shadow', ['uri-id' => $item['uri-id'], 'id' => $public_shadow]);
1862 // If this was a comment to a Diaspora post we don't get our comment back.
1863 // This means that we have to distribute the comment by ourselves.
1864 if ($origin && Post::exists(['id' => $parent, 'network' => Protocol::DIASPORA])) {
1865 self::distribute($public_shadow);
1870 * Adds a language specification in a "language" element of given $arr.
1871 * Expects "body" element to exist in $arr.
1873 * @param array $item
1874 * @return string detected language
1875 * @throws \Text_LanguageDetect_Exception
1877 private static function getLanguage(array $item): string
1879 if (!empty($item['language'])) {
1880 return $item['language'];
1883 if (!in_array($item['gravity'], [self::GRAVITY_PARENT, self::GRAVITY_COMMENT]) || empty($item['body'])) {
1887 $languages = self::getLanguageArray(trim($item['title'] . "\n" . $item['body']), 3);
1888 if (empty($languages)) {
1892 return json_encode($languages);
1896 * Get a language array from a given text
1898 * @param string $body
1899 * @param integer $count
1902 public static function getLanguageArray(string $body, int $count): array
1904 // Convert attachments to links
1905 $naked_body = BBCode::removeAttachment($body);
1906 if (empty($naked_body)) {
1910 // Remove links and pictures
1911 $naked_body = BBCode::removeLinks($naked_body);
1913 // Convert the title and the body to plain text
1914 $naked_body = BBCode::toPlaintext($naked_body);
1916 // Remove possibly remaining links
1917 $naked_body = preg_replace(Strings::autoLinkRegEx(), '', $naked_body);
1919 if (empty($naked_body)) {
1923 $naked_body = self::getDominantLanguage($naked_body);
1925 $availableLanguages = DI::l10n()->getAvailableLanguages();
1926 // See https://github.com/friendica/friendica/issues/10511
1927 // Persian is manually added to language detection until a persian translation is provided for the interface, at
1928 // which point it will be automatically available through `getAvailableLanguages()` and this should be removed.
1929 $availableLanguages['fa'] = 'fa';
1931 $ld = new Language(array_keys($availableLanguages));
1932 return $ld->detect($naked_body)->limit(0, $count)->close() ?: [];
1936 * Check if latin or non latin are dominant in the body and only return the dominant one
1938 * @param string $body
1941 private static function getDominantLanguage(string $body): string
1945 for ($i = 0; $i < mb_strlen($body); $i++) {
1946 $character = mb_substr($body, $i, 1);
1947 $ord = mb_ord($character);
1949 // We add the most common characters to both strings.
1950 if (($ord <= 64) || ($ord >= 91 && $ord <= 96) || ($ord >= 123 && $ord <= 191) || in_array($ord, [215, 247]) || ($ord >= 697 && $ord <= 735) || ($ord > 65535)) {
1951 $latin .= $character;
1952 $non_latin .= $character;
1953 } elseif ($ord < 768) {
1954 $latin .= $character;
1956 $non_latin .= $character;
1959 return (mb_strlen($latin) > mb_strlen($non_latin)) ? $latin : $non_latin;
1962 public static function getLanguageMessage(array $item): string
1964 $iso639 = new \Matriphe\ISO639\ISO639;
1966 $used_languages = '';
1967 foreach (json_decode($item['language'], true) as $language => $reliability) {
1968 $used_languages .= $iso639->languageByCode1($language) . ' (' . $language . "): " . number_format($reliability, 5) . '\n';
1970 $used_languages = DI::l10n()->t('Detected languages in this post:\n%s', $used_languages);
1971 return $used_languages;
1975 * Creates an unique guid out of a given uri.
1976 * This function is used for messages outside the fediverse (Connector posts, feeds, Mails, ...)
1977 * Posts that are created on this system are using System::createUUID.
1978 * Received ActivityPub posts are using Processor::getGUIDByURL.
1980 * @param string $uri uri of an item entry
1981 * @param string|null $host hostname for the GUID prefix
1982 * @return string Unique guid
1984 public static function guidFromUri(string $uri, string $host = null): string
1986 // Our regular guid routine is using this kind of prefix as well
1987 // We have to avoid that different routines could accidentally create the same value
1988 $parsed = parse_url($uri);
1990 // Remove the scheme to make sure that "https" and "http" doesn't make a difference
1991 unset($parsed['scheme']);
1993 // Glue it together to be able to make a hash from it
1994 $host_id = implode('/', $parsed);
1996 // Use a mixture of several hashes to provide some GUID like experience
1997 return hash('crc32', $host) . '-'. hash('joaat', $host_id) . '-'. hash('fnv164', $host_id);
2001 * generate an unique URI
2003 * @param string $guid An existing GUID (Otherwise it will be generated)
2006 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2008 public static function newURI(string $guid = ''): string
2011 $guid = System::createUUID();
2014 return DI::baseUrl()->get() . '/objects/' . $guid;
2018 * Set "success_update" and "last-item" to the date of the last time we heard from this contact
2020 * This can be used to filter for inactive contacts.
2021 * Only do this for public postings to avoid privacy problems, since poco data is public.
2022 * Don't set this value if it isn't from the owner (could be an author that we don't know)
2024 * @param array $arr Contains the just posted item record
2025 * @throws \Exception
2027 private static function updateContact(array $arr)
2029 // Unarchive the author
2030 $contact = DBA::selectFirst('contact', [], ['id' => $arr["author-id"]]);
2031 if (DBA::isResult($contact)) {
2032 Contact::unmarkForArchival($contact);
2035 // Unarchive the contact if it's not our own contact
2036 $contact = DBA::selectFirst('contact', [], ['id' => $arr["contact-id"], 'self' => false]);
2037 if (DBA::isResult($contact)) {
2038 Contact::unmarkForArchival($contact);
2041 /// @todo On private posts we could obfuscate the date
2042 $update = ($arr['private'] != self::PRIVATE) || in_array($arr['network'], Protocol::FEDERATED);
2044 // Is it a forum? Then we don't care about the rules from above
2045 if (!$update && in_array($arr["network"], [Protocol::ACTIVITYPUB, Protocol::DFRN]) && ($arr["parent-uri-id"] === $arr["uri-id"])) {
2046 if (DBA::exists('contact', ['id' => $arr['contact-id'], 'forum' => true])) {
2052 // The "self" contact id is used (for example in the connectors) when the contact is unknown
2053 // So we have to ensure to only update the last item when it had been our own post,
2054 // or it had been done by a "regular" contact.
2055 if (!empty($arr['wall'])) {
2056 $condition = ['id' => $arr['contact-id']];
2058 $condition = ['id' => $arr['contact-id'], 'self' => false];
2060 Contact::update(['failed' => false, 'local-data' => true, 'success_update' => $arr['received'], 'last-item' => $arr['received']], $condition);
2062 // Now do the same for the system wide contacts with uid=0
2063 if ($arr['private'] != self::PRIVATE) {
2064 Contact::update(['failed' => false, 'local-data' => true, 'success_update' => $arr['received'], 'last-item' => $arr['received']],
2065 ['id' => $arr['owner-id']]);
2067 if ($arr['owner-id'] != $arr['author-id']) {
2068 Contact::update(['failed' => false, 'local-data' => true, 'success_update' => $arr['received'], 'last-item' => $arr['received']],
2069 ['id' => $arr['author-id']]);
2074 public static function setHashtags(string $body): string
2076 $body = BBCode::performWithEscapedTags($body, ['noparse', 'pre', 'code', 'img'], function ($body) {
2077 $tags = BBCode::getTags($body);
2080 if (!count($tags)) {
2084 // This sorting is important when there are hashtags that are part of other hashtags
2085 // Otherwise there could be problems with hashtags like #test and #test2
2086 // Because of this we are sorting from the longest to the shortest tag.
2087 usort($tags, function ($a, $b) {
2088 return strlen($b) <=> strlen($a);
2091 $URLSearchString = "^\[\]";
2093 // All hashtags should point to the home server if "local_tags" is activated
2094 if (DI::config()->get('system', 'local_tags')) {
2095 $body = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
2096 "#[url=" . DI::baseUrl() . "/search?tag=$2]$2[/url]", $body);
2099 // mask hashtags inside of url, bookmarks and attachments to avoid urls in urls
2100 $body = preg_replace_callback("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
2102 return ("[url=" . str_replace("#", "#", $match[1]) . "]" . str_replace("#", "#", $match[2]) . "[/url]");
2105 $body = preg_replace_callback("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism",
2107 return ("[bookmark=" . str_replace("#", "#", $match[1]) . "]" . str_replace("#", "#", $match[2]) . "[/bookmark]");
2110 $body = preg_replace_callback("/\[attachment (.*?)\](.*?)\[\/attachment\]/ism",
2112 return ("[attachment " . str_replace("#", "#", $match[1]) . "]" . $match[2] . "[/attachment]");
2115 // Repair recursive urls
2116 $body = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
2119 foreach ($tags as $tag) {
2120 if ((strpos($tag, '#') !== 0) || strpos($tag, '[url=') || strlen($tag) < 2 || $tag[1] == '#') {
2124 $basetag = str_replace('_', ' ', substr($tag, 1));
2125 $newtag = '#[url=' . DI::baseUrl() . '/search?tag=' . $basetag . ']' . $basetag . '[/url]';
2127 $body = str_replace($tag, $newtag, $body);
2130 // Convert back the masked hashtags
2131 $body = str_replace("#", "#", $body);
2140 * look for mention tags and setup a second delivery chain for forum/community posts if appropriate
2143 * @param int $item_id
2144 * @return boolean true if item was deleted, else false
2145 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2146 * @throws \ImagickException
2148 private static function tagDeliver(int $uid, int $item_id): bool
2152 $owner = User::getOwnerDataById($uid);
2153 if (!DBA::isResult($owner)) {
2154 Logger::warning('User not found, quitting here.', ['uid' => $uid]);
2158 if ($owner['contact-type'] != User::ACCOUNT_TYPE_COMMUNITY) {
2159 Logger::debug('Owner is no community, quitting here.', ['uid' => $uid, 'id' => $item_id]);
2163 $item = Post::selectFirst(self::ITEM_FIELDLIST, ['id' => $item_id, 'gravity' => [self::GRAVITY_PARENT, self::GRAVITY_COMMENT], 'origin' => false]);
2164 if (!DBA::isResult($item)) {
2165 Logger::debug('Post is an activity or origin or not found at all, quitting here.', ['id' => $item_id]);
2169 if ($item['gravity'] == self::GRAVITY_PARENT) {
2170 if (Tag::isMentioned($item['uri-id'], $owner['url'])) {
2171 Logger::info('Mention found in tag.', ['uri' => $item['uri'], 'uid' => $uid, 'id' => $item_id, 'uri-id' => $item['uri-id'], 'guid' => $item['guid']]);
2173 Logger::info('Top-level post without mention is deleted.', ['uri' => $item['uri'], $uid, 'id' => $item_id, 'uri-id' => $item['uri-id'], 'guid' => $item['guid']]);
2174 Post\User::delete(['uri-id' => $item['uri-id'], 'uid' => $item['uid']]);
2178 $arr = ['item' => $item, 'user' => $owner];
2180 Hook::callAll('tagged', $arr);
2182 if (Tag::isMentioned($item['parent-uri-id'], $owner['url'])) {
2183 Logger::info('Mention found in parent tag.', ['uri' => $item['uri'], 'uid' => $uid, 'id' => $item_id, 'uri-id' => $item['uri-id'], 'guid' => $item['guid']]);
2185 Logger::debug('No mentions found in parent, quitting here.', ['id' => $item_id, 'uri-id' => $item['uri-id'], 'guid' => $item['guid']]);
2190 Logger::info('Community post will be distributed', ['uri' => $item['uri'], 'uid' => $uid, 'id' => $item_id, 'uri-id' => $item['uri-id'], 'guid' => $item['guid']]);
2192 if ($owner['page-flags'] == User::PAGE_FLAGS_PRVGROUP) {
2194 $allow_gid = '<' . Group::FOLLOWERS . '>';
2197 self::performActivity($item['id'], 'announce', $uid, $allow_cid, $allow_gid, $deny_cid, $deny_gid);
2199 self::performActivity($item['id'], 'announce', $uid);
2202 Logger::info('Community post had been distributed', ['uri' => $item['uri'], 'uid' => $uid, 'id' => $item_id, 'uri-id' => $item['uri-id'], 'guid' => $item['guid']]);
2207 * Automatically reshare the item if the "remote_self" option is selected
2209 * @param array $item
2212 private static function autoReshare(array $item)
2214 if ($item['gravity'] != self::GRAVITY_PARENT) {
2218 if (!DBA::exists('contact', ['id' => $item['contact-id'], 'remote_self' => Contact::MIRROR_NATIVE_RESHARE])) {
2222 if (!in_array($item['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN])) {
2226 Logger::info('Automatically reshare item', ['uid' => $item['uid'], 'id' => $item['id'], 'guid' => $item['guid'], 'uri-id' => $item['uri-id']]);
2228 self::performActivity($item['id'], 'announce', $item['uid']);
2231 public static function isRemoteSelf(array $contact, array &$datarray): bool
2233 if (!$contact['remote_self']) {
2237 // Prevent the forwarding of posts that are forwarded
2238 if (!empty($datarray["extid"]) && ($datarray["extid"] == Protocol::DFRN)) {
2239 Logger::info('Already forwarded');
2243 // Prevent to forward already forwarded posts
2244 if ($datarray["app"] == DI::baseUrl()->getHostname()) {
2245 Logger::info('Already forwarded (second test)');
2249 // Only forward posts
2250 if ($datarray["verb"] != Activity::POST) {
2251 Logger::info('No post');
2255 if (($contact['network'] != Protocol::FEED) && ($datarray['private'] == self::PRIVATE)) {
2256 Logger::info('Not public');
2260 $datarray2 = $datarray;
2261 Logger::info('remote-self start', ['contact' => $contact['url'], 'remote_self'=> $contact['remote_self'], 'item' => $datarray]);
2262 if ($contact['remote_self'] == Contact::MIRROR_OWN_POST) {
2263 $self = DBA::selectFirst('contact', ['id', 'name', 'url', 'thumb'],
2264 ['uid' => $contact['uid'], 'self' => true]);
2265 if (DBA::isResult($self)) {
2266 $datarray['contact-id'] = $self["id"];
2268 $datarray['owner-name'] = $self["name"];
2269 $datarray['owner-link'] = $self["url"];
2270 $datarray['owner-avatar'] = $self["thumb"];
2272 $datarray['author-name'] = $datarray['owner-name'];
2273 $datarray['author-link'] = $datarray['owner-link'];
2274 $datarray['author-avatar'] = $datarray['owner-avatar'];
2276 unset($datarray['edited']);
2278 unset($datarray['network']);
2279 unset($datarray['owner-id']);
2280 unset($datarray['author-id']);
2283 if ($contact['network'] != Protocol::FEED) {
2284 $old_uri_id = $datarray["uri-id"] ?? 0;
2285 $datarray["guid"] = System::createUUID();
2286 unset($datarray["plink"]);
2287 $datarray["uri"] = self::newURI($datarray["guid"]);
2288 $datarray["uri-id"] = ItemURI::getIdByURI($datarray["uri"]);
2289 $datarray["extid"] = Protocol::DFRN;
2290 $urlpart = parse_url($datarray2['author-link']);
2291 $datarray["app"] = $urlpart["host"];
2292 if (!empty($old_uri_id)) {
2293 Post\Media::copy($old_uri_id, $datarray["uri-id"]);
2296 unset($datarray["parent-uri"]);
2297 unset($datarray["thr-parent"]);
2299 $datarray['private'] = self::PUBLIC;
2303 if ($contact['network'] != Protocol::FEED) {
2304 // Store the original post
2305 $result = self::insert($datarray2);
2306 Logger::info('remote-self post original item', ['contact' => $contact['url'], 'result'=> $result, 'item' => $datarray2]);
2308 $datarray["app"] = "Feed";
2312 return (bool)$result;
2319 * @param array $item
2322 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2323 * @throws \ImagickException
2325 public static function fixPrivatePhotos(string $s, int $uid, array $item = null, int $cid = 0): string
2327 if (DI::config()->get('system', 'disable_embedded')) {
2331 Logger::info('check for photos');
2332 $site = substr(DI::baseUrl(), strpos(DI::baseUrl(), '://'));
2337 $img_start = strpos($orig_body, '[img');
2338 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
2339 $img_len = ($img_start !== false ? strpos(substr($orig_body, $img_start + $img_st_close + 1), '[/img]') : false);
2341 while (($img_st_close !== false) && ($img_len !== false)) {
2342 $img_st_close++; // make it point to AFTER the closing bracket
2343 $image = substr($orig_body, $img_start + $img_st_close, $img_len);
2345 Logger::info('found photo', ['image' => $image]);
2347 if (stristr($image, $site . '/photo/')) {
2348 // Only embed locally hosted photos
2350 $i = basename($image);
2351 $i = str_replace(['.jpg', '.png', '.gif'], ['', '', ''], $i);
2352 $x = strpos($i, '-');
2355 $res = substr($i, $x + 1);
2356 $i = substr($i, 0, $x);
2357 $photo = Photo::getPhotoForUser($uid, $i, $res);
2358 if (DBA::isResult($photo)) {
2360 * Check to see if we should replace this photo link with an embedded image
2361 * 1. No need to do so if the photo is public
2362 * 2. If there's a contact-id provided, see if they're in the access list
2363 * for the photo. If so, embed it.
2364 * 3. Otherwise, if we have an item, see if the item permissions match the photo
2365 * permissions, regardless of order but first check to see if they're an exact
2366 * match to save some processing overhead.
2368 if (self::hasPermissions($photo)) {
2370 $recips = self::enumeratePermissions($photo);
2371 if (in_array($cid, $recips)) {
2375 if (self::samePermissions($uid, $item, $photo)) {
2381 $photo_img = Photo::getImageForPhoto($photo);
2382 // If a custom width and height were specified, apply before embedding
2383 if (preg_match("/\[img\=([0-9]*)x([0-9]*)\]/is", substr($orig_body, $img_start, $img_st_close), $match)) {
2384 Logger::info('scaling photo');
2386 $width = intval($match[1]);
2387 $height = intval($match[2]);
2389 $photo_img->scaleDown(max($width, $height));
2392 $data = $photo_img->asString();
2393 $type = $photo_img->getType();
2395 Logger::info('replacing photo');
2396 $image = 'data:' . $type . ';base64,' . base64_encode($data);
2397 Logger::debug('replaced', ['image' => $image]);
2403 $new_body = $new_body . substr($orig_body, 0, $img_start + $img_st_close) . $image . '[/img]';
2404 $orig_body = substr($orig_body, $img_start + $img_st_close + $img_len + strlen('[/img]'));
2405 if ($orig_body === false) {
2409 $img_start = strpos($orig_body, '[img');
2410 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
2411 $img_len = ($img_start !== false ? strpos(substr($orig_body, $img_start + $img_st_close + 1), '[/img]') : false);
2414 $new_body = $new_body . $orig_body;
2419 private static function hasPermissions(array $obj)
2421 return !empty($obj['allow_cid']) || !empty($obj['allow_gid']) ||
2422 !empty($obj['deny_cid']) || !empty($obj['deny_gid']);
2425 // @TODO $uid is unused parameter
2426 private static function samePermissions($uid, array $obj1, array $obj2): bool
2428 // first part is easy. Check that these are exactly the same.
2429 if (($obj1['allow_cid'] == $obj2['allow_cid'])
2430 && ($obj1['allow_gid'] == $obj2['allow_gid'])
2431 && ($obj1['deny_cid'] == $obj2['deny_cid'])
2432 && ($obj1['deny_gid'] == $obj2['deny_gid'])) {
2436 // This is harder. Parse all the permissions and compare the resulting set.
2437 $recipients1 = self::enumeratePermissions($obj1);
2438 $recipients2 = self::enumeratePermissions($obj2);
2442 /// @TODO Comparison of arrays, maybe use array_diff_assoc() here?
2443 return ($recipients1 == $recipients2);
2447 * Returns an array of contact-ids that are allowed to see this object
2449 * @param array $obj Item array with at least uid, allow_cid, allow_gid, deny_cid and deny_gid
2450 * @param bool $check_dead Prunes unavailable contacts from the result
2452 * @throws \Exception
2454 public static function enumeratePermissions(array $obj, bool $check_dead = false): array
2456 $aclFormater = DI::aclFormatter();
2458 $allow_people = $aclFormater->expand($obj['allow_cid']);
2459 $allow_groups = Group::expand($obj['uid'], $aclFormater->expand($obj['allow_gid']), $check_dead);
2460 $deny_people = $aclFormater->expand($obj['deny_cid']);
2461 $deny_groups = Group::expand($obj['uid'], $aclFormater->expand($obj['deny_gid']), $check_dead);
2462 $recipients = array_unique(array_merge($allow_people, $allow_groups));
2463 $deny = array_unique(array_merge($deny_people, $deny_groups));
2464 $recipients = array_diff($recipients, $deny);
2468 public static function expire(int $uid, int $days, string $network = "", bool $force = false)
2470 if (!$uid || ($days < 1)) {
2474 $condition = ["`uid` = ? AND NOT `deleted` AND `gravity` = ?",
2475 $uid, self::GRAVITY_PARENT];
2478 * $expire_network_only = save your own wall posts
2479 * and just expire conversations started by others
2481 $expire_network_only = DI::pConfig()->get($uid, 'expire', 'network_only', false);
2483 if ($expire_network_only) {
2484 $condition[0] .= " AND NOT `wall`";
2487 if ($network != "") {
2488 $condition[0] .= " AND `network` = ?";
2489 $condition[] = $network;
2492 $condition[0] .= " AND `received` < ?";
2493 $condition[] = DateTimeFormat::utc('now - ' . $days . ' day');
2495 $items = Post::select(['resource-id', 'starred', 'id', 'post-type', 'uid', 'uri-id'], $condition);
2497 if (!DBA::isResult($items)) {
2501 $expire_items = (bool)DI::pConfig()->get($uid, 'expire', 'items', true);
2503 // Forcing expiring of items - but not notes and marked items
2505 $expire_items = true;
2508 $expire_notes = (bool)DI::pConfig()->get($uid, 'expire', 'notes', true);
2509 $expire_starred = (bool)DI::pConfig()->get($uid, 'expire', 'starred', true);
2510 $expire_photos = (bool)DI::pConfig()->get($uid, 'expire', 'photos', false);
2514 $priority = DI::config()->get('system', 'expire-notify-priority');
2516 while ($item = Post::fetch($items)) {
2517 // don't expire filed items
2518 if (DBA::exists('post-category', ['uri-id' => $item['uri-id'], 'uid' => $item['uid'], 'type' => Post\Category::FILE])) {
2522 // Only expire posts, not photos and photo comments
2524 if (!$expire_photos && !empty($item['resource-id'])) {
2526 } elseif (!$expire_starred && intval($item['starred'])) {
2528 } elseif (!$expire_notes && ($item['post-type'] == self::PT_PERSONAL_NOTE)) {
2530 } elseif (!$expire_items && ($item['post-type'] != self::PT_PERSONAL_NOTE)) {
2534 self::markForDeletionById($item['id'], $priority);
2539 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]);
2542 public static function firstPostDate(int $uid, bool $wall = false)
2544 $user = User::getById($uid, ['register_date']);
2549 $condition = ["`uid` = ? AND `wall` = ? AND NOT `deleted` AND `visible` AND `received` >= ?",
2550 $uid, $wall, $user['register_date']];
2551 $params = ['order' => ['received' => false]];
2552 $thread = Post::selectFirstThread(['received'], $condition, $params);
2553 if (DBA::isResult($thread)) {
2554 $postdate = substr(DateTimeFormat::local($thread['received']), 0, 10);
2561 * add/remove activity to an item
2563 * Toggle activities as like,dislike,attend of an item
2565 * @param int $item_id
2566 * @param string $verb
2567 * Activity verb. One of
2568 * like, unlike, dislike, undislike, attendyes, unattendyes,
2569 * attendno, unattendno, attendmaybe, unattendmaybe,
2570 * announce, unannouce
2572 * @param string $allow_cid
2573 * @param string $allow_gid
2574 * @param string $deny_cid
2575 * @param string $deny_gid
2577 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2578 * @throws \ImagickException
2579 * @hook 'post_local_end'
2581 * 'post_id' => ID of posted item
2583 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
2589 Logger::notice('Start create activity', ['verb' => $verb, 'item' => $item_id, 'user' => $uid]);
2591 $item = Post::selectFirst(self::ITEM_FIELDLIST, ['id' => $item_id]);
2592 if (!DBA::isResult($item)) {
2593 Logger::warning('Post had not been fetched', ['id' => $item_id]);
2597 $uri_id = $item['uri-id'];
2599 if (!in_array($item['uid'], [0, $uid])) {
2603 if (!Post::exists(['uri-id' => $item['parent-uri-id'], 'uid' => $uid])) {
2604 $stored = self::storeForUserByUriId($item['parent-uri-id'], $uid, ['post-reason' => Item::PR_ACTIVITY]);
2605 if (($item['parent-uri-id'] == $item['uri-id']) && !empty($stored)) {
2606 $item = Post::selectFirst(self::ITEM_FIELDLIST, ['id' => $stored]);
2607 if (!DBA::isResult($item)) {
2608 Logger::info('Could not fetch just created item - should not happen', ['stored' => $stored, 'uid' => $uid, 'uri-id' => $uri_id]);
2614 // Retrieves the local post owner
2615 $owner = User::getOwnerDataById($uid);
2616 if (empty($owner)) {
2617 Logger::info('Empty owner for user', ['uid' => $uid]);
2621 // Retrieve the current logged in user's public contact
2622 $author_id = Contact::getPublicIdByUserId($uid);
2623 if (empty($author_id)) {
2624 Logger::info('Empty public contact');
2632 $activity = Activity::LIKE;
2636 $activity = Activity::DISLIKE;
2640 $activity = Activity::ATTEND;
2644 $activity = Activity::ATTENDNO;
2647 case 'unattendmaybe':
2648 $activity = Activity::ATTENDMAYBE;
2652 $activity = Activity::FOLLOW;
2656 $activity = Activity::ANNOUNCE;
2659 Logger::warning('unknown verb', ['verb' => $verb, 'item' => $item_id]);
2663 $mode = Strings::startsWith($verb, 'un') ? 'delete' : 'create';
2665 // Enable activity toggling instead of on/off
2666 $event_verb_flag = $activity === Activity::ATTEND || $activity === Activity::ATTENDNO || $activity === Activity::ATTENDMAYBE;
2668 // Look for an existing verb row
2669 // Event participation activities are mutually exclusive, only one of them can exist at all times.
2670 if ($event_verb_flag) {
2671 $verbs = [Activity::ATTEND, Activity::ATTENDNO, Activity::ATTENDMAYBE];
2673 // Translate to the index based activity index
2675 foreach ($verbs as $verb) {
2676 $vids[] = Verb::getID($verb);
2679 $vids = Verb::getID($activity);
2682 $condition = ['vid' => $vids, 'deleted' => false, 'gravity' => self::GRAVITY_ACTIVITY,
2683 'author-id' => $author_id, 'uid' => $item['uid'], 'thr-parent-id' => $uri_id];
2684 $like_item = Post::selectFirst(['id', 'guid', 'verb'], $condition);
2686 if (DBA::isResult($like_item)) {
2688 * Truth table for existing activities
2690 * | Inputs || Outputs |
2691 * |----------------------------||-------------------|
2692 * | Mode | Event | Same verb || Delete? | Return? |
2693 * |--------|-------|-----------||---------|---------|
2694 * | create | Yes | Yes || No | Yes |
2695 * | create | Yes | No || Yes | No |
2696 * | create | No | Yes || No | Yes |
2697 * | create | No | No || N/A†|
2698 * | delete | Yes | Yes || Yes | N/A‡ |
2699 * | delete | Yes | No || No | N/A‡ |
2700 * | delete | No | Yes || Yes | N/A‡ |
2701 * | delete | No | No || N/A†|
2702 * |--------|-------|-----------||---------|---------|
2703 * | A | B | C || A xor C | !B or C |
2705 * †Can't happen: It's impossible to find an existing non-event activity without
2706 * the same verb because we are only looking for this single verb.
2708 * ‡ The "mode = delete" is returning early whether an existing activity was found or not.
2710 if ($mode == 'create' xor $like_item['verb'] == $activity) {
2711 self::markForDeletionById($like_item['id']);
2714 if (!$event_verb_flag || $like_item['verb'] == $activity) {
2719 // No need to go further if we aren't creating anything
2720 if ($mode == 'delete') {
2724 $objtype = $item['resource-id'] ? Activity\ObjectType::IMAGE : Activity\ObjectType::NOTE;
2727 'guid' => System::createUUID(),
2728 'uri' => self::newURI(),
2730 'contact-id' => $owner['id'],
2731 'wall' => $item['wall'],
2733 'network' => Protocol::DFRN,
2734 'protocol' => Conversation::PARCEL_DIRECT,
2735 'direction' => Conversation::PUSH,
2736 'gravity' => self::GRAVITY_ACTIVITY,
2737 'parent' => $item['id'],
2738 'thr-parent' => $item['uri'],
2739 'owner-id' => $author_id,
2740 'author-id' => $author_id,
2741 'body' => $activity,
2742 'verb' => $activity,
2743 'object-type' => $objtype,
2744 'allow_cid' => $allow_cid ?? $item['allow_cid'],
2745 'allow_gid' => $allow_gid ?? $item['allow_gid'],
2746 'deny_cid' => $deny_cid ?? $item['deny_cid'],
2747 'deny_gid' => $deny_gid ?? $item['deny_gid'],
2752 if (in_array($activity, [Activity::LIKE, Activity::DISLIKE])) {
2753 $signed = Diaspora::createLikeSignature($uid, $new_item);
2754 if (!empty($signed)) {
2755 $new_item['diaspora_signed_text'] = json_encode($signed);
2759 self::insert($new_item, true);
2761 // If the parent item isn't visible then set it to visible
2762 // @todo Check if this is still needed
2763 if (!$item['visible']) {
2764 self::update(['visible' => true], ['id' => $item['id']]);
2770 * Fetch the SQL condition for the given user id
2772 * @param integer $owner_id User ID for which the permissions should be fetched
2773 * @return array condition
2775 public static function getPermissionsConditionArrayByUserId(int $owner_id): array
2777 $local_user = DI::userSession()->getLocalUserId();
2778 $remote_user = DI::userSession()->getRemoteContactID($owner_id);
2780 // default permissions - anonymous user
2781 $condition = ["`private` != ?", self::PRIVATE];
2783 if ($local_user && ($local_user == $owner_id)) {
2784 // Profile owner - everything is visible
2786 } elseif ($remote_user) {
2787 // Authenticated visitor - fetch the matching permissionsets
2788 $permissionSets = DI::permissionSet()->selectByContactId($remote_user, $owner_id);
2790 $condition = ["(`private` != ? OR (`private` = ? AND `wall`
2791 AND `psid` IN (" . implode(', ', array_fill(0, count($set), '?')) . ")))",
2792 self::PRIVATE, self::PRIVATE];
2793 $condition = array_merge($condition, $permissionSets->column('id'));
2801 * Get a permission SQL string for the given user
2803 * @param int $owner_id
2804 * @param string $table
2807 public static function getPermissionsSQLByUserId(int $owner_id, string $table = ''): string
2809 $local_user = DI::userSession()->getLocalUserId();
2810 $remote_user = DI::userSession()->getRemoteContactID($owner_id);
2812 if (!empty($table)) {
2813 $table = DBA::quoteIdentifier($table) . '.';
2817 * Construct permissions
2819 * default permissions - anonymous user
2821 $sql = sprintf(" AND " . $table . "`private` != %d", self::PRIVATE);
2823 // Profile owner - everything is visible
2824 if ($local_user && ($local_user == $owner_id)) {
2826 } elseif ($remote_user) {
2828 * Authenticated visitor. Unless pre-verified,
2829 * check that the contact belongs to this $owner_id
2830 * and load the groups the visitor belongs to.
2831 * If pre-verified, the caller is expected to have already
2832 * done this and passed the groups into this function.
2834 $permissionSets = DI::permissionSet()->selectByContactId($remote_user, $owner_id);
2837 $sql_set = sprintf(" OR (" . $table . "`private` = %d AND " . $table . "`wall` AND " . $table . "`psid` IN (", self::PRIVATE) . implode(',', $permissionSets->column('id')) . "))";
2842 $sql = sprintf(" AND (" . $table . "`private` != %d", self::PRIVATE) . $sql_set . ")";
2849 * get translated item type
2851 * @param array $item
2852 * @param \Friendica\Core\L10n $l10n
2855 public static function postType(array $item, \Friendica\Core\L10n $l10n): string
2857 if (!empty($item['event-id'])) {
2858 return $l10n->t('event');
2859 } elseif (!empty($item['resource-id'])) {
2860 return $l10n->t('photo');
2861 } elseif ($item['gravity'] == self::GRAVITY_ACTIVITY) {
2862 return $l10n->t('activity');
2863 } elseif ($item['gravity'] == self::GRAVITY_COMMENT) {
2864 return $l10n->t('comment');
2867 return $l10n->t('post');
2871 * Sets the "rendered-html" field of the provided item
2873 * Body is preserved to avoid side-effects as we modify it just-in-time for spoilers and private image links
2875 * @param array $item
2877 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2878 * @todo Remove reference, simply return "rendered-html" and "rendered-hash"
2880 private static function putInCache(&$item)
2882 // Save original body to prevent addons to modify it
2883 $body = $item['body'];
2885 $rendered_hash = $item['rendered-hash'] ?? '';
2886 $rendered_html = $item['rendered-html'] ?? '';
2888 if ($rendered_hash == ''
2889 || $rendered_html == ''
2890 || $rendered_hash != hash('md5', BBCode::VERSION . '::' . $body)
2891 || DI::config()->get('system', 'ignore_cache')
2893 $item['rendered-html'] = BBCode::convertForUriId($item['uri-id'], $item['body']);
2894 $item['rendered-hash'] = hash('md5', BBCode::VERSION . '::' . $body);
2896 $hook_data = ['item' => $item, 'rendered-html' => $item['rendered-html'], 'rendered-hash' => $item['rendered-hash']];
2897 Hook::callAll('put_item_in_cache', $hook_data);
2898 $item['rendered-html'] = $hook_data['rendered-html'];
2899 $item['rendered-hash'] = $hook_data['rendered-hash'];
2902 // Update if the generated values differ from the existing ones
2903 if ((($rendered_hash != $item['rendered-hash']) || ($rendered_html != $item['rendered-html'])) && !empty($item['id'])) {
2906 'rendered-html' => $item['rendered-html'],
2907 'rendered-hash' => $item['rendered-hash']
2909 ['id' => $item['id']]
2914 $item['body'] = $body;
2918 * Given an item array, convert the body element from bbcode to html and add smilie icons.
2919 * If attach is true, also add icons for item attachments.
2921 * @param array $item Record from item table
2922 * @param boolean $attach If true, add icons for item attachments as well
2923 * @param boolean $is_preview Whether this is a preview
2924 * @param boolean $only_cache Whether only cached HTML should be updated
2925 * @return string item body html
2926 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2927 * @throws \ImagickException
2928 * @hook prepare_body_init item array before any work
2929 * @hook prepare_body_content_filter ('item'=>item array, 'filter_reasons'=>string array) before first bbcode to html
2930 * @hook prepare_body ('item'=>item array, 'html'=>body string, 'is_preview'=>boolean, 'filter_reasons'=>string array) after first bbcode to html
2931 * @hook prepare_body_final ('item'=>item array, 'html'=>body string) after attach icons and blockquote special case handling (spoiler, author)
2933 public static function prepareBody(array &$item, bool $attach = false, bool $is_preview = false, bool $only_cache = false): string
2936 Hook::callAll('prepare_body_init', $item);
2938 // In order to provide theme developers more possibilities, event items
2939 // are treated differently.
2940 if ($item['object-type'] === Activity\ObjectType::EVENT && isset($item['event-id'])) {
2941 $ev = Event::getItemHTML($item);
2945 $tags = Tag::populateFromItem($item);
2947 $item['tags'] = $tags['tags'];
2948 $item['hashtags'] = $tags['hashtags'];
2949 $item['mentions'] = $tags['mentions'];
2951 $body = $item['body'] ?? '';
2952 $shared = BBCode::fetchShareAttributes($body);
2953 if (!empty($shared['guid'])) {
2954 $shared_item = Post::selectFirst(['uri-id', 'guid', 'plink', 'has-media'], ['guid' => $shared['guid'], 'uid' => [$item['uid'], 0]]);
2957 $fields = ['uri-id', 'uri', 'body', 'title', 'author-name', 'author-link', 'author-avatar', 'guid', 'created', 'plink', 'network', 'has-media'];
2962 if (empty($shared_item['uri-id']) && !empty($item['quote-uri-id'])) {
2963 $shared_item = Post::selectFirst($fields, ['uri-id' => $item['quote-uri-id']]);
2964 $quote_uri_id = $item['quote-uri-id'] ?? 0;
2965 $shared_links[] = strtolower($item['quote-uri']);
2966 } elseif (empty($shared_item['uri-id']) && empty($item['quote-uri-id'])) {
2967 $media = Post\Media::getByURIId($item['uri-id'], [Post\Media::ACTIVITY]);
2968 if (!empty($media)) {
2969 $shared_item = Post::selectFirst($fields, ['plink' => $media[0]['url'], 'uid' => [$item['uid'], 0]]);
2971 if (empty($shared_item['uri-id'])) {
2972 $shared_item = Post::selectFirst($fields, ['uri' => $media[0]['url'], 'uid' => [$item['uid'], 0]]);
2973 $shared_links[] = strtolower($media[0]['url']);
2976 $quote_uri_id = $shared_item['uri-id'] ?? 0;
2980 if (!empty($quote_uri_id)) {
2981 $item['body'] .= "\n" . DI::contentItem()->createSharedBlockByArray($shared_item);
2984 if (!empty($shared_item['uri-id'])) {
2985 $shared_uri_id = $shared_item['uri-id'];
2986 $shared_links[] = strtolower($shared_item['plink']);
2987 $shared_attachments = Post\Media::splitAttachments($shared_uri_id, $shared_item['guid'], [], $shared_item['has-media']);
2988 $shared_links = array_merge($shared_links, array_column($shared_attachments['visual'], 'url'));
2989 $shared_links = array_merge($shared_links, array_column($shared_attachments['link'], 'url'));
2990 $shared_links = array_merge($shared_links, array_column($shared_attachments['additional'], 'url'));
2991 $item['body'] = self::replaceVisualAttachments($shared_attachments, $item['body']);
2994 $attachments = Post\Media::splitAttachments($item['uri-id'], $item['guid'] ?? '', $shared_links, $item['has-media'] ?? false);
2995 $item['body'] = self::replaceVisualAttachments($attachments, $item['body'] ?? '');
2997 $item['body'] = preg_replace("/\s*\[attachment .*?\].*?\[\/attachment\]\s*/ism", "\n", $item['body']);
2998 self::putInCache($item);
2999 $item['body'] = $body;
3000 $s = $item["rendered-html"];
3006 // Compile eventual content filter reasons
3007 $filter_reasons = [];
3008 if (!$is_preview && DI::userSession()->getPublicContactId() != $item['author-id']) {
3009 if (!empty($item['content-warning']) && (!DI::userSession()->getLocalUserId() || !DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'system', 'disable_cw', false))) {
3010 $filter_reasons[] = DI::l10n()->t('Content warning: %s', $item['content-warning']);
3013 $item['attachments'] = $attachments;
3017 'filter_reasons' => $filter_reasons
3019 Hook::callAll('prepare_body_content_filter', $hook_data);
3020 $filter_reasons = $hook_data['filter_reasons'];
3027 'preview' => $is_preview,
3028 'filter_reasons' => $filter_reasons
3030 Hook::callAll('prepare_body', $hook_data);
3031 $s = $hook_data['html'];
3035 // Replace the blockquotes with quotes that are used in mails.
3036 $mailquote = '<blockquote type="cite" class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex;">';
3037 $s = str_replace(['<blockquote>', '<blockquote class="spoiler">', '<blockquote class="author">'], [$mailquote, $mailquote, $mailquote], $s);
3041 if (!empty($shared_attachments)) {
3042 $s = self::addVisualAttachments($shared_attachments, $item, $s, true);
3043 $s = self::addLinkAttachment($shared_uri_id ?: $item['uri-id'], $shared_attachments, $body, $s, true, []);
3044 $s = self::addNonVisualAttachments($shared_attachments, $item, $s, true);
3045 $body = preg_replace("/\s*\[share .*?\].*?\[\/share\]\s*/ism", '', $body);
3048 $s = self::addVisualAttachments($attachments, $item, $s, false);
3049 $s = self::addLinkAttachment($item['uri-id'], $attachments, $body, $s, false, $shared_links);
3050 $s = self::addNonVisualAttachments($attachments, $item, $s, false);
3051 $s = self::addQuestions($item, $s);
3054 if (strpos($s, '<div class="map">') !== false && !empty($item['coord'])) {
3055 $x = Map::byCoordinates(trim($item['coord']));
3057 $s = preg_replace('/\<div class\=\"map\"\>/', '$0' . $x, $s);
3061 // Replace friendica image url size with theme preference.
3062 if (!empty($a->getThemeInfoValue('item_image_size'))) {
3063 $ps = $a->getThemeInfoValue('item_image_size');
3064 $s = preg_replace('|(<img[^>]+src="[^"]+/photo/[0-9a-f]+)-[0-9]|', "$1-" . $ps, $s);
3067 $s = HTML::applyContentFilter($s, $filter_reasons);
3069 $hook_data = ['item' => $item, 'html' => $s];
3070 Hook::callAll('prepare_body_final', $hook_data);
3072 return $hook_data['html'];
3076 * Check if the body contains a link
3078 * @param string $body
3079 * @param string $url
3083 public static function containsLink(string $body, string $url, int $type = 0): bool
3085 // Make sure that for example site parameters aren't used when testing if the link is contained in the body
3086 $urlparts = parse_url($url);
3087 if (!empty($urlparts)) {
3088 unset($urlparts['query']);
3089 unset($urlparts['fragment']);
3090 $url = (string)Uri::fromParts($urlparts);
3095 // Remove media links to only search in embedded content
3096 // @todo Check images for image link, audio for audio links, ...
3097 if (in_array($type, [Post\Media::AUDIO, Post\Media::VIDEO, Post\Media::IMAGE])) {
3098 $body = preg_replace("/\[url=[^\[\]]*\](.*)\[\/url\]/Usi", ' $1 ', $body);
3101 if (strpos($body, $url)) {
3104 foreach ([0, 1, 2] as $size) {
3105 if (preg_match('#/photo/.*-' . $size . '\.#ism', $url) &&
3106 strpos(preg_replace('#(/photo/.*)-[012]\.#ism', '$1-' . $size . '.', $body), $url)) {
3114 * Replace visual attachments in the body
3116 * @param array $attachments
3117 * @param string $body
3118 * @return string modified body
3120 private static function replaceVisualAttachments(array $attachments, string $body): string
3122 DI::profiler()->startRecording('rendering');
3124 foreach ($attachments['visual'] as $attachment) {
3125 if (!empty($attachment['preview'])) {
3126 $proxy = Post\Media::getPreviewUrlForId($attachment['id'], Proxy::SIZE_LARGE);
3127 $search = ['[img=' . $attachment['preview'] . ']', ']' . $attachment['preview'] . '[/img]'];
3128 $replace = ['[img=' . $proxy . ']', ']' . $proxy . '[/img]'];
3130 $body = str_replace($search, $replace, $body);
3131 } elseif ($attachment['filetype'] == 'image') {
3132 $proxy = Post\Media::getUrlForId($attachment['id']);
3133 $search = ['[img=' . $attachment['url'] . ']', ']' . $attachment['url'] . '[/img]'];
3134 $replace = ['[img=' . $proxy . ']', ']' . $proxy . '[/img]'];
3136 $body = str_replace($search, $replace, $body);
3139 DI::profiler()->stopRecording();
3144 * Add visual attachments to the content
3146 * @param array $attachments
3147 * @param array $item
3148 * @param string $content
3149 * @return string modified content
3151 private static function addVisualAttachments(array $attachments, array $item, string $content, bool $shared): string
3153 DI::profiler()->startRecording('rendering');
3157 // @todo In the future we should make a single for the template engine with all media in it. This allows more flexibilty.
3158 foreach ($attachments['visual'] as $attachment) {
3159 if (self::containsLink($item['body'], $attachment['preview'] ?? $attachment['url'], $attachment['type'])) {
3163 if (!empty($attachment['preview'])) {
3164 $preview_url = Post\Media::getPreviewUrlForId($attachment['id'], Proxy::SIZE_LARGE);
3169 if (($attachment['filetype'] == 'video')) {
3170 /// @todo Move the template to /content as well
3171 $media = Renderer::replaceMacros(Renderer::getMarkupTemplate('video_top.tpl'), [
3173 'id' => $attachment['id'],
3174 'src' => $attachment['url'],
3175 'name' => $attachment['name'] ?: $attachment['url'],
3176 'preview' => $preview_url,
3177 'mime' => $attachment['mimetype'],
3180 if (($item['post-type'] ?? null) == Item::PT_VIDEO) {
3183 $trailing .= $media;
3185 } elseif ($attachment['filetype'] == 'audio') {
3186 $media = Renderer::replaceMacros(Renderer::getMarkupTemplate('content/audio.tpl'), [
3188 'id' => $attachment['id'],
3189 'src' => $attachment['url'],
3190 'name' => $attachment['name'] ?: $attachment['url'],
3191 'mime' => $attachment['mimetype'],
3194 if (($item['post-type'] ?? null) == Item::PT_AUDIO) {
3197 $trailing .= $media;
3199 } elseif ($attachment['filetype'] == 'image') {
3200 $media = Renderer::replaceMacros(Renderer::getMarkupTemplate('content/image.tpl'), [
3202 'src' => Post\Media::getUrlForId($attachment['id']),
3203 'preview' => Post\Media::getPreviewUrlForId($attachment['id'], ($attachment['width'] > $attachment['height']) ? Proxy::SIZE_MEDIUM : Proxy::SIZE_LARGE),
3204 'attachment' => $attachment,
3207 // On Diaspora posts the attached pictures are leading
3208 if ($item['network'] == Protocol::DIASPORA) {
3211 $trailing .= $media;
3217 $content = str_replace(BBCode::TOP_ANCHOR, '<div class="body-attach">' . $leading . '<div class="clear"></div></div>' . BBCode::TOP_ANCHOR, $content);
3218 $content = str_replace(BBCode::BOTTOM_ANCHOR, '<div class="body-attach">' . $trailing . '<div class="clear"></div></div>' . BBCode::BOTTOM_ANCHOR, $content);
3220 if ($leading != '') {
3221 $content = '<div class="body-attach">' . $leading . '<div class="clear"></div></div>' . $content;
3224 if ($trailing != '') {
3225 $content .= '<div class="body-attach">' . $trailing . '<div class="clear"></div></div>';
3229 DI::profiler()->stopRecording();
3234 * Add link attachment to the content
3236 * @param array $attachments
3237 * @param string $body
3238 * @param string $content
3239 * @param bool $shared
3240 * @param array $ignore_links A list of URLs to ignore
3241 * @return string modified content
3243 private static function addLinkAttachment(int $uriid, array $attachments, string $body, string $content, bool $shared, array $ignore_links): string
3245 DI::profiler()->startRecording('rendering');
3246 // Don't show a preview when there is a visual attachment (audio or video)
3247 $types = array_column($attachments['visual'], 'type');
3248 $preview = !in_array(Post\Media::IMAGE, $types) && !in_array(Post\Media::VIDEO, $types);
3250 if (!empty($attachments['link'])) {
3251 foreach ($attachments['link'] as $link) {
3253 foreach ($ignore_links as $ignore_link) {
3254 if (Strings::compareLink($link['url'], $ignore_link)) {
3258 // @todo Judge between the links to use the one with most information
3259 if (!$found && (empty($attachment) || !empty($link['author-name']) ||
3260 (empty($attachment['name']) && !empty($link['name'])) ||
3261 (empty($attachment['description']) && !empty($link['description'])) ||
3262 (empty($attachment['preview']) && !empty($link['preview'])))) {
3263 $attachment = $link;
3268 if (!empty($attachment)) {
3271 'author_name' => $attachment['author-name'] ?? '',
3272 'author_url' => $attachment['author-url'] ?? '',
3273 'description' => $attachment['description'] ?? '',
3276 'provider_name' => $attachment['publisher-name'] ?? '',
3277 'provider_url' => $attachment['publisher-url'] ?? '',
3279 'title' => $attachment['name'] ?? '',
3281 'url' => $attachment['url']];
3283 if ($preview && !empty($attachment['preview'])) {
3284 if ($attachment['preview-width'] >= 500) {
3285 $data['image'] = Post\Media::getPreviewUrlForId($attachment['id'], Proxy::SIZE_MEDIUM);
3287 $data['preview'] = Post\Media::getPreviewUrlForId($attachment['id'], Proxy::SIZE_MEDIUM);
3291 if (!empty($data['description']) && !empty($content)) {
3292 similar_text($data['description'], $content, $percent);
3297 if (!empty($data['description']) && (($data['title'] == $data['description']) || ($percent > 95) || (strpos($content, $data['description']) !== false))) {
3298 $data['description'] = '';
3301 if (($data['author_name'] ?? '') == ($data['provider_name'] ?? '')) {
3302 $data['author_name'] = '';
3305 if (($data['author_url'] ?? '') == ($data['provider_url'] ?? '')) {
3306 $data['author_url'] = '';
3308 } elseif (preg_match("/.*(\[attachment.*?\].*?\[\/attachment\]).*/ism", $body, $match)) {
3309 $data = BBCode::getAttachmentData($match[1]);
3311 DI::profiler()->stopRecording();
3313 if (isset($data['url']) && !in_array(strtolower($data['url']), $ignore_links)) {
3314 if (!empty($data['description']) || !empty($data['image']) || !empty($data['preview'])) {
3315 $parts = parse_url($data['url']);
3316 if (!empty($parts['scheme']) && !empty($parts['host'])) {
3317 if (empty($data['provider_name'])) {
3318 $data['provider_name'] = $parts['host'];
3320 if (empty($data['provider_url']) || empty(parse_url($data['provider_url'], PHP_URL_SCHEME))) {
3321 $data['provider_url'] = $parts['scheme'] . '://' . $parts['host'];
3323 if (!empty($parts['port'])) {
3324 $data['provider_url'] .= ':' . $parts['port'];
3329 // @todo Use a template
3330 $rendered = BBCode::convertAttachment('', BBCode::INTERNAL, false, $data, $uriid);
3331 } elseif (!self::containsLink($content, $data['url'], Post\Media::HTML)) {
3332 $rendered = Renderer::replaceMacros(Renderer::getMarkupTemplate('content/link.tpl'), [
3333 '$url' => $data['url'],
3334 '$title' => $data['title'],
3341 return str_replace(BBCode::BOTTOM_ANCHOR, BBCode::BOTTOM_ANCHOR . $rendered, $content);
3343 return $content . $rendered;
3350 * Add non visual attachments to the content
3352 * @param array $attachments
3353 * @param array $item
3354 * @param string $content
3355 * @return string modified content
3357 private static function addNonVisualAttachments(array $attachments, array $item, string $content): string
3359 DI::profiler()->startRecording('rendering');
3361 foreach ($attachments['additional'] as $attachment) {
3362 if (strpos($item['body'], $attachment['url'])) {
3366 $author = ['uid' => 0, 'id' => $item['author-id'],
3367 'network' => $item['author-network'], 'url' => $item['author-link']];
3368 $the_url = Contact::magicLinkByContact($author, $attachment['url']);
3370 $title = Strings::escapeHtml(trim(($attachment['description'] ?? '') ?: $attachment['url']));
3372 if (!empty($attachment['size'])) {
3373 $title .= ' ' . $attachment['size'] . ' ' . DI::l10n()->t('bytes');
3376 /// @todo Use a template
3377 $icon = '<div class="attachtype icon s22 type-' . $attachment['filetype'] . ' subtype-' . $attachment['subtype'] . '"></div>';
3378 $trailing .= '<a href="' . strip_tags($the_url) . '" title="' . $title . '" class="attachlink" target="_blank" rel="noopener noreferrer" >' . $icon . '</a>';
3381 if ($trailing != '') {
3382 $content .= '<div class="body-attach">' . $trailing . '<div class="clear"></div></div>';
3385 DI::profiler()->stopRecording();
3389 private static function addQuestions(array $item, string $content): string
3391 DI::profiler()->startRecording('rendering');
3392 if (!empty($item['question-id'])) {
3394 'id' => $item['question-id'],
3395 'multiple' => $item['question-multiple'],
3396 'voters' => $item['question-voters'],
3397 'endtime' => $item['question-end-time']
3400 $options = Post\QuestionOption::getByURIId($item['uri-id']);
3401 foreach ($options as $key => $option) {
3402 if ($question['voters'] > 0) {
3403 $percent = $option['replies'] / $question['voters'] * 100;
3404 $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));
3406 $options[$key]['vote'] = DI::l10n()->tt('%2$s (%1$d vote)', '%2$s (%1$d votes)', $option['replies'], $option['name'], );
3410 if (!empty($question['voters']) && !empty($question['endtime'])) {
3411 $summary = DI::l10n()->tt('%d voter. Poll end: %s', '%d voters. Poll end: %s', $question['voters'], Temporal::getRelativeDate($question['endtime']));
3412 } elseif (!empty($question['voters'])) {
3413 $summary = DI::l10n()->tt('%d voter.', '%d voters.', $question['voters']);
3414 } elseif (!empty($question['endtime'])) {
3415 $summary = DI::l10n()->t('Poll end: %s', Temporal::getRelativeDate($question['endtime']));
3420 $content .= Renderer::replaceMacros(Renderer::getMarkupTemplate('content/question.tpl'), [
3421 '$question' => $question,
3422 '$options' => $options,
3423 '$summary' => $summary,
3426 DI::profiler()->stopRecording();
3431 * get private link for item
3433 * @param array $item
3434 * @return boolean|array False if item has not plink, otherwise array('href'=>plink url, 'title'=>translated title)
3435 * @throws \Exception
3437 public static function getPlink(array $item)
3439 if (!empty($item['plink']) && Network::isValidHttpUrl($item['plink'])) {
3440 $plink = $item['plink'];
3441 } elseif (!empty($item['uri']) && Network::isValidHttpUrl($item['uri']) && !Network::isLocalLink($item['uri'])) {
3442 $plink = $item['uri'];
3445 if (DI::userSession()->getLocalUserId()) {
3447 'href' => "display/" . $item['guid'],
3448 'orig' => "display/" . $item['guid'],
3449 'title' => DI::l10n()->t('View on separate page'),
3450 'orig_title' => DI::l10n()->t('View on separate page'),
3453 if (!empty($plink) && ($item['private'] == self::PRIVATE)) {
3454 $author = ['uid' => 0, 'id' => $item['author-id'],
3455 'network' => $item['author-network'], 'url' => $item['author-link']];
3456 $plink = Contact::magicLinkByContact($author, $plink);
3459 if (!empty($plink)) {
3460 $ret['href'] = DI::baseUrl()->remove($plink);
3461 $ret['title'] = DI::l10n()->t('Link to source');
3463 } elseif (!empty($plink) && ($item['private'] != self::PRIVATE)) {
3467 'title' => DI::l10n()->t('Link to source'),
3468 'orig_title' => DI::l10n()->t('Link to source'),
3478 * Does the given uri-id belongs to a post that is sent as starting post to a forum?
3480 * @param int $uri_id
3482 * @return boolean "true" when it is a forum post
3484 public static function isForumPost(int $uri_id): bool
3486 foreach (Tag::getByURIId($uri_id, [Tag::EXCLUSIVE_MENTION]) as $tag) {
3487 if (DBA::exists('contact', ['uid' => 0, 'nurl' => Strings::normaliseLink($tag['url']), 'contact-type' => Contact::TYPE_COMMUNITY])) {
3495 * Search item id for given URI or plink
3497 * @param string $uri
3498 * @param integer $uid
3500 * @return integer item id
3502 public static function searchByLink(string $uri, int $uid = 0): int
3504 $ssl_uri = str_replace('http://', 'https://', $uri);
3505 $uris = [$uri, $ssl_uri, Strings::normaliseLink($uri)];
3507 $item = Post::selectFirst(['id'], ['uri' => $uris, 'uid' => $uid]);
3508 if (DBA::isResult($item)) {
3512 $item = Post::selectFirst(['id'], ['plink' => $uris, 'uid' => $uid]);
3513 if (DBA::isResult($item)) {
3521 * Return the URI for a link to the post
3523 * @param string $uri URI or link to post
3525 * @return string URI
3527 public static function getURIByLink(string $uri): string
3529 $ssl_uri = str_replace('http://', 'https://', $uri);
3530 $uris = [$uri, $ssl_uri, Strings::normaliseLink($uri)];
3532 $item = Post::selectFirst(['uri'], ['uri' => $uris]);
3533 if (DBA::isResult($item)) {
3534 return $item['uri'];
3537 $item = Post::selectFirst(['uri'], ['plink' => $uris]);
3538 if (DBA::isResult($item)) {
3539 return $item['uri'];
3546 * Fetches item for given URI or plink
3548 * @param string $uri
3549 * @param integer $uid
3551 * @return integer item id
3553 public static function fetchByLink(string $uri, int $uid = 0): int
3555 Logger::info('Trying to fetch link', ['uid' => $uid, 'uri' => $uri]);
3556 $item_id = self::searchByLink($uri, $uid);
3557 if (!empty($item_id)) {
3558 Logger::info('Link found', ['uid' => $uid, 'uri' => $uri, 'id' => $item_id]);
3568 Hook::callAll('item_by_link', $hookData);
3570 if (isset($hookData['item_id'])) {
3571 return is_numeric($hookData['item_id']) ? $hookData['item_id'] : 0;
3574 $fetched_uri = ActivityPub\Processor::fetchMissingActivity($uri);
3577 $item_id = self::searchByLink($fetched_uri, $uid);
3579 $item_id = Diaspora::fetchByURL($uri);
3582 if (!empty($item_id)) {
3583 Logger::info('Link fetched', ['uid' => $uid, 'uri' => $uri, 'id' => $item_id]);
3587 Logger::info('Link not found', ['uid' => $uid, 'uri' => $uri]);
3592 * Return share data from an item array (if the item is shared item)
3593 * We are providing the complete Item array, because at some time in the future
3594 * we hopefully will define these values not in the body anymore but in some item fields.
3595 * This function is meant to replace all similar functions in the system.
3597 * @param array $item
3599 * @return array with share information
3601 public static function getShareArray(array $item): array
3603 return BBCode::fetchShareAttributes($item['body']);
3607 * Check a prospective item array against user-level permissions
3609 * @param array $item Expected keys: uri, gravity, and
3610 * author-link if is author-id is set,
3611 * owner-link if is owner-id is set,
3612 * causer-link if is causer-id is set.
3613 * @param int $user_id Local user ID
3615 * @throws \Exception
3617 protected static function isAllowedByUser(array $item, int $user_id): bool
3619 if (!empty($item['author-id']) && Contact\User::isBlocked($item['author-id'], $user_id)) {
3620 Logger::notice('Author is blocked by user', ['author-link' => $item['author-link'], 'uid' => $user_id, 'item-uri' => $item['uri']]);
3624 if (!empty($item['owner-id']) && Contact\User::isBlocked($item['owner-id'], $user_id)) {
3625 Logger::notice('Owner is blocked by user', ['owner-link' => $item['owner-link'], 'uid' => $user_id, 'item-uri' => $item['uri']]);
3629 // The causer is set during a thread completion, for example because of a reshare. It countains the responsible actor.
3630 if (!empty($item['causer-id']) && Contact\User::isBlocked($item['causer-id'], $user_id)) {
3631 Logger::notice('Causer is blocked by user', ['causer-link' => $item['causer-link'] ?? $item['causer-id'], 'uid' => $user_id, 'item-uri' => $item['uri']]);
3635 if (!empty($item['causer-id']) && ($item['gravity'] === self::GRAVITY_PARENT) && Contact\User::isIgnored($item['causer-id'], $user_id)) {
3636 Logger::notice('Causer is ignored by user', ['causer-link' => $item['causer-link'] ?? $item['causer-id'], 'uid' => $user_id, 'item-uri' => $item['uri']]);
3644 * Improve the data in shared posts
3646 * @param array $item
3647 * @param bool $add_media
3648 * @return string body
3650 public static function improveSharedDataInBody(array $item, bool $add_media = false): string
3652 $shared = BBCode::fetchShareAttributes($item['body']);
3653 if (empty($shared['guid']) && empty($shared['message_id'])) {
3654 return $item['body'];
3657 $link = $shared['link'] ?: $shared['message_id'];
3659 if (empty($shared_content)) {
3660 $shared_content = DI::contentItem()->createSharedPostByUrl($link, $item['uid'] ?? 0, $add_media);
3663 if (empty($shared_content)) {
3664 return $item['body'];
3667 $item['body'] = preg_replace("/\[share.*?\](.*)\[\/share\]/ism", $shared_content, $item['body']);
3669 Logger::debug('New shared data', ['uri-id' => $item['uri-id'], 'link' => $link, 'guid' => $item['guid']]);
3670 return $item['body'];
3674 * Fetch the uri-id of a quote
3676 * @param string $body
3679 private static function getQuoteUriId(string $body): int
3681 $shared = BBCode::fetchShareAttributes($body);
3682 if (empty($shared['message_id'])) {
3685 return ItemURI::getIdByURI($shared['message_id']);