3 * @copyright Copyright (C) 2010-2022, the Friendica project
5 * @license GNU AGPL version 3 or any later version
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU Affero General Public License as
9 * published by the Free Software Foundation, either version 3 of the
10 * License, or (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU Affero General Public License for more details.
17 * You should have received a copy of the GNU Affero General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
22 namespace Friendica\Model;
24 use Friendica\Content\Text\BBCode;
25 use Friendica\Content\Text\HTML;
26 use Friendica\Core\Hook;
27 use Friendica\Core\Logger;
28 use Friendica\Core\Protocol;
29 use Friendica\Core\Renderer;
30 use Friendica\Core\System;
31 use Friendica\Model\Tag;
32 use Friendica\Core\Worker;
33 use Friendica\Database\DBA;
35 use Friendica\Protocol\Activity;
36 use Friendica\Protocol\ActivityPub;
37 use Friendica\Protocol\Diaspora;
38 use Friendica\Util\DateTimeFormat;
39 use Friendica\Util\Map;
40 use Friendica\Util\Network;
41 use Friendica\Util\Proxy;
42 use Friendica\Util\Strings;
43 use Friendica\Util\Temporal;
44 use Friendica\Worker\Delivery;
45 use GuzzleHttp\Psr7\Uri;
46 use LanguageDetection\Language;
50 // Posting types, inspired by https://www.w3.org/TR/activitystreams-vocabulary/#object-types
57 const PT_DOCUMENT = 19;
60 const PT_PERSONAL_NOTE = 128;
62 // Posting reasons (Why had a post been stored for a user?)
69 const PR_FOLLOWER = 69;
70 const PR_ANNOUNCEMENT = 70;
71 const PR_COMMENT = 71;
75 const PR_FETCHED = 75;
76 const PR_COMPLETION = 76;
78 const PR_ACTIVITY = 78;
79 const PR_DISTRIBUTE = 79;
83 // system.accept_only_sharer setting values
84 const COMPLETION_NONE = 1;
85 const COMPLETION_COMMENT = 0;
86 const COMPLETION_LIKE = 2;
88 // Field list that is used to display the items
89 const DISPLAY_FIELDLIST = [
90 'uid', 'id', 'parent', 'guid', 'network', 'gravity',
91 'uri-id', 'uri', 'thr-parent-id', 'thr-parent', 'parent-uri-id', 'parent-uri', 'conversation',
92 'commented', 'created', 'edited', 'received', 'verb', 'object-type', 'postopts', 'plink',
93 'wall', 'private', 'starred', 'origin', 'parent-origin', 'title', 'body', 'language',
94 'content-warning', 'location', 'coord', 'app', 'rendered-hash', 'rendered-html', 'object',
95 'quote-uri', 'quote-uri-id', 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid', 'mention', 'global',
96 'author-id', 'author-link', 'author-name', 'author-avatar', 'author-network', 'author-updated', 'author-gsid', 'author-addr', 'author-uri-id',
97 'owner-id', 'owner-link', 'owner-name', 'owner-avatar', 'owner-network', 'owner-contact-type', 'owner-updated',
98 'causer-id', 'causer-link', 'causer-name', 'causer-avatar', 'causer-contact-type', 'causer-network',
99 'contact-id', 'contact-uid', 'contact-link', 'contact-name', 'contact-avatar',
100 'writable', 'self', 'cid', 'alias',
101 'event-created', 'event-edited', 'event-start', 'event-finish',
102 'event-summary', 'event-desc', 'event-location', 'event-type',
103 'event-nofinish', 'event-ignore', 'event-id',
104 'question-id', 'question-multiple', 'question-voters', 'question-end-time',
105 'has-categories', 'has-media',
106 'delivery_queue_count', 'delivery_queue_done', 'delivery_queue_failed'
109 // Field list that is used to deliver items via the protocols
110 const DELIVER_FIELDLIST = ['uid', 'id', 'parent', 'uri-id', 'uri', 'thr-parent', 'parent-uri', 'guid',
111 'parent-guid', 'conversation', 'received', 'created', 'edited', 'verb', 'object-type', 'object', 'target',
112 'private', 'title', 'body', 'raw-body', 'location', 'coord', 'app',
113 'inform', 'deleted', 'extid', 'post-type', 'post-reason', 'gravity',
114 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid',
115 'author-id', 'author-addr', 'author-link', 'author-name', 'author-avatar', 'owner-id', 'owner-link', 'contact-uid',
116 'signed_text', 'network', 'wall', 'contact-id', 'plink', 'origin',
117 'thr-parent-id', 'parent-uri-id', 'quote-uri', 'quote-uri-id', 'postopts', 'pubmail',
118 'event-created', 'event-edited', 'event-start', 'event-finish',
119 'event-summary', 'event-desc', 'event-location', 'event-type',
120 'event-nofinish', 'event-ignore', 'event-id'];
122 // All fields in the item table
123 const ITEM_FIELDLIST = ['id', 'uid', 'parent', 'uri', 'parent-uri', 'thr-parent',
124 'guid', 'uri-id', 'parent-uri-id', 'thr-parent-id', 'conversation', 'vid',
125 'quote-uri', 'quote-uri-id', 'contact-id', 'wall', 'gravity', 'extid', 'psid',
126 'created', 'edited', 'commented', 'received', 'changed', 'verb',
127 'postopts', 'plink', 'resource-id', 'event-id', 'inform',
128 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid', 'post-type', 'post-reason',
129 'private', 'pubmail', 'visible', 'starred',
130 'unseen', 'deleted', 'origin', 'mention', 'global', 'network',
131 'title', 'content-warning', 'body', 'location', 'coord', 'app',
132 'rendered-hash', 'rendered-html', 'object-type', 'object', 'target-type', 'target',
133 'author-id', 'author-link', 'author-name', 'author-avatar', 'author-network',
134 'owner-id', 'owner-link', 'owner-name', 'owner-avatar', 'causer-id'];
136 // List of all verbs that don't need additional content data.
137 // Never reorder or remove entries from this list. Just add new ones at the end, if needed.
139 Activity::LIKE, Activity::DISLIKE,
140 Activity::ATTEND, Activity::ATTENDNO, Activity::ATTENDMAYBE,
149 // Item weight for query ordering
150 const GRAVITY_PARENT = 0;
151 const GRAVITY_ACTIVITY = 3;
152 const GRAVITY_COMMENT = 6;
153 const GRAVITY_UNKNOWN = 9;
156 * Update existing item entries
158 * @param array $fields The fields that are to be changed
159 * @param array $condition The condition for finding the item entries
161 * In the future we may have to change permissions as well.
162 * Then we had to add the user id as third parameter.
164 * A return value of "0" doesn't mean an error - but that 0 rows had been changed.
166 * @return integer|boolean number of affected rows - or "false" if there was an error
167 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
169 public static function update(array $fields, array $condition)
171 if (empty($condition) || empty($fields)) {
175 if (isset($fields['extid'])) {
176 $fields['external-id'] = ItemURI::getIdByURI($fields['extid']);
179 if (!empty($fields['verb'])) {
180 $fields['vid'] = Verb::getID($fields['verb']);
183 if (!empty($fields['edited'])) {
184 $previous = Post::selectFirst(['edited'], $condition);
187 $rows = Post::update($fields, $condition);
188 if (is_bool($rows)) {
192 // We only need to call the line by line update for specific fields
193 if (empty($fields['body']) && empty($fields['file']) &&
194 empty($fields['attach']) && empty($fields['edited'])) {
198 Logger::info('Updating per single row method', ['fields' => $fields, 'condition' => $condition]);
200 $items = Post::select(['id', 'origin', 'uri-id', 'uid', 'author-network'], $condition);
204 while ($item = DBA::fetch($items)) {
205 if (!empty($fields['body'])) {
206 Post\Media::insertFromAttachmentData($item['uri-id'], $fields['body']);
208 $content_fields = ['raw-body' => trim($fields['raw-body'] ?? $fields['body'])];
210 // Remove all media attachments from the body and store them in the post-media table
211 // @todo On shared postings (Diaspora style and commented reshare) don't fetch content from the shared part
212 $content_fields['raw-body'] = Post\Media::insertFromBody($item['uri-id'], $content_fields['raw-body']);
213 $content_fields['raw-body'] = self::setHashtags($content_fields['raw-body']);
215 if ($item['author-network'] != Protocol::DFRN) {
216 Post\Media::insertFromRelevantUrl($item['uri-id'], $content_fields['raw-body']);
219 Post\Content::update($item['uri-id'], $content_fields);
222 if (!empty($fields['file'])) {
223 Post\Category::storeTextByURIId($item['uri-id'], $item['uid'], $fields['file']);
226 if (!empty($fields['attach'])) {
227 Post\Media::insertFromAttachment($item['uri-id'], $fields['attach']);
230 // We only need to notfiy others when it is an original entry from us.
231 // Only call the notifier when the item had been edited and records had been changed.
232 if ($item['origin'] && !empty($fields['edited']) && ($previous['edited'] != $fields['edited'])) {
233 $notify_items[] = $item['id'];
239 foreach ($notify_items as $notify_item) {
240 $post = Post::selectFirst(['uri-id', 'uid'], ['id' => $notify_item]);
241 Worker::add(Worker::PRIORITY_HIGH, 'Notifier', Delivery::POST, (int)$post['uri-id'], (int)$post['uid']);
248 * Delete an item and notify others about it - if it was ours
250 * @param array $condition The condition for finding the item entries
251 * @param integer $priority Priority for the notification
253 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
255 public static function markForDeletion(array $condition, int $priority = Worker::PRIORITY_HIGH)
257 $items = Post::select(['id'], $condition);
258 while ($item = Post::fetch($items)) {
259 self::markForDeletionById($item['id'], $priority);
265 * Delete an item for an user and notify others about it - if it was ours
267 * @param array $condition The condition for finding the item entries
268 * @param integer $uid User who wants to delete this item
270 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
272 public static function deleteForUser(array $condition, int $uid)
278 $items = Post::select(['id', 'uid', 'uri-id'], $condition);
279 while ($item = Post::fetch($items)) {
280 if (in_array($item['uid'], [$uid, 0])) {
281 Post\User::update($item['uri-id'], $uid, ['hidden' => true], true);
282 Post\ThreadUser::update($item['uri-id'], $uid, ['hidden' => true], true);
285 if ($item['uid'] == $uid) {
286 self::markForDeletionById($item['id'], Worker::PRIORITY_HIGH);
287 } elseif ($item['uid'] != 0) {
288 Logger::warning('Wrong ownership. Not deleting item', ['id' => $item['id']]);
295 * Mark an item for deletion, delete related data and notify others about it - if it was ours
297 * @param integer $item_id
298 * @param integer $priority Priority for the notification
299 * @return boolean success
300 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
302 public static function markForDeletionById(int $item_id, int $priority = Worker::PRIORITY_HIGH): bool
304 Logger::info('Mark item for deletion by id', ['id' => $item_id, 'callstack' => System::callstack()]);
305 // locate item to be deleted
306 $fields = ['id', 'uri', 'uri-id', 'uid', 'parent', 'parent-uri-id', 'origin',
307 'deleted', 'resource-id', 'event-id',
308 'verb', 'object-type', 'object', 'target', 'contact-id', 'psid', 'gravity'];
309 $item = Post::selectFirst($fields, ['id' => $item_id]);
310 if (!DBA::isResult($item)) {
311 Logger::info('Item not found.', ['id' => $item_id]);
315 if ($item['deleted']) {
316 Logger::info('Item has already been marked for deletion.', ['id' => $item_id]);
320 $parent = Post::selectFirst(['origin'], ['id' => $item['parent']]);
321 if (!DBA::isResult($parent)) {
322 $parent = ['origin' => false];
325 // clean up categories and tags so they don't end up as orphans
326 Post\Category::deleteByURIId($item['uri-id'], $item['uid']);
329 * If item is a link to a photo resource, nuke all the associated photos
330 * (visitors will not have photo resources)
331 * This only applies to photos uploaded from the photos page. Photos inserted into a post do not
332 * generate a resource-id and therefore aren't intimately linked to the item.
334 /// @TODO: this should first check if photo is used elsewhere
335 if (strlen($item['resource-id'])) {
336 Photo::delete(['resource-id' => $item['resource-id'], 'uid' => $item['uid']]);
339 // If item is a link to an event, delete the event.
340 if (intval($item['event-id'])) {
341 Event::delete($item['event-id']);
344 // If item has attachments, drop them
345 $attachments = Post\Media::getByURIId($item['uri-id'], [Post\Media::DOCUMENT]);
346 foreach($attachments as $attachment) {
347 if (preg_match('|attach/(\d+)|', $attachment['url'], $matches)) {
348 Attach::delete(['id' => $matches[1], 'uid' => $item['uid']]);
352 // Set the item to "deleted"
353 $item_fields = ['deleted' => true, 'edited' => DateTimeFormat::utcNow(), 'changed' => DateTimeFormat::utcNow()];
354 Post::update($item_fields, ['id' => $item['id']]);
356 Post\Category::storeTextByURIId($item['uri-id'], $item['uid'], '');
358 if (!Post::exists(["`uri-id` = ? AND `uid` != 0 AND NOT `deleted`", $item['uri-id']])) {
359 self::markForDeletion(['uri-id' => $item['uri-id'], 'uid' => 0, 'deleted' => false], $priority);
362 Post\DeliveryData::delete($item['uri-id']);
364 // If it's the parent of a comment thread, kill all the kids
365 if ($item['gravity'] == self::GRAVITY_PARENT) {
366 self::markForDeletion(['parent' => $item['parent'], 'deleted' => false], $priority);
369 // Is it our comment and/or our thread?
370 if (($item['origin'] || $parent['origin']) && ($item['uid'] != 0)) {
371 // When we delete the original post we will delete all existing copies on the server as well
372 self::markForDeletion(['uri-id' => $item['uri-id'], 'deleted' => false], $priority);
374 // send the notification upstream/downstream
376 Worker::add(['priority' => $priority, 'dont_fork' => true], 'Notifier', Delivery::DELETION, (int)$item['uri-id'], (int)$item['uid']);
378 } elseif ($item['uid'] != 0) {
379 Post\User::update($item['uri-id'], $item['uid'], ['hidden' => true]);
380 Post\ThreadUser::update($item['uri-id'], $item['uid'], ['hidden' => true]);
383 Logger::info('Item has been marked for deletion.', ['id' => $item_id]);
389 * Get guid from given item record
391 * @param array $item Item record
392 * @param bool Whether to notify (?)
393 * @return string Guid
395 public static function guid(array $item, bool $notify): string
397 if (!empty($item['guid'])) {
398 return trim($item['guid']);
402 // We have to avoid duplicates. So we create the GUID in form of a hash of the plink or uri.
403 // We add the hash of our own host because our host is the original creator of the post.
404 $prefix_host = DI::baseUrl()->getHostname();
408 // We are only storing the post so we create a GUID from the original hostname.
409 if (!empty($item['author-link'])) {
410 $parsed = parse_url($item['author-link']);
411 if (!empty($parsed['host'])) {
412 $prefix_host = $parsed['host'];
416 if (empty($prefix_host) && !empty($item['plink'])) {
417 $parsed = parse_url($item['plink']);
418 if (!empty($parsed['host'])) {
419 $prefix_host = $parsed['host'];
423 if (empty($prefix_host) && !empty($item['uri'])) {
424 $parsed = parse_url($item['uri']);
425 if (!empty($parsed['host'])) {
426 $prefix_host = $parsed['host'];
430 // Is it in the format data@host.tld? - Used for mail contacts
431 if (empty($prefix_host) && !empty($item['author-link']) && strstr($item['author-link'], '@')) {
432 $mailparts = explode('@', $item['author-link']);
433 $prefix_host = array_pop($mailparts);
437 if (!empty($item['plink'])) {
438 $guid = self::guidFromUri($item['plink'], $prefix_host);
439 } elseif (!empty($item['uri'])) {
440 $guid = self::guidFromUri($item['uri'], $prefix_host);
442 $guid = System::createUUID(hash('crc32', $prefix_host));
449 * Returns contact id from given item record
451 * @param array $item Item record
452 * @return int Contact id
454 private static function contactId(array $item): int
456 if ($item['uid'] == 0) {
457 return $item['author-id'];
460 if ($item['origin']) {
461 $owner = User::getOwnerDataById($item['uid']);
465 if (!empty($item['causer-id']) && Contact::isSharing($item['causer-id'], $item['uid'], true)) {
466 $cdata = Contact::getPublicAndUserContactID($item['causer-id'], $item['uid']);
467 if (!empty($cdata['user'])) {
468 return $cdata['user'];
472 if ($item['gravity'] == self::GRAVITY_PARENT) {
473 if (Contact::isSharingByURL($item['owner-link'], $item['uid'], true)) {
474 $contact_id = Contact::getIdForURL($item['owner-link'], $item['uid']);
476 $contact_id = Contact::getIdForURL($item['owner-link']);
478 if (!empty($contact_id)) {
483 if (Contact::isSharingByURL($item['author-link'], $item['uid'], true)) {
484 $contact_id = Contact::getIdForURL($item['author-link'], $item['uid']);
486 $contact_id = Contact::getIdForURL($item['author-link']);
489 if (!empty($contact_id)) {
493 Logger::warning('contact-id could not be fetched, using self contact instead.', ['uid' => $item['uid'], 'item' => $item]);
494 $self = Contact::selectFirst(['id'], ['self' => true, 'uid' => $item['uid']]);
499 * Write an item array into a spool file to be inserted later.
500 * This command is called whenever there are issues storing an item.
502 * @param array $item The item fields that are to be inserted
505 private static function spool(array $item)
507 // Now we store the data in the spool directory
508 // We use "microtime" to keep the arrival order and "mt_rand" to avoid duplicates
509 $file = 'item-' . round(microtime(true) * 10000) . '-' . mt_rand() . '.msg';
511 $spoolpath = System::getSpoolPath();
512 if ($spoolpath != '') {
513 $spool = $spoolpath . '/' . $file;
515 file_put_contents($spool, json_encode($item));
516 Logger::warning("Item wasn't stored - Item was spooled into file", ['file' => $file]);
521 * Check if the item array is a duplicate
523 * @param array $item Item record
524 * @return boolean is it a duplicate?
526 private static function isDuplicate(array $item): bool
528 // Checking if there is already an item with the same guid
529 $condition = ['guid' => $item['guid'], 'network' => $item['network'], 'uid' => $item['uid']];
530 if (Post::exists($condition)) {
531 Logger::notice('Found already existing item', $condition);
535 $condition = ['uri-id' => $item['uri-id'], 'uid' => $item['uid'],
536 'network' => [$item['network'], Protocol::DFRN]];
537 if (Post::exists($condition)) {
538 Logger::notice('duplicated item with the same uri found.', $condition);
542 // On Friendica and Diaspora the GUID is unique
543 if (in_array($item['network'], [Protocol::DFRN, Protocol::DIASPORA])) {
544 $condition = ['guid' => $item['guid'], 'uid' => $item['uid']];
545 if (Post::exists($condition)) {
546 Logger::notice('duplicated item with the same guid found.', $condition);
549 } elseif ($item['network'] == Protocol::OSTATUS) {
550 // Check for an existing post with the same content. There seems to be a problem with OStatus.
551 $condition = ["`body` = ? AND `network` = ? AND `created` = ? AND `contact-id` = ? AND `uid` = ?",
552 $item['body'], $item['network'], $item['created'], $item['contact-id'], $item['uid']];
553 if (Post::exists($condition)) {
554 Logger::notice('duplicated item with the same body found.', $item);
560 * Check for already added items.
561 * There is a timing issue here that sometimes creates double postings.
562 * An unique index would help - but the limitations of MySQL (maximum size of index values) prevent this.
564 if (($item['uid'] == 0) && Post::exists(['uri-id' => $item['uri-id'], 'uid' => 0])) {
565 Logger::notice('Global item already stored.', ['uri-id' => $item['uri-id'], 'network' => $item['network']]);
573 * Check if the item array is valid
575 * @param array $item Item record
576 * @return boolean item is valid
578 public static function isValid(array $item): bool
580 // When there is no content then we don't post it
581 if (($item['body'] . $item['title'] == '') && (empty($item['uri-id']) || !Post\Media::existsByURIId($item['uri-id']))) {
582 Logger::notice('No body, no title.');
586 if (!empty($item['uid'])) {
587 $owner = User::getOwnerDataById($item['uid'], false);
589 Logger::warning('Missing item user owner data', ['uid' => $item['uid']]);
593 if ($owner['account_expired'] || $owner['account_removed']) {
594 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']]);
599 if (!empty($item['author-id']) && Contact::isBlocked($item['author-id'])) {
600 Logger::notice('Author is blocked node-wide', ['author-link' => $item['author-link'], 'item-uri' => $item['uri']]);
604 if (!empty($item['author-link']) && Network::isUrlBlocked($item['author-link'])) {
605 Logger::notice('Author server is blocked', ['author-link' => $item['author-link'], 'item-uri' => $item['uri']]);
609 if (!empty($item['owner-id']) && Contact::isBlocked($item['owner-id'])) {
610 Logger::notice('Owner is blocked node-wide', ['owner-link' => $item['owner-link'], 'item-uri' => $item['uri']]);
614 if (!empty($item['owner-link']) && Network::isUrlBlocked($item['owner-link'])) {
615 Logger::notice('Owner server is blocked', ['owner-link' => $item['owner-link'], 'item-uri' => $item['uri']]);
619 if (!empty($item['uid']) && !self::isAllowedByUser($item, $item['uid'])) {
623 if ($item['verb'] == Activity::FOLLOW) {
624 if (!$item['origin'] && ($item['author-id'] == Contact::getPublicIdByUserId($item['uid']))) {
625 // Our own follow request can be relayed to us. We don't store it to avoid notification chaos.
626 Logger::info("Follow: Don't store not origin follow request", ['parent-uri' => $item['parent-uri']]);
630 $condition = ['verb' => Activity::FOLLOW, 'uid' => $item['uid'],
631 'parent-uri' => $item['parent-uri'], 'author-id' => $item['author-id']];
632 if (Post::exists($condition)) {
633 // It happens that we receive multiple follow requests by the same author - we only store one.
634 Logger::info('Follow: Found existing follow request from author', ['author-id' => $item['author-id'], 'parent-uri' => $item['parent-uri']]);
643 * Check if the item array is too old
645 * @param array $item Item record
646 * @return boolean item is too old
648 public static function isTooOld(array $item): bool
650 // check for create date and expire time
651 $expire_interval = DI::config()->get('system', 'dbclean-expire-days', 0);
653 $user = DBA::selectFirst('user', ['expire'], ['uid' => $item['uid']]);
654 if (DBA::isResult($user) && ($user['expire'] > 0) && (($user['expire'] < $expire_interval) || ($expire_interval == 0))) {
655 $expire_interval = $user['expire'];
658 if (($expire_interval > 0) && !empty($item['created'])) {
659 $expire_date = time() - ($expire_interval * 86400);
660 $created_date = strtotime($item['created']);
661 if ($created_date < $expire_date) {
662 Logger::notice('Item created before expiration interval.', [
663 'created' => date('c', $created_date),
664 'expired' => date('c', $expire_date),
675 * Return the id of the given item array if it has been stored before
677 * @param array $item Item record
678 * @return integer Item id or zero on error
680 private static function getDuplicateID(array $item): int
682 if (empty($item['network']) || in_array($item['network'], Protocol::FEDERATED)) {
683 $condition = ['`uri-id` = ? AND `uid` = ? AND `network` IN (?, ?, ?, ?)',
686 Protocol::ACTIVITYPUB,
691 $existing = Post::selectFirst(['id', 'network'], $condition);
692 if (DBA::isResult($existing)) {
693 // We only log the entries with a different user id than 0. Otherwise we would have too many false positives
694 if ($item['uid'] != 0) {
695 Logger::notice('Item already existed for user', [
696 'uri-id' => $item['uri-id'],
697 'uid' => $item['uid'],
698 'network' => $item['network'],
699 'existing_id' => $existing['id'],
700 'existing_network' => $existing['network']
704 return $existing['id'];
711 * Fetch the uri-id of the parent for the given uri-id
713 * @param integer $uriid
716 public static function getParent(int $uriid): int
718 $thread_parent = Post::selectFirstPost(['thr-parent-id', 'gravity'], ['uri-id' => $uriid]);
719 if (empty($thread_parent)) {
723 if ($thread_parent['gravity'] == Item::GRAVITY_PARENT) {
727 return self::getParent($thread_parent['thr-parent-id']);
731 * Fetch top-level parent data for the given item array
734 * @return array item array with parent data
737 private static function getTopLevelParent(array $item): array
739 $fields = ['uid', 'uri', 'parent-uri', 'id', 'deleted',
740 'uri-id', 'parent-uri-id',
741 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid',
742 'wall', 'private', 'origin', 'author-id'];
743 $condition = ['uri-id' => [$item['thr-parent-id'], $item['parent-uri-id']], 'uid' => $item['uid']];
744 $params = ['order' => ['id' => false]];
745 $parent = Post::selectFirst($fields, $condition, $params);
747 if (!DBA::isResult($parent) && Post::exists(['uri-id' => [$item['thr-parent-id'], $item['parent-uri-id']], 'uid' => 0])) {
748 $stored = Item::storeForUserByUriId($item['thr-parent-id'], $item['uid'], ['post-reason' => Item::PR_COMPLETION]);
749 if (!$stored && ($item['thr-parent-id'] != $item['parent-uri-id'])) {
750 $stored = Item::storeForUserByUriId($item['parent-uri-id'], $item['uid'], ['post-reason' => Item::PR_COMPLETION]);
753 Logger::info('Stored thread parent item for user', ['uri-id' => $item['thr-parent-id'], 'uid' => $item['uid'], 'stored' => $stored]);
754 $parent = Post::selectFirst($fields, $condition, $params);
758 if (!DBA::isResult($parent)) {
759 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)]);
763 if ($parent['uri-id'] == $parent['parent-uri-id']) {
767 $condition = ['uri-id' => $parent['parent-uri-id'],
768 'parent-uri-id' => $parent['parent-uri-id'],
769 'uid' => $parent['uid']];
770 $params = ['order' => ['id' => false]];
771 $toplevel_parent = Post::selectFirst($fields, $condition, $params);
773 if (!DBA::isResult($toplevel_parent) && $item['origin']) {
774 $stored = Item::storeForUserByUriId($item['parent-uri-id'], $item['uid'], ['post-reason' => Item::PR_COMPLETION]);
775 Logger::info('Stored parent item for user', ['uri-id' => $item['parent-uri-id'], 'uid' => $item['uid'], 'stored' => $stored]);
776 $toplevel_parent = Post::selectFirst($fields, $condition, $params);
779 if (!DBA::isResult($toplevel_parent)) {
780 Logger::notice('item top level parent was not found - ignoring item', ['parent-uri-id' => $parent['parent-uri-id'], 'uid' => $parent['uid']]);
784 return $toplevel_parent;
788 * Get the gravity for the given item array
791 * @return integer gravity
793 private static function getGravity(array $item): int
795 $activity = DI::activity();
797 if (isset($item['gravity'])) {
798 return intval($item['gravity']);
799 } elseif ($item['parent-uri-id'] === $item['uri-id']) {
800 return self::GRAVITY_PARENT;
801 } elseif ($activity->match($item['verb'], Activity::POST)) {
802 return self::GRAVITY_COMMENT;
803 } elseif ($activity->match($item['verb'], Activity::FOLLOW)) {
804 return self::GRAVITY_ACTIVITY;
805 } elseif ($activity->match($item['verb'], Activity::ANNOUNCE)) {
806 return self::GRAVITY_ACTIVITY;
809 Logger::info('Unknown gravity for verb', ['verb' => $item['verb']]);
810 return self::GRAVITY_UNKNOWN; // Should not happen
814 * Inserts item record
816 * @param array $item Item array to be inserted
817 * @param int $notify Notification (type?)
818 * @param bool $post_local (???)
819 * @return int Zero means error, otherwise primary key (id) is being returned
821 public static function insert(array $item, int $notify = 0, bool $post_local = true): int
825 $priority = Worker::PRIORITY_HIGH;
827 // If it is a posting where users should get notifications, then define it as wall posting
831 $item['network'] = Protocol::DFRN;
832 $item['protocol'] = Conversation::PARCEL_DIRECT;
833 $item['direction'] = Conversation::PUSH;
835 if (is_int($notify) && in_array($notify, Worker::PRIORITIES)) {
839 $item['network'] = trim(($item['network'] ?? '') ?: Protocol::PHANTOM);
842 $uid = intval($item['uid']);
844 $item['guid'] = self::guid($item, $notify);
845 $item['uri'] = substr(trim($item['uri'] ?? '') ?: self::newURI($item['guid']), 0, 255);
848 $item['uri-id'] = ItemURI::insert(['uri' => $item['uri'], 'guid' => $item['guid']]);
850 // Backward compatibility: parent-uri used to be the direct parent uri.
851 // If it is provided without a thr-parent, it probably is the old behavior.
852 if (empty($item['thr-parent']) || empty($item['parent-uri'])) {
853 $item['thr-parent'] = trim($item['thr-parent'] ?? $item['parent-uri'] ?? $item['uri']);
854 $item['parent-uri'] = $item['thr-parent'];
857 $item['thr-parent-id'] = ItemURI::getIdByURI($item['thr-parent']);
858 $item['parent-uri-id'] = ItemURI::getIdByURI($item['parent-uri']);
860 // Store conversation data
861 $source = $item['source'] ?? '';
862 unset($item['conversation-uri']);
863 unset($item['conversation-href']);
864 unset($item['source']);
867 * Do we already have this item?
868 * We have to check several networks since Friendica posts could be repeated
869 * via OStatus (maybe Diasporsa as well)
871 $duplicate = self::getDuplicateID($item);
876 // Additional duplicate checks
877 /// @todo Check why the first duplication check returns the item number and the second a 0
878 if (self::isDuplicate($item)) {
882 if (!isset($item['post-type'])) {
883 $item['post-type'] = empty($item['title']) ? self::PT_NOTE : self::PT_ARTICLE;
886 $item['wall'] = intval($item['wall'] ?? 0);
887 $item['extid'] = trim($item['extid'] ?? '');
888 $item['author-name'] = trim($item['author-name'] ?? '');
889 $item['author-link'] = trim($item['author-link'] ?? '');
890 $item['author-avatar'] = trim($item['author-avatar'] ?? '');
891 $item['owner-name'] = trim($item['owner-name'] ?? '');
892 $item['owner-link'] = trim($item['owner-link'] ?? '');
893 $item['owner-avatar'] = trim($item['owner-avatar'] ?? '');
894 $item['received'] = (isset($item['received']) ? DateTimeFormat::utc($item['received']) : DateTimeFormat::utcNow());
895 $item['created'] = (isset($item['created']) ? DateTimeFormat::utc($item['created']) : $item['received']);
896 $item['edited'] = (isset($item['edited']) ? DateTimeFormat::utc($item['edited']) : $item['created']);
897 $item['changed'] = (isset($item['changed']) ? DateTimeFormat::utc($item['changed']) : $item['created']);
898 $item['commented'] = (isset($item['commented']) ? DateTimeFormat::utc($item['commented']) : $item['created']);
899 $item['title'] = substr(trim($item['title'] ?? ''), 0, 255);
900 $item['location'] = trim($item['location'] ?? '');
901 $item['coord'] = trim($item['coord'] ?? '');
902 $item['visible'] = (isset($item['visible']) ? intval($item['visible']) : 1);
903 $item['deleted'] = 0;
904 $item['verb'] = trim($item['verb'] ?? '');
905 $item['object-type'] = trim($item['object-type'] ?? '');
906 $item['object'] = trim($item['object'] ?? '');
907 $item['target-type'] = trim($item['target-type'] ?? '');
908 $item['target'] = trim($item['target'] ?? '');
909 $item['plink'] = substr(trim($item['plink'] ?? ''), 0, 255);
910 $item['allow_cid'] = trim($item['allow_cid'] ?? '');
911 $item['allow_gid'] = trim($item['allow_gid'] ?? '');
912 $item['deny_cid'] = trim($item['deny_cid'] ?? '');
913 $item['deny_gid'] = trim($item['deny_gid'] ?? '');
914 $item['private'] = intval($item['private'] ?? self::PUBLIC);
915 $item['body'] = trim($item['body'] ?? '');
916 $item['raw-body'] = trim($item['raw-body'] ?? $item['body']);
917 $item['app'] = trim($item['app'] ?? '');
918 $item['origin'] = intval($item['origin'] ?? 0);
919 $item['postopts'] = trim($item['postopts'] ?? '');
920 $item['resource-id'] = trim($item['resource-id'] ?? '');
921 $item['event-id'] = intval($item['event-id'] ?? 0);
922 $item['inform'] = trim($item['inform'] ?? '');
923 $item['file'] = trim($item['file'] ?? '');
925 // Communities aren't working with the Diaspora protoccol
926 if (($uid != 0) && ($item['network'] == Protocol::DIASPORA)) {
927 $user = User::getById($uid, ['account-type']);
928 if ($user['account-type'] == Contact::TYPE_COMMUNITY) {
929 Logger::info('Community posts are not supported via Diaspora');
934 // Items cannot be stored before they happen ...
935 if ($item['created'] > DateTimeFormat::utcNow()) {
936 $item['created'] = DateTimeFormat::utcNow();
939 // We haven't invented time travel by now.
940 if ($item['edited'] > DateTimeFormat::utcNow()) {
941 $item['edited'] = DateTimeFormat::utcNow();
944 $item['plink'] = ($item['plink'] ?? '') ?: DI::baseUrl() . '/display/' . urlencode($item['guid']);
946 $item['gravity'] = self::getGravity($item);
948 $default = ['url' => $item['author-link'], 'name' => $item['author-name'],
949 'photo' => $item['author-avatar'], 'network' => $item['network']];
950 $item['author-id'] = ($item['author-id'] ?? 0) ?: Contact::getIdForURL($item['author-link'], 0, null, $default);
952 $default = ['url' => $item['owner-link'], 'name' => $item['owner-name'],
953 'photo' => $item['owner-avatar'], 'network' => $item['network']];
954 $item['owner-id'] = ($item['owner-id'] ?? 0) ?: Contact::getIdForURL($item['owner-link'], 0, null, $default);
956 $item['post-reason'] = self::getPostReason($item);
958 // Ensure that there is an avatar cache
959 Contact::checkAvatarCache($item['author-id']);
960 Contact::checkAvatarCache($item['owner-id']);
962 $item['contact-id'] = self::contactId($item);
964 if (!empty($item['direction']) && in_array($item['direction'], [Conversation::PUSH, Conversation::RELAY]) &&
965 empty($item['origin']) && self::isTooOld($item)) {
966 Logger::info('Item is too old', ['item' => $item]);
970 if (!self::isValid($item)) {
974 if ($item['gravity'] !== self::GRAVITY_PARENT) {
975 $toplevel_parent = self::getTopLevelParent($item);
976 if (empty($toplevel_parent)) {
980 // If the thread originated from this node, we check the permission against the thread starter
981 $condition = ['uri-id' => $toplevel_parent['uri-id'], 'wall' => true];
982 $localTopLevelParent = Post::selectFirst(['uid'], $condition);
983 if (!empty($localTopLevelParent['uid']) && !self::isAllowedByUser($item, $localTopLevelParent['uid'])) {
987 $parent_id = $toplevel_parent['id'];
988 $item['parent-uri'] = $toplevel_parent['uri'];
989 $item['parent-uri-id'] = $toplevel_parent['uri-id'];
990 $item['deleted'] = $toplevel_parent['deleted'];
992 // Reshares have to keep their permissions to allow forums to work
993 if (!$item['origin'] || ($item['verb'] != Activity::ANNOUNCE)) {
994 $item['allow_cid'] = $toplevel_parent['allow_cid'];
995 $item['allow_gid'] = $toplevel_parent['allow_gid'];
996 $item['deny_cid'] = $toplevel_parent['deny_cid'];
997 $item['deny_gid'] = $toplevel_parent['deny_gid'];
1000 $parent_origin = $toplevel_parent['origin'];
1002 // Don't federate received participation messages
1003 if ($item['verb'] != Activity::FOLLOW) {
1004 $item['wall'] = $toplevel_parent['wall'];
1006 $item['wall'] = false;
1007 // Participations are technical messages, so they are set to "seen" automatically
1008 $item['unseen'] = false;
1012 * If the parent is private, force privacy for the entire conversation
1013 * This differs from the above settings as it subtly allows comments from
1014 * email correspondents to be private even if the overall thread is not.
1016 if ($toplevel_parent['private']) {
1017 $item['private'] = $toplevel_parent['private'];
1020 // If its a post that originated here then tag the thread as "mention"
1021 if ($item['origin'] && $item['uid']) {
1022 DBA::update('post-thread-user', ['mention' => true], ['uri-id' => $item['parent-uri-id'], 'uid' => $item['uid']]);
1023 Logger::info('tagged thread as mention', ['parent' => $parent_id, 'parent-uri-id' => $item['parent-uri-id'], 'uid' => $item['uid']]);
1026 // Update the contact relations
1027 Contact\Relation::store($toplevel_parent['author-id'], $item['author-id'], $item['created']);
1030 $parent_origin = $item['origin'];
1032 if ($item['wall'] && empty($item['conversation'])) {
1033 $item['conversation'] = $item['parent-uri'] . '#context';
1037 $item['parent-uri-id'] = ItemURI::getIdByURI($item['parent-uri']);
1038 $item['thr-parent-id'] = ItemURI::getIdByURI($item['thr-parent']);
1040 if (!empty($item['conversation']) && empty($item['conversation-id'])) {
1041 $item['conversation-id'] = ItemURI::getIdByURI($item['conversation']);
1044 // Is this item available in the global items (with uid=0)?
1045 if ($item['uid'] == 0) {
1046 $item['global'] = true;
1048 // Set the global flag on all items if this was a global item entry
1049 Post::update(['global' => true], ['uri-id' => $item['uri-id']]);
1051 $item['global'] = Post::exists(['uid' => 0, 'uri-id' => $item['uri-id']]);
1055 if (!empty($item['allow_cid'] . $item['allow_gid'] . $item['deny_cid'] . $item['deny_gid'])) {
1056 $item['private'] = self::PRIVATE;
1059 if ($notify && $post_local) {
1060 $item['edit'] = false;
1061 $item['parent'] = $parent_id;
1063 // Trigger automatic reactions for addons
1064 if (!isset($item['api_source'])) {
1065 $item['api_source'] = true;
1068 // We have to tell the hooks who we are - this really should be improved
1069 if (!DI::userSession()->getLocalUserId()) {
1070 $_SESSION['authenticated'] = true;
1071 $_SESSION['uid'] = $uid;
1072 $dummy_session = true;
1074 $dummy_session = false;
1077 Hook::callAll('post_local', $item);
1079 if ($dummy_session) {
1080 unset($_SESSION['authenticated']);
1081 unset($_SESSION['uid']);
1083 } elseif (!$notify) {
1084 Hook::callAll('post_remote', $item);
1087 if (!empty($item['cancel'])) {
1088 Logger::notice('post cancelled by addon.');
1092 if (empty($item['vid']) && !empty($item['verb'])) {
1093 $item['vid'] = Verb::getID($item['verb']);
1096 // Creates or assigns the permission set
1097 $item['psid'] = DI::permissionSet()->selectOrCreate(
1098 DI::permissionSetFactory()->createFromString(
1106 if (!empty($item['extid'])) {
1107 $item['external-id'] = ItemURI::getIdByURI($item['extid']);
1110 if ($item['verb'] == Activity::ANNOUNCE) {
1111 self::setOwnerforResharedItem($item);
1114 if (isset($item['attachments'])) {
1115 foreach ($item['attachments'] as $attachment) {
1116 $attachment['uri-id'] = $item['uri-id'];
1117 Post\Media::insert($attachment);
1119 unset($item['attachments']);
1122 Post\Media::insertFromAttachmentData($item['uri-id'], $item['body']);
1124 // Remove all media attachments from the body and store them in the post-media table
1125 $item['raw-body'] = Post\Media::insertFromBody($item['uri-id'], $item['raw-body']);
1126 $item['raw-body'] = self::setHashtags($item['raw-body']);
1128 $quote_id = self::getQuoteUriId($item['body']);
1130 if (!empty($quote_id) && Post::exists(['uri-id' => $quote_id, 'network' => Protocol::FEDERATED])) {
1131 $item['quote-uri-id'] = $quote_id;
1132 $item['raw-body'] = BBCode::removeSharedData($item['raw-body']);
1135 if (!DBA::exists('contact', ['id' => $item['author-id'], 'network' => Protocol::DFRN])) {
1136 Post\Media::insertFromRelevantUrl($item['uri-id'], $item['raw-body']);
1139 // Check for hashtags in the body and repair or add hashtag links
1140 $item['body'] = self::setHashtags($item['body']);
1142 $item['language'] = self::getLanguage($item);
1144 $notify_type = Delivery::POST;
1146 // Filling item related side tables
1147 if (!empty($item['attach'])) {
1148 Post\Media::insertFromAttachment($item['uri-id'], $item['attach']);
1151 if (empty($item['event-id'])) {
1152 unset($item['event-id']);
1154 $ev = Event::fromBBCode($item['body']);
1155 if ((!empty($ev['desc']) || !empty($ev['summary'])) && !empty($ev['start'])) {
1156 Logger::info('Event found.');
1157 $ev['cid'] = $item['contact-id'];
1158 $ev['uid'] = $item['uid'];
1159 $ev['uri'] = $item['uri'];
1160 $ev['edited'] = $item['edited'];
1161 $ev['private'] = $item['private'];
1162 $ev['guid'] = $item['guid'];
1163 $ev['plink'] = $item['plink'];
1164 $ev['network'] = $item['network'];
1165 $ev['protocol'] = $item['protocol'] ?? Conversation::PARCEL_UNKNOWN;
1166 $ev['direction'] = $item['direction'] ?? Conversation::UNKNOWN;
1167 $ev['source'] = $item['source'] ?? '';
1169 $event = DBA::selectFirst('event', ['id'], ['uri' => $item['uri'], 'uid' => $item['uid']]);
1170 if (DBA::isResult($event)) {
1171 $ev['id'] = $event['id'];
1174 $event_id = Event::store($ev);
1175 $item = Event::getItemArrayForImportedId($event_id, $item);
1177 Logger::info('Event was stored', ['id' => $event_id]);
1181 if (empty($item['causer-id'])) {
1182 unset($item['causer-id']);
1185 if (in_array($item['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN])) {
1186 $content_warning = BBCode::getAbstract($item['body'], Protocol::ACTIVITYPUB);
1187 if (!empty($content_warning) && empty($item['content-warning'])) {
1188 $item['content-warning'] = BBCode::toPlaintext($content_warning);
1192 Post::insert($item['uri-id'], $item);
1194 if ($item['gravity'] == self::GRAVITY_PARENT) {
1195 Post\Thread::insert($item['uri-id'], $item);
1198 if (!in_array($item['verb'], self::ACTIVITIES)) {
1199 Post\Content::insert($item['uri-id'], $item);
1202 // Create Diaspora signature
1203 if ($item['origin'] && empty($item['diaspora_signed_text']) && ($item['gravity'] != self::GRAVITY_PARENT)) {
1204 $signed = Diaspora::createCommentSignature($item);
1205 if (!empty($signed)) {
1206 $item['diaspora_signed_text'] = json_encode($signed);
1210 if (!empty($item['diaspora_signed_text'])) {
1211 DBA::replace('diaspora-interaction', ['uri-id' => $item['uri-id'], 'interaction' => $item['diaspora_signed_text']]);
1214 // Attached file links
1215 if (!empty($item['file'])) {
1216 Post\Category::storeTextByURIId($item['uri-id'], $item['uid'], $item['file']);
1219 // Delivery relevant data
1220 $delivery_data = Post\DeliveryData::extractFields($item);
1222 if (!empty($item['origin']) || !empty($item['wall']) || !empty($delivery_data['postopts']) || !empty($delivery_data['inform'])) {
1223 Post\DeliveryData::insert($item['uri-id'], $delivery_data);
1226 // Store tags from the body if this hadn't been handled previously in the protocol classes
1227 if (!Tag::existsForPost($item['uri-id'])) {
1228 Tag::storeFromBody($item['uri-id'], $item['body']);
1231 $condition = ['uri-id' => $item['uri-id'], 'uid' => $item['uid']];
1232 if (Post::exists($condition)) {
1233 Logger::notice('Item is already inserted - aborting', $condition);
1237 $post_user_id = Post\User::insert($item['uri-id'], $item['uid'], $item);
1238 if (!$post_user_id) {
1239 Logger::notice('Post-User is already inserted - aborting', ['uid' => $item['uid'], 'uri-id' => $item['uri-id']]);
1243 if ($item['gravity'] == self::GRAVITY_PARENT) {
1244 $item['post-user-id'] = $post_user_id;
1245 Post\ThreadUser::insert($item['uri-id'], $item['uid'], $item);
1248 Logger::notice('created item', ['post-id' => $post_user_id, 'uid' => $item['uid'], 'network' => $item['network'], 'uri-id' => $item['uri-id'], 'guid' => $item['guid']]);
1250 $posted_item = Post::selectFirst(self::ITEM_FIELDLIST, ['post-user-id' => $post_user_id]);
1251 if (!DBA::isResult($posted_item)) {
1252 // On failure store the data into a spool file so that the "SpoolPost" worker can try again later.
1253 Logger::warning('Could not store item. it will be spooled', ['id' => $post_user_id]);
1254 self::spool($orig_item);
1258 // update the commented timestamp on the parent
1259 if (DI::config()->get('system', 'like_no_comment')) {
1260 // Update when it is a comment
1261 $update_commented = in_array($posted_item['gravity'], [self::GRAVITY_PARENT, self::GRAVITY_COMMENT]);
1263 // Update when it isn't a follow or tag verb
1264 $update_commented = !in_array($posted_item['verb'], [Activity::FOLLOW, Activity::TAG]);
1267 if ($update_commented) {
1268 $fields = ['commented' => DateTimeFormat::utcNow(), 'changed' => DateTimeFormat::utcNow()];
1270 $fields = ['changed' => DateTimeFormat::utcNow()];
1273 Post::update($fields, ['uri-id' => $posted_item['parent-uri-id'], 'uid' => $posted_item['uid']]);
1275 // In that function we check if this is a forum post. Additionally we delete the item under certain circumstances
1276 if (self::tagDeliver($posted_item['uid'], $post_user_id)) {
1277 // Get the user information for the logging
1278 $user = User::getById($uid);
1280 Logger::notice('Item had been deleted', ['id' => $post_user_id, 'user' => $uid, 'account-type' => $user['account-type']]);
1285 if (!\Friendica\Content\Feature::isEnabled($posted_item['uid'], 'explicit_mentions') && ($posted_item['gravity'] == self::GRAVITY_COMMENT)) {
1286 Tag::createImplicitMentions($posted_item['uri-id'], $posted_item['thr-parent-id']);
1288 Hook::callAll('post_local_end', $posted_item);
1290 Hook::callAll('post_remote_end', $posted_item);
1293 if ($posted_item['gravity'] === self::GRAVITY_PARENT) {
1294 self::addShadow($post_user_id);
1296 self::addShadowPost($post_user_id);
1299 self::updateContact($posted_item);
1301 Post\UserNotification::setNotification($posted_item['uri-id'], $posted_item['uid']);
1303 // Distribute items to users who subscribed to their tags
1304 self::distributeByTags($posted_item);
1306 // Automatically reshare the item if the "remote_self" option is selected
1307 self::autoReshare($posted_item);
1309 $transmit = $notify || ($posted_item['visible'] && ($parent_origin || $posted_item['origin']));
1312 // Don't relay participation messages
1313 if (($posted_item['verb'] == Activity::FOLLOW) &&
1314 (!$posted_item['origin'] || ($posted_item['author-id'] != Contact::getPublicIdByUserId($uid)))) {
1315 Logger::info('Participation messages will not be relayed', ['item' => $posted_item['id'], 'uri' => $posted_item['uri'], 'verb' => $posted_item['verb']]);
1321 if (!empty($source)) {
1322 Post\Activity::insert($item['uri-id'], $source);
1324 Worker::add(['priority' => $priority, 'dont_fork' => true], 'Notifier', $notify_type, (int)$posted_item['uri-id'], (int)$posted_item['uid']);
1327 // Fill the cache with the rendered content.
1328 if (in_array($posted_item['gravity'], [self::GRAVITY_PARENT, self::GRAVITY_COMMENT]) && ($posted_item['uid'] == 0)) {
1329 self::updateDisplayCache($posted_item['uri-id']);
1332 return $post_user_id;
1336 * Fetch the post reason for a given item array
1338 * @param array $item
1342 public static function getPostReason(array $item): int
1344 $actor = ($item['gravity'] == self::GRAVITY_PARENT) ? $item['owner-id'] : $item['author-id'];
1345 if (empty($item['origin']) && ($item['uid'] != 0) && Contact::isSharing($actor, $item['uid'])) {
1346 return self::PR_FOLLOWER;
1349 if (!empty($item['origin']) && empty($item['post-reason'])) {
1350 return self::PR_LOCAL;
1353 return $item['post-reason'] ?? self::PR_NONE;
1357 * Update the display cache
1359 * @param integer $uri_id
1362 public static function updateDisplayCache(int $uri_id)
1364 $item = Post::selectFirst(self::DISPLAY_FIELDLIST, ['uri-id' => $uri_id]);
1365 self::prepareBody($item, false, false, true);
1369 * Change the owner of a parent item if it had been shared by a forum
1371 * (public) forum posts in the new format consist of the regular post by the author
1372 * followed by an announce message sent from the forum account.
1373 * Changing the owner helps in grouping forum posts.
1375 * @param array $item
1378 private static function setOwnerforResharedItem(array $item)
1380 $parent = Post::selectFirst(['id', 'causer-id', 'owner-id', 'author-id', 'author-link', 'origin', 'post-reason'],
1381 ['uri-id' => $item['thr-parent-id'], 'uid' => $item['uid']]);
1382 if (!DBA::isResult($parent)) {
1383 Logger::error('Parent not found', ['uri-id' => $item['thr-parent-id'], 'uid' => $item['uid']]);
1387 $author = Contact::selectFirst(['url', 'contact-type', 'network'], ['id' => $item['author-id']]);
1388 if (!DBA::isResult($author)) {
1389 Logger::error('Author not found', ['id' => $item['author-id']]);
1393 $self_contact = Contact::selectFirst(['id'], ['uid' => $item['uid'], 'self' => true]);
1394 $self = !empty($self_contact) ? $self_contact['id'] : 0;
1396 $cid = Contact::getIdForURL($author['url'], $item['uid']);
1397 if (empty($cid) || (!Contact::isSharing($cid, $item['uid']) && ($cid != $self))) {
1398 Logger::info('The resharer is not a following contact: quit', ['resharer' => $author['url'], 'uid' => $item['uid'], 'cid' => $cid]);
1402 if ($author['contact-type'] != Contact::TYPE_COMMUNITY) {
1403 if ($parent['post-reason'] == self::PR_ANNOUNCEMENT) {
1404 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']]);
1408 if (Contact::isSharing($parent['owner-id'], $item['uid'])) {
1409 Logger::info('The resharer is no forum: quit', ['resharer' => $item['author-id'], 'owner' => $parent['owner-id'], 'author' => $parent['author-id'], 'uid' => $item['uid']]);
1414 self::update(['post-reason' => self::PR_ANNOUNCEMENT, 'causer-id' => $item['author-id']], ['id' => $parent['id']]);
1415 Logger::info('Set announcement post-reason', ['uri-id' => $item['uri-id'], 'thr-parent-id' => $item['thr-parent-id'], 'uid' => $item['uid']]);
1419 * Distribute the given item to users who subscribed to their tags
1421 * @param array $item Processed item
1423 private static function distributeByTags(array $item)
1425 if (($item['uid'] != 0) || ($item['gravity'] != self::GRAVITY_PARENT) || !in_array($item['network'], Protocol::FEDERATED)) {
1429 $uids = Tag::getUIDListByURIId($item['uri-id']);
1430 foreach ($uids as $uid) {
1431 $stored = self::storeForUserByUriId($item['uri-id'], $uid, ['post-reason' => self::PR_TAG]);
1432 Logger::info('Stored item for users', ['uri-id' => $item['uri-id'], 'uid' => $uid, 'stored' => $stored]);
1437 * Distributes public items to the receivers
1439 * @param integer $itemid Item ID that should be added
1440 * @param string $signed_text Original text (for Diaspora signatures), JSON encoded.
1441 * @throws \Exception
1443 public static function distribute(int $itemid, string $signed_text = '')
1445 $condition = ["`id` IN (SELECT `parent` FROM `post-user-view` WHERE `id` = ?)", $itemid];
1446 $parent = Post::selectFirst(['owner-id'], $condition);
1447 if (!DBA::isResult($parent)) {
1448 Logger::warning('Item not found', ['condition' => $condition]);
1452 // Only distribute public items from native networks
1453 $condition = ['id' => $itemid, 'uid' => 0,
1454 'network' => array_merge(Protocol::FEDERATED ,['']),
1455 'visible' => true, 'deleted' => false, 'private' => [self::PUBLIC, self::UNLISTED]];
1456 $item = Post::selectFirst(array_merge(self::ITEM_FIELDLIST, ['protocol']), $condition);
1457 if (!DBA::isResult($item)) {
1458 Logger::warning('Item not found', ['condition' => $condition]);
1462 $origin = $item['origin'];
1466 /// @todo add a field "pcid" in the contact table that referrs to the public contact id.
1467 $owner = DBA::selectFirst('contact', ['url', 'nurl', 'alias'], ['id' => $parent['owner-id']]);
1468 if (!DBA::isResult($owner)) {
1472 $condition = ['nurl' => $owner['nurl'], 'rel' => [Contact::SHARING, Contact::FRIEND]];
1473 $contacts = DBA::select('contact', ['uid'], $condition);
1474 while ($contact = DBA::fetch($contacts)) {
1475 if ($contact['uid'] == 0) {
1479 $users[$contact['uid']] = $contact['uid'];
1481 DBA::close($contacts);
1483 $condition = ['alias' => $owner['url'], 'rel' => [Contact::SHARING, Contact::FRIEND]];
1484 $contacts = DBA::select('contact', ['uid'], $condition);
1485 while ($contact = DBA::fetch($contacts)) {
1486 if ($contact['uid'] == 0) {
1490 $users[$contact['uid']] = $contact['uid'];
1492 DBA::close($contacts);
1494 if (!empty($owner['alias'])) {
1495 $condition = ['nurl' => Strings::normaliseLink($owner['alias']), 'rel' => [Contact::SHARING, Contact::FRIEND]];
1496 $contacts = DBA::select('contact', ['uid'], $condition);
1497 while ($contact = DBA::fetch($contacts)) {
1498 if ($contact['uid'] == 0) {
1502 $users[$contact['uid']] = $contact['uid'];
1504 DBA::close($contacts);
1509 if ($item['uri-id'] != $item['parent-uri-id']) {
1510 $parents = Post::select(['uid', 'origin'], ["`uri-id` = ? AND `uid` != 0", $item['parent-uri-id']]);
1511 while ($parent = Post::fetch($parents)) {
1512 $users[$parent['uid']] = $parent['uid'];
1513 if ($parent['origin'] && !$origin) {
1514 $origin_uid = $parent['uid'];
1517 DBA::close($parents);
1520 foreach ($users as $uid) {
1521 if ($origin_uid == $uid) {
1522 $item['diaspora_signed_text'] = $signed_text;
1524 $item['post-reason'] = self::PR_DISTRIBUTE;
1525 self::storeForUser($item, $uid);
1530 * Store a public item defined by their URI-ID for the given users
1532 * @param integer $uri_id URI-ID of the given item
1533 * @param integer $uid The user that will receive the item entry
1534 * @param array $fields Additional fields to be stored
1535 * @param integer $source_uid User id of the source post
1536 * @return integer stored item id
1538 public static function storeForUserByUriId(int $uri_id, int $uid, array $fields = [], int $source_uid = 0): int
1540 if ($uid == $source_uid) {
1541 Logger::warning('target UID must not be be equal to the source UID', ['uri-id' => $uri_id, 'uid' => $uid]);
1545 $item = Post::selectFirst(array_merge(self::ITEM_FIELDLIST, ['protocol']), ['uri-id' => $uri_id, 'uid' => $source_uid]);
1546 if (!DBA::isResult($item)) {
1547 Logger::warning('Item could not be fetched', ['uri-id' => $uri_id, 'uid' => $source_uid]);
1551 if (($uid != 0) && ($item['gravity'] == self::GRAVITY_PARENT)) {
1552 $owner = User::getOwnerDataById($uid);
1553 if (($owner['contact-type'] == User::ACCOUNT_TYPE_COMMUNITY) && !Tag::isMentioned($uri_id, $owner['url'])) {
1554 Logger::info('Target user is a forum but is not mentioned here, thread will not be stored', ['uid' => $uid, 'uri-id' => $uri_id]);
1559 if (($source_uid == 0) && (($item['private'] == self::PRIVATE) || !in_array($item['network'], Protocol::FEDERATED))) {
1560 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']]);
1564 $item['post-reason'] = self::PR_STORED;
1566 $item = array_merge($item, $fields);
1568 if (($uid != 0) && Contact::isSharing(($item['gravity'] == Item::GRAVITY_PARENT) ? $item['owner-id'] : $item['author-id'], $uid)) {
1569 $item['post-reason'] = self::PR_FOLLOWER;
1572 $is_reshare = ($item['gravity'] == self::GRAVITY_ACTIVITY) && ($item['verb'] == Activity::ANNOUNCE);
1574 if (($uid != 0) && (($item['gravity'] == self::GRAVITY_PARENT) || $is_reshare) &&
1575 DI::pConfig()->get($uid, 'system', 'accept_only_sharer') == self::COMPLETION_NONE &&
1576 !in_array($item['post-reason'], [self::PR_FOLLOWER, self::PR_TAG, self::PR_TO, self::PR_CC])) {
1577 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']]);
1581 $causer = $item['causer-id'] ?: $item['author-id'];
1583 if (($uri_id != $item['parent-uri-id']) && ($item['gravity'] == self::GRAVITY_COMMENT) && !Post::exists(['uri-id' => $item['parent-uri-id'], 'uid' => $uid])) {
1584 if (!self::fetchParent($item['parent-uri-id'], $uid, $causer)) {
1585 Logger::info('Parent post had not been added', ['uri-id' => $item['parent-uri-id'], 'uid' => $uid, 'causer' => $causer]);
1588 Logger::info('Fetched parent post', ['uri-id' => $item['parent-uri-id'], 'uid' => $uid, 'causer' => $causer]);
1589 } elseif (($uri_id != $item['thr-parent-id']) && $is_reshare && !Post::exists(['uri-id' => $item['thr-parent-id'], 'uid' => $uid])) {
1590 if (!self::fetchParent($item['thr-parent-id'], $uid, $causer)) {
1591 Logger::info('Thread parent had not been added', ['uri-id' => $item['thr-parent-id'], 'uid' => $uid, 'causer' => $causer]);
1594 Logger::info('Fetched thread parent', ['uri-id' => $item['thr-parent-id'], 'uid' => $uid, 'causer' => $causer]);
1597 $stored = self::storeForUser($item, $uid);
1598 Logger::info('Item stored for user', ['uri-id' => $item['uri-id'], 'uid' => $uid, 'causer' => $causer, 'source-uid' => $source_uid, 'stored' => $stored]);
1603 * Fetch the parent with the given uri-id
1605 * @param integer $uri_id
1606 * @param integer $uid
1607 * @param integer $causer
1611 private static function fetchParent(int $uri_id, int $uid, int $causer): int
1613 // Fetch the origin user for the post
1614 $origin_uid = self::GetOriginUidForUriId($uri_id, $uid);
1615 if (is_null($origin_uid)) {
1616 Logger::info('Origin item was not found', ['uid' => $uid, 'uri-id' => $uri_id]);
1620 return self::storeForUserByUriId($uri_id, $uid, ['causer-id' => $causer, 'post-reason' => self::PR_FETCHED], $origin_uid);
1624 * Returns the origin uid of a post if the given user is allowed to see it.
1630 private static function GetOriginUidForUriId(int $uriid, int $uid)
1632 if (Post::exists(['uri-id' => $uriid, 'uid' => $uid])) {
1636 $post = Post::selectFirst(['uid', 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid', 'private'], ['uri-id' => $uriid, 'origin' => true]);
1637 if (!empty($post)) {
1638 if (in_array($post['private'], [Item::PUBLIC, Item::UNLISTED])) {
1639 return $post['uid'];
1642 $pcid = Contact::getPublicIdByUserId($uid);
1647 foreach (Item::enumeratePermissions($post, true) as $receiver) {
1648 if ($receiver == $pcid) {
1649 return $post['uid'];
1656 if (Post::exists(['uri-id' => $uriid, 'uid' => 0])) {
1660 // When the post belongs to a a forum then all forum users are allowed to access it
1661 foreach (Tag::getByURIId($uriid, [Tag::MENTION, Tag::EXCLUSIVE_MENTION]) as $tag) {
1662 if (DBA::exists('contact', ['uid' => $uid, 'nurl' => Strings::normaliseLink($tag['url']), 'contact-type' => Contact::TYPE_COMMUNITY])) {
1663 $target_uid = User::getIdForURL($tag['url']);
1664 if (!empty($target_uid)) {
1674 * Store a public item array for the given users
1676 * @param array $item The item entry that will be stored
1677 * @param integer $uid The user that will receive the item entry
1678 * @return integer stored item id
1679 * @throws \Exception
1681 private static function storeForUser(array $item, int $uid): int
1683 $post = Post::selectFirst(['id'], ['uri-id' => $item['uri-id'], 'uid' => $uid]);
1684 if (!empty($post['id'])) {
1685 if (!empty($item['event-id'])) {
1686 $event_post = Post::selectFirst(['event-id'], ['uri-id' => $item['uri-id'], 'uid' => $uid]);
1687 if (!empty($event_post['event-id'])) {
1688 $event = DBA::selectFirst('event', ['edited', 'start', 'finish', 'summary', 'desc', 'location', 'nofinish', 'adjust'], ['id' => $item['event-id']]);
1689 if (!empty($event)) {
1690 // We aren't using "Event::store" here, since we don't want to trigger any further action
1691 $ret = DBA::update('event', $event, ['id' => $event_post['event-id']]);
1692 Logger::info('Event updated', ['uid' => $uid, 'source-event' => $item['event-id'], 'target-event' => $event_post['event-id'], 'ret' => $ret]);
1696 Logger::info('Item already exists', ['uri-id' => $item['uri-id'], 'uid' => $uid, 'id' => $post['id']]);
1700 // Data from the "post-user" table
1702 unset($item['mention']);
1703 unset($item['starred']);
1704 unset($item['unseen']);
1705 unset($item['psid']);
1706 unset($item['pinned']);
1707 unset($item['ignored']);
1708 unset($item['pubmail']);
1709 unset($item['event-id']);
1710 unset($item['hidden']);
1711 unset($item['notification-type']);
1713 // Data from the "post-delivery-data" table
1714 unset($item['postopts']);
1715 unset($item['inform']);
1717 $item['uid'] = $uid;
1718 $item['origin'] = 0;
1721 $item['contact-id'] = self::contactId($item);
1724 if ($item['gravity'] == self::GRAVITY_PARENT) {
1725 $contact = DBA::selectFirst('contact', [], ['id' => $item['contact-id'], 'self' => false]);
1726 if (DBA::isResult($contact)) {
1727 $notify = self::isRemoteSelf($contact, $item);
1731 $distributed = self::insert($item, $notify);
1733 if (!$distributed) {
1734 Logger::info("Distributed item wasn't stored", ['uri-id' => $item['uri-id'], 'user' => $uid]);
1736 Logger::info('Distributed item was stored', ['uri-id' => $item['uri-id'], 'user' => $uid, 'stored' => $distributed]);
1738 return $distributed;
1742 * Add a shadow entry for a given item id that is a thread starter
1744 * We store every public item entry additionally with the user id "0".
1745 * This is used for the community page and for the search.
1746 * It is planned that in the future we will store public item entries only once.
1748 * @param integer $itemid Item ID that should be added
1749 * @throws \Exception
1751 private static function addShadow(int $itemid)
1753 $fields = ['uid', 'private', 'visible', 'deleted', 'network', 'uri-id'];
1754 $condition = ['id' => $itemid, 'gravity' => self::GRAVITY_PARENT];
1755 $item = Post::selectFirst($fields, $condition);
1757 if (!DBA::isResult($item)) {
1761 // is it already a copy?
1762 if (($itemid == 0) || ($item['uid'] == 0)) {
1766 // Is it a visible public post?
1767 if (!$item["visible"] || $item["deleted"] || ($item["private"] == self::PRIVATE)) {
1771 // is it an entry from a connector? Only add an entry for natively connected networks
1772 if (!in_array($item["network"], array_merge(Protocol::FEDERATED ,['']))) {
1776 if (Post::exists(['uri-id' => $item['uri-id'], 'uid' => 0])) {
1780 $item = Post::selectFirst(array_merge(self::ITEM_FIELDLIST, ['protocol']), ['id' => $itemid]);
1782 if (DBA::isResult($item)) {
1783 // Preparing public shadow (removing user specific data)
1786 unset($item['parent']);
1787 unset($item['wall']);
1788 unset($item['mention']);
1789 unset($item['origin']);
1790 unset($item['starred']);
1791 unset($item['postopts']);
1792 unset($item['inform']);
1793 unset($item['post-reason']);
1794 if ($item['uri-id'] == $item['parent-uri-id']) {
1795 $item['contact-id'] = $item['owner-id'];
1797 $item['contact-id'] = $item['author-id'];
1800 $public_shadow = self::insert($item);
1802 Logger::info('Stored public shadow', ['thread' => $itemid, 'id' => $public_shadow]);
1807 * Add a shadow entry for a given item id that is a comment
1809 * This function does the same like the function above - but for comments
1811 * @param integer $itemid Item ID that should be added
1812 * @throws \Exception
1814 private static function addShadowPost(int $itemid)
1816 $item = Post::selectFirst(array_merge(self::ITEM_FIELDLIST, ['protocol']), ['id' => $itemid]);
1817 if (!DBA::isResult($item)) {
1821 // Is it a toplevel post?
1822 if ($item['gravity'] == self::GRAVITY_PARENT) {
1823 self::addShadow($itemid);
1827 // Is this a shadow entry?
1828 if ($item['uid'] == 0) {
1832 // Is there a shadow parent?
1833 if (!Post::exists(['uri-id' => $item['parent-uri-id'], 'uid' => 0])) {
1837 // Is there already a shadow entry?
1838 if (Post::exists(['uri-id' => $item['uri-id'], 'uid' => 0])) {
1842 // Save "origin" and "parent" state
1843 $origin = $item['origin'];
1844 $parent = $item['parent'];
1846 // Preparing public shadow (removing user specific data)
1849 unset($item['parent']);
1850 unset($item['wall']);
1851 unset($item['mention']);
1852 unset($item['origin']);
1853 unset($item['starred']);
1854 unset($item['postopts']);
1855 unset($item['inform']);
1856 unset($item['post-reason']);
1857 $item['contact-id'] = Contact::getIdForURL($item['author-link']);
1859 $public_shadow = self::insert($item);
1861 Logger::info('Stored public shadow', ['uri-id' => $item['uri-id'], 'id' => $public_shadow]);
1863 // If this was a comment to a Diaspora post we don't get our comment back.
1864 // This means that we have to distribute the comment by ourselves.
1865 if ($origin && Post::exists(['id' => $parent, 'network' => Protocol::DIASPORA])) {
1866 self::distribute($public_shadow);
1871 * Adds a language specification in a "language" element of given $arr.
1872 * Expects "body" element to exist in $arr.
1874 * @param array $item
1875 * @return string detected language
1876 * @throws \Text_LanguageDetect_Exception
1878 private static function getLanguage(array $item): string
1880 if (!empty($item['language'])) {
1881 return $item['language'];
1884 if (!in_array($item['gravity'], [self::GRAVITY_PARENT, self::GRAVITY_COMMENT]) || empty($item['body'])) {
1888 $languages = self::getLanguageArray(trim($item['title'] . "\n" . $item['body']), 3);
1889 if (empty($languages)) {
1893 return json_encode($languages);
1897 * Get a language array from a given text
1899 * @param string $body
1900 * @param integer $count
1903 public static function getLanguageArray(string $body, int $count): array
1905 // Convert attachments to links
1906 $naked_body = BBCode::removeAttachment($body);
1907 if (empty($naked_body)) {
1911 // Remove links and pictures
1912 $naked_body = BBCode::removeLinks($naked_body);
1914 // Convert the title and the body to plain text
1915 $naked_body = BBCode::toPlaintext($naked_body);
1917 // Remove possibly remaining links
1918 $naked_body = preg_replace(Strings::autoLinkRegEx(), '', $naked_body);
1920 if (empty($naked_body)) {
1924 $naked_body = self::getDominantLanguage($naked_body);
1926 $availableLanguages = DI::l10n()->getAvailableLanguages();
1927 // See https://github.com/friendica/friendica/issues/10511
1928 // Persian is manually added to language detection until a persian translation is provided for the interface, at
1929 // which point it will be automatically available through `getAvailableLanguages()` and this should be removed.
1930 $availableLanguages['fa'] = 'fa';
1932 $ld = new Language(array_keys($availableLanguages));
1933 return $ld->detect($naked_body)->limit(0, $count)->close() ?: [];
1937 * Check if latin or non latin are dominant in the body and only return the dominant one
1939 * @param string $body
1942 private static function getDominantLanguage(string $body): string
1946 for ($i = 0; $i < mb_strlen($body); $i++) {
1947 $character = mb_substr($body, $i, 1);
1948 $ord = mb_ord($character);
1950 // We add the most common characters to both strings.
1951 if (($ord <= 64) || ($ord >= 91 && $ord <= 96) || ($ord >= 123 && $ord <= 191) || in_array($ord, [215, 247]) || ($ord >= 697 && $ord <= 735) || ($ord > 65535)) {
1952 $latin .= $character;
1953 $non_latin .= $character;
1954 } elseif ($ord < 768) {
1955 $latin .= $character;
1957 $non_latin .= $character;
1960 return (mb_strlen($latin) > mb_strlen($non_latin)) ? $latin : $non_latin;
1963 public static function getLanguageMessage(array $item): string
1965 $iso639 = new \Matriphe\ISO639\ISO639;
1967 $used_languages = '';
1968 foreach (json_decode($item['language'], true) as $language => $reliability) {
1969 $used_languages .= $iso639->languageByCode1($language) . ' (' . $language . "): " . number_format($reliability, 5) . '\n';
1971 $used_languages = DI::l10n()->t('Detected languages in this post:\n%s', $used_languages);
1972 return $used_languages;
1976 * Creates an unique guid out of a given uri.
1977 * This function is used for messages outside the fediverse (Connector posts, feeds, Mails, ...)
1978 * Posts that are created on this system are using System::createUUID.
1979 * Received ActivityPub posts are using Processor::getGUIDByURL.
1981 * @param string $uri uri of an item entry
1982 * @param string|null $host hostname for the GUID prefix
1983 * @return string Unique guid
1985 public static function guidFromUri(string $uri, string $host = null): string
1987 // Our regular guid routine is using this kind of prefix as well
1988 // We have to avoid that different routines could accidentally create the same value
1989 $parsed = parse_url($uri);
1991 // Remove the scheme to make sure that "https" and "http" doesn't make a difference
1992 unset($parsed['scheme']);
1994 // Glue it together to be able to make a hash from it
1995 $host_id = implode('/', $parsed);
1997 // Use a mixture of several hashes to provide some GUID like experience
1998 return hash('crc32', $host) . '-'. hash('joaat', $host_id) . '-'. hash('fnv164', $host_id);
2002 * generate an unique URI
2004 * @param string $guid An existing GUID (Otherwise it will be generated)
2007 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2009 public static function newURI(string $guid = ''): string
2012 $guid = System::createUUID();
2015 return DI::baseUrl()->get() . '/objects/' . $guid;
2019 * Set "success_update" and "last-item" to the date of the last time we heard from this contact
2021 * This can be used to filter for inactive contacts.
2022 * Only do this for public postings to avoid privacy problems, since poco data is public.
2023 * Don't set this value if it isn't from the owner (could be an author that we don't know)
2025 * @param array $arr Contains the just posted item record
2026 * @throws \Exception
2028 private static function updateContact(array $arr)
2030 // Unarchive the author
2031 $contact = DBA::selectFirst('contact', [], ['id' => $arr["author-id"]]);
2032 if (DBA::isResult($contact)) {
2033 Contact::unmarkForArchival($contact);
2036 // Unarchive the contact if it's not our own contact
2037 $contact = DBA::selectFirst('contact', [], ['id' => $arr["contact-id"], 'self' => false]);
2038 if (DBA::isResult($contact)) {
2039 Contact::unmarkForArchival($contact);
2042 /// @todo On private posts we could obfuscate the date
2043 $update = ($arr['private'] != self::PRIVATE) || in_array($arr['network'], Protocol::FEDERATED);
2045 // Is it a forum? Then we don't care about the rules from above
2046 if (!$update && in_array($arr["network"], [Protocol::ACTIVITYPUB, Protocol::DFRN]) && ($arr["parent-uri-id"] === $arr["uri-id"])) {
2047 if (DBA::exists('contact', ['id' => $arr['contact-id'], 'forum' => true])) {
2053 // The "self" contact id is used (for example in the connectors) when the contact is unknown
2054 // So we have to ensure to only update the last item when it had been our own post,
2055 // or it had been done by a "regular" contact.
2056 if (!empty($arr['wall'])) {
2057 $condition = ['id' => $arr['contact-id']];
2059 $condition = ['id' => $arr['contact-id'], 'self' => false];
2061 Contact::update(['failed' => false, 'local-data' => true, 'success_update' => $arr['received'], 'last-item' => $arr['received']], $condition);
2063 // Now do the same for the system wide contacts with uid=0
2064 if ($arr['private'] != self::PRIVATE) {
2065 Contact::update(['failed' => false, 'local-data' => true, 'success_update' => $arr['received'], 'last-item' => $arr['received']],
2066 ['id' => $arr['owner-id']]);
2068 if ($arr['owner-id'] != $arr['author-id']) {
2069 Contact::update(['failed' => false, 'local-data' => true, 'success_update' => $arr['received'], 'last-item' => $arr['received']],
2070 ['id' => $arr['author-id']]);
2075 public static function setHashtags(string $body): string
2077 $body = BBCode::performWithEscapedTags($body, ['noparse', 'pre', 'code', 'img'], function ($body) {
2078 $tags = BBCode::getTags($body);
2081 if (!count($tags)) {
2085 // This sorting is important when there are hashtags that are part of other hashtags
2086 // Otherwise there could be problems with hashtags like #test and #test2
2087 // Because of this we are sorting from the longest to the shortest tag.
2088 usort($tags, function ($a, $b) {
2089 return strlen($b) <=> strlen($a);
2092 $URLSearchString = "^\[\]";
2094 // All hashtags should point to the home server if "local_tags" is activated
2095 if (DI::config()->get('system', 'local_tags')) {
2096 $body = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
2097 "#[url=" . DI::baseUrl() . "/search?tag=$2]$2[/url]", $body);
2100 // mask hashtags inside of url, bookmarks and attachments to avoid urls in urls
2101 $body = preg_replace_callback("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
2103 return ("[url=" . str_replace("#", "#", $match[1]) . "]" . str_replace("#", "#", $match[2]) . "[/url]");
2106 $body = preg_replace_callback("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism",
2108 return ("[bookmark=" . str_replace("#", "#", $match[1]) . "]" . str_replace("#", "#", $match[2]) . "[/bookmark]");
2111 $body = preg_replace_callback("/\[attachment (.*?)\](.*?)\[\/attachment\]/ism",
2113 return ("[attachment " . str_replace("#", "#", $match[1]) . "]" . $match[2] . "[/attachment]");
2116 // Repair recursive urls
2117 $body = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
2120 foreach ($tags as $tag) {
2121 if ((strpos($tag, '#') !== 0) || strpos($tag, '[url=') || strlen($tag) < 2 || $tag[1] == '#') {
2125 $basetag = str_replace('_', ' ', substr($tag, 1));
2126 $newtag = '#[url=' . DI::baseUrl() . '/search?tag=' . $basetag . ']' . $basetag . '[/url]';
2128 $body = str_replace($tag, $newtag, $body);
2131 // Convert back the masked hashtags
2132 $body = str_replace("#", "#", $body);
2141 * look for mention tags and setup a second delivery chain for forum/community posts if appropriate
2144 * @param int $item_id
2145 * @return boolean true if item was deleted, else false
2146 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2147 * @throws \ImagickException
2149 private static function tagDeliver(int $uid, int $item_id): bool
2153 $owner = User::getOwnerDataById($uid);
2154 if (!DBA::isResult($owner)) {
2155 Logger::warning('User not found, quitting here.', ['uid' => $uid]);
2159 if ($owner['contact-type'] != User::ACCOUNT_TYPE_COMMUNITY) {
2160 Logger::debug('Owner is no community, quitting here.', ['uid' => $uid, 'id' => $item_id]);
2164 $item = Post::selectFirst(self::ITEM_FIELDLIST, ['id' => $item_id, 'gravity' => [self::GRAVITY_PARENT, self::GRAVITY_COMMENT], 'origin' => false]);
2165 if (!DBA::isResult($item)) {
2166 Logger::debug('Post is an activity or origin or not found at all, quitting here.', ['id' => $item_id]);
2170 if ($item['gravity'] == self::GRAVITY_PARENT) {
2171 if (Tag::isMentioned($item['uri-id'], $owner['url'])) {
2172 Logger::info('Mention found in tag.', ['uri' => $item['uri'], 'uid' => $uid, 'id' => $item_id, 'uri-id' => $item['uri-id'], 'guid' => $item['guid']]);
2174 Logger::info('Top-level post without mention is deleted.', ['uri' => $item['uri'], $uid, 'id' => $item_id, 'uri-id' => $item['uri-id'], 'guid' => $item['guid']]);
2175 Post\User::delete(['uri-id' => $item['uri-id'], 'uid' => $item['uid']]);
2179 $arr = ['item' => $item, 'user' => $owner];
2181 Hook::callAll('tagged', $arr);
2183 if (Tag::isMentioned($item['parent-uri-id'], $owner['url'])) {
2184 Logger::info('Mention found in parent tag.', ['uri' => $item['uri'], 'uid' => $uid, 'id' => $item_id, 'uri-id' => $item['uri-id'], 'guid' => $item['guid']]);
2186 Logger::debug('No mentions found in parent, quitting here.', ['id' => $item_id, 'uri-id' => $item['uri-id'], 'guid' => $item['guid']]);
2191 Logger::info('Community post will be distributed', ['uri' => $item['uri'], 'uid' => $uid, 'id' => $item_id, 'uri-id' => $item['uri-id'], 'guid' => $item['guid']]);
2193 if ($owner['page-flags'] == User::PAGE_FLAGS_PRVGROUP) {
2195 $allow_gid = '<' . Group::FOLLOWERS . '>';
2198 self::performActivity($item['id'], 'announce', $uid, $allow_cid, $allow_gid, $deny_cid, $deny_gid);
2200 self::performActivity($item['id'], 'announce', $uid);
2203 Logger::info('Community post had been distributed', ['uri' => $item['uri'], 'uid' => $uid, 'id' => $item_id, 'uri-id' => $item['uri-id'], 'guid' => $item['guid']]);
2208 * Automatically reshare the item if the "remote_self" option is selected
2210 * @param array $item
2213 private static function autoReshare(array $item)
2215 if ($item['gravity'] != self::GRAVITY_PARENT) {
2219 if (!DBA::exists('contact', ['id' => $item['contact-id'], 'remote_self' => Contact::MIRROR_NATIVE_RESHARE])) {
2223 if (!in_array($item['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN])) {
2227 Logger::info('Automatically reshare item', ['uid' => $item['uid'], 'id' => $item['id'], 'guid' => $item['guid'], 'uri-id' => $item['uri-id']]);
2229 self::performActivity($item['id'], 'announce', $item['uid']);
2232 public static function isRemoteSelf(array $contact, array &$datarray): bool
2234 if (!$contact['remote_self']) {
2238 // Prevent the forwarding of posts that are forwarded
2239 if (!empty($datarray["extid"]) && ($datarray["extid"] == Protocol::DFRN)) {
2240 Logger::info('Already forwarded');
2244 // Prevent to forward already forwarded posts
2245 if ($datarray["app"] == DI::baseUrl()->getHostname()) {
2246 Logger::info('Already forwarded (second test)');
2250 // Only forward posts
2251 if ($datarray["verb"] != Activity::POST) {
2252 Logger::info('No post');
2256 if (($contact['network'] != Protocol::FEED) && ($datarray['private'] == self::PRIVATE)) {
2257 Logger::info('Not public');
2261 $datarray2 = $datarray;
2262 Logger::info('remote-self start', ['contact' => $contact['url'], 'remote_self'=> $contact['remote_self'], 'item' => $datarray]);
2263 if ($contact['remote_self'] == Contact::MIRROR_OWN_POST) {
2264 $self = DBA::selectFirst('contact', ['id', 'name', 'url', 'thumb'],
2265 ['uid' => $contact['uid'], 'self' => true]);
2266 if (DBA::isResult($self)) {
2267 $datarray['contact-id'] = $self["id"];
2269 $datarray['owner-name'] = $self["name"];
2270 $datarray['owner-link'] = $self["url"];
2271 $datarray['owner-avatar'] = $self["thumb"];
2273 $datarray['author-name'] = $datarray['owner-name'];
2274 $datarray['author-link'] = $datarray['owner-link'];
2275 $datarray['author-avatar'] = $datarray['owner-avatar'];
2277 unset($datarray['edited']);
2279 unset($datarray['network']);
2280 unset($datarray['owner-id']);
2281 unset($datarray['author-id']);
2284 if ($contact['network'] != Protocol::FEED) {
2285 $old_uri_id = $datarray["uri-id"] ?? 0;
2286 $datarray["guid"] = System::createUUID();
2287 unset($datarray["plink"]);
2288 $datarray["uri"] = self::newURI($datarray["guid"]);
2289 $datarray["uri-id"] = ItemURI::getIdByURI($datarray["uri"]);
2290 $datarray["extid"] = Protocol::DFRN;
2291 $urlpart = parse_url($datarray2['author-link']);
2292 $datarray["app"] = $urlpart["host"];
2293 if (!empty($old_uri_id)) {
2294 Post\Media::copy($old_uri_id, $datarray["uri-id"]);
2297 unset($datarray["parent-uri"]);
2298 unset($datarray["thr-parent"]);
2300 $datarray['private'] = self::PUBLIC;
2304 if ($contact['network'] != Protocol::FEED) {
2305 // Store the original post
2306 $result = self::insert($datarray2);
2307 Logger::info('remote-self post original item', ['contact' => $contact['url'], 'result'=> $result, 'item' => $datarray2]);
2309 $datarray["app"] = "Feed";
2313 return (bool)$result;
2320 * @param array $item
2323 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2324 * @throws \ImagickException
2326 public static function fixPrivatePhotos(string $s, int $uid, array $item = null, int $cid = 0): string
2328 if (DI::config()->get('system', 'disable_embedded')) {
2332 Logger::info('check for photos');
2333 $site = substr(DI::baseUrl(), strpos(DI::baseUrl(), '://'));
2338 $img_start = strpos($orig_body, '[img');
2339 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
2340 $img_len = ($img_start !== false ? strpos(substr($orig_body, $img_start + $img_st_close + 1), '[/img]') : false);
2342 while (($img_st_close !== false) && ($img_len !== false)) {
2343 $img_st_close++; // make it point to AFTER the closing bracket
2344 $image = substr($orig_body, $img_start + $img_st_close, $img_len);
2346 Logger::info('found photo', ['image' => $image]);
2348 if (stristr($image, $site . '/photo/')) {
2349 // Only embed locally hosted photos
2351 $i = basename($image);
2352 $i = str_replace(['.jpg', '.png', '.gif'], ['', '', ''], $i);
2353 $x = strpos($i, '-');
2356 $res = substr($i, $x + 1);
2357 $i = substr($i, 0, $x);
2358 $photo = Photo::getPhotoForUser($uid, $i, $res);
2359 if (DBA::isResult($photo)) {
2361 * Check to see if we should replace this photo link with an embedded image
2362 * 1. No need to do so if the photo is public
2363 * 2. If there's a contact-id provided, see if they're in the access list
2364 * for the photo. If so, embed it.
2365 * 3. Otherwise, if we have an item, see if the item permissions match the photo
2366 * permissions, regardless of order but first check to see if they're an exact
2367 * match to save some processing overhead.
2369 if (self::hasPermissions($photo)) {
2371 $recips = self::enumeratePermissions($photo);
2372 if (in_array($cid, $recips)) {
2376 if (self::samePermissions($uid, $item, $photo)) {
2382 $photo_img = Photo::getImageForPhoto($photo);
2383 // If a custom width and height were specified, apply before embedding
2384 if (preg_match("/\[img\=([0-9]*)x([0-9]*)\]/is", substr($orig_body, $img_start, $img_st_close), $match)) {
2385 Logger::info('scaling photo');
2387 $width = intval($match[1]);
2388 $height = intval($match[2]);
2390 $photo_img->scaleDown(max($width, $height));
2393 $data = $photo_img->asString();
2394 $type = $photo_img->getType();
2396 Logger::info('replacing photo');
2397 $image = 'data:' . $type . ';base64,' . base64_encode($data);
2398 Logger::debug('replaced', ['image' => $image]);
2404 $new_body = $new_body . substr($orig_body, 0, $img_start + $img_st_close) . $image . '[/img]';
2405 $orig_body = substr($orig_body, $img_start + $img_st_close + $img_len + strlen('[/img]'));
2406 if ($orig_body === false) {
2410 $img_start = strpos($orig_body, '[img');
2411 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
2412 $img_len = ($img_start !== false ? strpos(substr($orig_body, $img_start + $img_st_close + 1), '[/img]') : false);
2415 $new_body = $new_body . $orig_body;
2420 private static function hasPermissions(array $obj)
2422 return !empty($obj['allow_cid']) || !empty($obj['allow_gid']) ||
2423 !empty($obj['deny_cid']) || !empty($obj['deny_gid']);
2426 // @TODO $uid is unused parameter
2427 private static function samePermissions($uid, array $obj1, array $obj2): bool
2429 // first part is easy. Check that these are exactly the same.
2430 if (($obj1['allow_cid'] == $obj2['allow_cid'])
2431 && ($obj1['allow_gid'] == $obj2['allow_gid'])
2432 && ($obj1['deny_cid'] == $obj2['deny_cid'])
2433 && ($obj1['deny_gid'] == $obj2['deny_gid'])) {
2437 // This is harder. Parse all the permissions and compare the resulting set.
2438 $recipients1 = self::enumeratePermissions($obj1);
2439 $recipients2 = self::enumeratePermissions($obj2);
2443 /// @TODO Comparison of arrays, maybe use array_diff_assoc() here?
2444 return ($recipients1 == $recipients2);
2448 * Returns an array of contact-ids that are allowed to see this object
2450 * @param array $obj Item array with at least uid, allow_cid, allow_gid, deny_cid and deny_gid
2451 * @param bool $check_dead Prunes unavailable contacts from the result
2453 * @throws \Exception
2455 public static function enumeratePermissions(array $obj, bool $check_dead = false): array
2457 $aclFormater = DI::aclFormatter();
2459 $allow_people = $aclFormater->expand($obj['allow_cid']);
2460 $allow_groups = Group::expand($obj['uid'], $aclFormater->expand($obj['allow_gid']), $check_dead);
2461 $deny_people = $aclFormater->expand($obj['deny_cid']);
2462 $deny_groups = Group::expand($obj['uid'], $aclFormater->expand($obj['deny_gid']), $check_dead);
2463 $recipients = array_unique(array_merge($allow_people, $allow_groups));
2464 $deny = array_unique(array_merge($deny_people, $deny_groups));
2465 $recipients = array_diff($recipients, $deny);
2469 public static function expire(int $uid, int $days, string $network = "", bool $force = false)
2471 if (!$uid || ($days < 1)) {
2475 $condition = ["`uid` = ? AND NOT `deleted` AND `gravity` = ?",
2476 $uid, self::GRAVITY_PARENT];
2479 * $expire_network_only = save your own wall posts
2480 * and just expire conversations started by others
2482 $expire_network_only = DI::pConfig()->get($uid, 'expire', 'network_only', false);
2484 if ($expire_network_only) {
2485 $condition[0] .= " AND NOT `wall`";
2488 if ($network != "") {
2489 $condition[0] .= " AND `network` = ?";
2490 $condition[] = $network;
2493 $condition[0] .= " AND `received` < ?";
2494 $condition[] = DateTimeFormat::utc('now - ' . $days . ' day');
2496 $items = Post::select(['resource-id', 'starred', 'id', 'post-type', 'uid', 'uri-id'], $condition);
2498 if (!DBA::isResult($items)) {
2502 $expire_items = (bool)DI::pConfig()->get($uid, 'expire', 'items', true);
2504 // Forcing expiring of items - but not notes and marked items
2506 $expire_items = true;
2509 $expire_notes = (bool)DI::pConfig()->get($uid, 'expire', 'notes', true);
2510 $expire_starred = (bool)DI::pConfig()->get($uid, 'expire', 'starred', true);
2511 $expire_photos = (bool)DI::pConfig()->get($uid, 'expire', 'photos', false);
2515 $priority = DI::config()->get('system', 'expire-notify-priority');
2517 while ($item = Post::fetch($items)) {
2518 // don't expire filed items
2519 if (DBA::exists('post-category', ['uri-id' => $item['uri-id'], 'uid' => $item['uid'], 'type' => Post\Category::FILE])) {
2523 // Only expire posts, not photos and photo comments
2525 if (!$expire_photos && !empty($item['resource-id'])) {
2527 } elseif (!$expire_starred && intval($item['starred'])) {
2529 } elseif (!$expire_notes && ($item['post-type'] == self::PT_PERSONAL_NOTE)) {
2531 } elseif (!$expire_items && ($item['post-type'] != self::PT_PERSONAL_NOTE)) {
2535 self::markForDeletionById($item['id'], $priority);
2540 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]);
2543 public static function firstPostDate(int $uid, bool $wall = false)
2545 $user = User::getById($uid, ['register_date']);
2550 $condition = ["`uid` = ? AND `wall` = ? AND NOT `deleted` AND `visible` AND `received` >= ?",
2551 $uid, $wall, $user['register_date']];
2552 $params = ['order' => ['received' => false]];
2553 $thread = Post::selectFirstThread(['received'], $condition, $params);
2554 if (DBA::isResult($thread)) {
2555 $postdate = substr(DateTimeFormat::local($thread['received']), 0, 10);
2562 * add/remove activity to an item
2564 * Toggle activities as like,dislike,attend of an item
2566 * @param int $item_id
2567 * @param string $verb
2568 * Activity verb. One of
2569 * like, unlike, dislike, undislike, attendyes, unattendyes,
2570 * attendno, unattendno, attendmaybe, unattendmaybe,
2571 * announce, unannouce
2573 * @param string $allow_cid
2574 * @param string $allow_gid
2575 * @param string $deny_cid
2576 * @param string $deny_gid
2578 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2579 * @throws \ImagickException
2580 * @hook 'post_local_end'
2582 * 'post_id' => ID of posted item
2584 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
2590 Logger::notice('Start create activity', ['verb' => $verb, 'item' => $item_id, 'user' => $uid]);
2592 $item = Post::selectFirst(self::ITEM_FIELDLIST, ['id' => $item_id]);
2593 if (!DBA::isResult($item)) {
2594 Logger::warning('Post had not been fetched', ['id' => $item_id]);
2598 $uri_id = $item['uri-id'];
2600 if (!in_array($item['uid'], [0, $uid])) {
2604 if (!Post::exists(['uri-id' => $item['parent-uri-id'], 'uid' => $uid])) {
2605 $stored = self::storeForUserByUriId($item['parent-uri-id'], $uid, ['post-reason' => Item::PR_ACTIVITY]);
2606 if (($item['parent-uri-id'] == $item['uri-id']) && !empty($stored)) {
2607 $item = Post::selectFirst(self::ITEM_FIELDLIST, ['id' => $stored]);
2608 if (!DBA::isResult($item)) {
2609 Logger::info('Could not fetch just created item - should not happen', ['stored' => $stored, 'uid' => $uid, 'uri-id' => $uri_id]);
2615 // Retrieves the local post owner
2616 $owner = User::getOwnerDataById($uid);
2617 if (empty($owner)) {
2618 Logger::info('Empty owner for user', ['uid' => $uid]);
2622 // Retrieve the current logged in user's public contact
2623 $author_id = Contact::getPublicIdByUserId($uid);
2624 if (empty($author_id)) {
2625 Logger::info('Empty public contact');
2633 $activity = Activity::LIKE;
2637 $activity = Activity::DISLIKE;
2641 $activity = Activity::ATTEND;
2645 $activity = Activity::ATTENDNO;
2648 case 'unattendmaybe':
2649 $activity = Activity::ATTENDMAYBE;
2653 $activity = Activity::FOLLOW;
2657 $activity = Activity::ANNOUNCE;
2660 Logger::warning('unknown verb', ['verb' => $verb, 'item' => $item_id]);
2664 $mode = Strings::startsWith($verb, 'un') ? 'delete' : 'create';
2666 // Enable activity toggling instead of on/off
2667 $event_verb_flag = $activity === Activity::ATTEND || $activity === Activity::ATTENDNO || $activity === Activity::ATTENDMAYBE;
2669 // Look for an existing verb row
2670 // Event participation activities are mutually exclusive, only one of them can exist at all times.
2671 if ($event_verb_flag) {
2672 $verbs = [Activity::ATTEND, Activity::ATTENDNO, Activity::ATTENDMAYBE];
2674 // Translate to the index based activity index
2676 foreach ($verbs as $verb) {
2677 $vids[] = Verb::getID($verb);
2680 $vids = Verb::getID($activity);
2683 $condition = ['vid' => $vids, 'deleted' => false, 'gravity' => self::GRAVITY_ACTIVITY,
2684 'author-id' => $author_id, 'uid' => $item['uid'], 'thr-parent-id' => $uri_id];
2685 $like_item = Post::selectFirst(['id', 'guid', 'verb'], $condition);
2687 if (DBA::isResult($like_item)) {
2689 * Truth table for existing activities
2691 * | Inputs || Outputs |
2692 * |----------------------------||-------------------|
2693 * | Mode | Event | Same verb || Delete? | Return? |
2694 * |--------|-------|-----------||---------|---------|
2695 * | create | Yes | Yes || No | Yes |
2696 * | create | Yes | No || Yes | No |
2697 * | create | No | Yes || No | Yes |
2698 * | create | No | No || N/A†|
2699 * | delete | Yes | Yes || Yes | N/A‡ |
2700 * | delete | Yes | No || No | N/A‡ |
2701 * | delete | No | Yes || Yes | N/A‡ |
2702 * | delete | No | No || N/A†|
2703 * |--------|-------|-----------||---------|---------|
2704 * | A | B | C || A xor C | !B or C |
2706 * †Can't happen: It's impossible to find an existing non-event activity without
2707 * the same verb because we are only looking for this single verb.
2709 * ‡ The "mode = delete" is returning early whether an existing activity was found or not.
2711 if ($mode == 'create' xor $like_item['verb'] == $activity) {
2712 self::markForDeletionById($like_item['id']);
2715 if (!$event_verb_flag || $like_item['verb'] == $activity) {
2720 // No need to go further if we aren't creating anything
2721 if ($mode == 'delete') {
2725 $objtype = $item['resource-id'] ? Activity\ObjectType::IMAGE : Activity\ObjectType::NOTE;
2728 'guid' => System::createUUID(),
2729 'uri' => self::newURI(),
2731 'contact-id' => $owner['id'],
2732 'wall' => $item['wall'],
2734 'network' => Protocol::DFRN,
2735 'protocol' => Conversation::PARCEL_DIRECT,
2736 'direction' => Conversation::PUSH,
2737 'gravity' => self::GRAVITY_ACTIVITY,
2738 'parent' => $item['id'],
2739 'thr-parent' => $item['uri'],
2740 'owner-id' => $author_id,
2741 'author-id' => $author_id,
2742 'body' => $activity,
2743 'verb' => $activity,
2744 'object-type' => $objtype,
2745 'allow_cid' => $allow_cid ?? $item['allow_cid'],
2746 'allow_gid' => $allow_gid ?? $item['allow_gid'],
2747 'deny_cid' => $deny_cid ?? $item['deny_cid'],
2748 'deny_gid' => $deny_gid ?? $item['deny_gid'],
2753 if (in_array($activity, [Activity::LIKE, Activity::DISLIKE])) {
2754 $signed = Diaspora::createLikeSignature($uid, $new_item);
2755 if (!empty($signed)) {
2756 $new_item['diaspora_signed_text'] = json_encode($signed);
2760 self::insert($new_item, true);
2762 // If the parent item isn't visible then set it to visible
2763 // @todo Check if this is still needed
2764 if (!$item['visible']) {
2765 self::update(['visible' => true], ['id' => $item['id']]);
2771 * Fetch the SQL condition for the given user id
2773 * @param integer $owner_id User ID for which the permissions should be fetched
2774 * @return array condition
2776 public static function getPermissionsConditionArrayByUserId(int $owner_id): array
2778 $local_user = DI::userSession()->getLocalUserId();
2779 $remote_user = DI::userSession()->getRemoteContactID($owner_id);
2781 // default permissions - anonymous user
2782 $condition = ["`private` != ?", self::PRIVATE];
2784 if ($local_user && ($local_user == $owner_id)) {
2785 // Profile owner - everything is visible
2787 } elseif ($remote_user) {
2788 // Authenticated visitor - fetch the matching permissionsets
2789 $permissionSets = DI::permissionSet()->selectByContactId($remote_user, $owner_id);
2791 $condition = ["(`private` != ? OR (`private` = ? AND `wall`
2792 AND `psid` IN (" . implode(', ', array_fill(0, count($set), '?')) . ")))",
2793 self::PRIVATE, self::PRIVATE];
2794 $condition = array_merge($condition, $permissionSets->column('id'));
2802 * Get a permission SQL string for the given user
2804 * @param int $owner_id
2805 * @param string $table
2808 public static function getPermissionsSQLByUserId(int $owner_id, string $table = ''): string
2810 $local_user = DI::userSession()->getLocalUserId();
2811 $remote_user = DI::userSession()->getRemoteContactID($owner_id);
2813 if (!empty($table)) {
2814 $table = DBA::quoteIdentifier($table) . '.';
2818 * Construct permissions
2820 * default permissions - anonymous user
2822 $sql = sprintf(" AND " . $table . "`private` != %d", self::PRIVATE);
2824 // Profile owner - everything is visible
2825 if ($local_user && ($local_user == $owner_id)) {
2827 } elseif ($remote_user) {
2829 * Authenticated visitor. Unless pre-verified,
2830 * check that the contact belongs to this $owner_id
2831 * and load the groups the visitor belongs to.
2832 * If pre-verified, the caller is expected to have already
2833 * done this and passed the groups into this function.
2835 $permissionSets = DI::permissionSet()->selectByContactId($remote_user, $owner_id);
2838 $sql_set = sprintf(" OR (" . $table . "`private` = %d AND " . $table . "`wall` AND " . $table . "`psid` IN (", self::PRIVATE) . implode(',', $permissionSets->column('id')) . "))";
2843 $sql = sprintf(" AND (" . $table . "`private` != %d", self::PRIVATE) . $sql_set . ")";
2850 * get translated item type
2852 * @param array $item
2853 * @param \Friendica\Core\L10n $l10n
2856 public static function postType(array $item, \Friendica\Core\L10n $l10n): string
2858 if (!empty($item['event-id'])) {
2859 return $l10n->t('event');
2860 } elseif (!empty($item['resource-id'])) {
2861 return $l10n->t('photo');
2862 } elseif ($item['gravity'] == self::GRAVITY_ACTIVITY) {
2863 return $l10n->t('activity');
2864 } elseif ($item['gravity'] == self::GRAVITY_COMMENT) {
2865 return $l10n->t('comment');
2868 return $l10n->t('post');
2872 * Sets the "rendered-html" field of the provided item
2874 * Body is preserved to avoid side-effects as we modify it just-in-time for spoilers and private image links
2876 * @param array $item
2878 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2879 * @todo Remove reference, simply return "rendered-html" and "rendered-hash"
2881 private static function putInCache(&$item)
2883 // Save original body to prevent addons to modify it
2884 $body = $item['body'];
2886 $rendered_hash = $item['rendered-hash'] ?? '';
2887 $rendered_html = $item['rendered-html'] ?? '';
2889 if ($rendered_hash == ''
2890 || $rendered_html == ''
2891 || $rendered_hash != hash('md5', BBCode::VERSION . '::' . $body)
2892 || DI::config()->get('system', 'ignore_cache')
2894 $item['rendered-html'] = BBCode::convertForUriId($item['uri-id'], $item['body']);
2895 $item['rendered-hash'] = hash('md5', BBCode::VERSION . '::' . $body);
2897 $hook_data = ['item' => $item, 'rendered-html' => $item['rendered-html'], 'rendered-hash' => $item['rendered-hash']];
2898 Hook::callAll('put_item_in_cache', $hook_data);
2899 $item['rendered-html'] = $hook_data['rendered-html'];
2900 $item['rendered-hash'] = $hook_data['rendered-hash'];
2903 // Update if the generated values differ from the existing ones
2904 if ((($rendered_hash != $item['rendered-hash']) || ($rendered_html != $item['rendered-html'])) && !empty($item['id'])) {
2907 'rendered-html' => $item['rendered-html'],
2908 'rendered-hash' => $item['rendered-hash']
2910 ['id' => $item['id']]
2915 $item['body'] = $body;
2919 * Given an item array, convert the body element from bbcode to html and add smilie icons.
2920 * If attach is true, also add icons for item attachments.
2922 * @param array $item Record from item table
2923 * @param boolean $attach If true, add icons for item attachments as well
2924 * @param boolean $is_preview Whether this is a preview
2925 * @param boolean $only_cache Whether only cached HTML should be updated
2926 * @return string item body html
2927 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2928 * @throws \ImagickException
2929 * @hook prepare_body_init item array before any work
2930 * @hook prepare_body_content_filter ('item'=>item array, 'filter_reasons'=>string array) before first bbcode to html
2931 * @hook prepare_body ('item'=>item array, 'html'=>body string, 'is_preview'=>boolean, 'filter_reasons'=>string array) after first bbcode to html
2932 * @hook prepare_body_final ('item'=>item array, 'html'=>body string) after attach icons and blockquote special case handling (spoiler, author)
2934 public static function prepareBody(array &$item, bool $attach = false, bool $is_preview = false, bool $only_cache = false): string
2937 Hook::callAll('prepare_body_init', $item);
2939 // In order to provide theme developers more possibilities, event items
2940 // are treated differently.
2941 if ($item['object-type'] === Activity\ObjectType::EVENT && isset($item['event-id'])) {
2942 $ev = Event::getItemHTML($item);
2946 $tags = Tag::populateFromItem($item);
2948 $item['tags'] = $tags['tags'];
2949 $item['hashtags'] = $tags['hashtags'];
2950 $item['mentions'] = $tags['mentions'];
2952 $body = $item['body'] ?? '';
2954 $fields = ['uri-id', 'uri', 'body', 'title', 'author-name', 'author-link', 'author-avatar', 'guid', 'created', 'plink', 'network', 'has-media'];
2959 $shared = DI::contentItem()->getSharedPost($item, $fields);
2960 if (!empty($shared['post'])) {
2961 $shared_item = $shared['post'];
2962 $quote_uri_id = $shared['post']['uri-id'];
2963 $shared_links[] = strtolower($shared['post']['uri']);
2964 $item['body'] = BBCode::removeSharedData($item['body']);
2965 } elseif (empty($shared_item['uri-id']) && empty($item['quote-uri-id'])) {
2966 $media = Post\Media::getByURIId($item['uri-id'], [Post\Media::ACTIVITY]);
2967 if (!empty($media)) {
2968 $shared_item = Post::selectFirst($fields, ['plink' => $media[0]['url'], 'uid' => [$item['uid'], 0]]);
2970 if (empty($shared_item['uri-id'])) {
2971 $shared_item = Post::selectFirst($fields, ['uri' => $media[0]['url'], 'uid' => [$item['uid'], 0]]);
2972 $shared_links[] = strtolower($media[0]['url']);
2975 $quote_uri_id = $shared_item['uri-id'] ?? 0;
2979 if (!empty($quote_uri_id)) {
2980 $item['body'] .= "\n" . DI::contentItem()->createSharedBlockByArray($shared_item);
2983 if (!empty($shared_item['uri-id'])) {
2984 $shared_uri_id = $shared_item['uri-id'];
2985 $shared_links[] = strtolower($shared_item['plink']);
2986 $shared_attachments = Post\Media::splitAttachments($shared_uri_id, $shared_item['guid'], [], $shared_item['has-media']);
2987 $shared_links = array_merge($shared_links, array_column($shared_attachments['visual'], 'url'));
2988 $shared_links = array_merge($shared_links, array_column($shared_attachments['link'], 'url'));
2989 $shared_links = array_merge($shared_links, array_column($shared_attachments['additional'], 'url'));
2990 $item['body'] = self::replaceVisualAttachments($shared_attachments, $item['body']);
2993 $attachments = Post\Media::splitAttachments($item['uri-id'], $item['guid'] ?? '', $shared_links, $item['has-media'] ?? false);
2994 $item['body'] = self::replaceVisualAttachments($attachments, $item['body'] ?? '');
2996 $item['body'] = preg_replace("/\s*\[attachment .*?\].*?\[\/attachment\]\s*/ism", "\n", $item['body']);
2997 self::putInCache($item);
2998 $item['body'] = $body;
2999 $s = $item["rendered-html"];
3005 // Compile eventual content filter reasons
3006 $filter_reasons = [];
3007 if (!$is_preview && DI::userSession()->getPublicContactId() != $item['author-id']) {
3008 if (!empty($item['content-warning']) && (!DI::userSession()->getLocalUserId() || !DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'system', 'disable_cw', false))) {
3009 $filter_reasons[] = DI::l10n()->t('Content warning: %s', $item['content-warning']);
3012 $item['attachments'] = $attachments;
3016 'filter_reasons' => $filter_reasons
3018 Hook::callAll('prepare_body_content_filter', $hook_data);
3019 $filter_reasons = $hook_data['filter_reasons'];
3026 'preview' => $is_preview,
3027 'filter_reasons' => $filter_reasons
3029 Hook::callAll('prepare_body', $hook_data);
3030 $s = $hook_data['html'];
3034 // Replace the blockquotes with quotes that are used in mails.
3035 $mailquote = '<blockquote type="cite" class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex;">';
3036 $s = str_replace(['<blockquote>', '<blockquote class="spoiler">', '<blockquote class="author">'], [$mailquote, $mailquote, $mailquote], $s);
3040 if (!empty($shared_attachments)) {
3041 $s = self::addVisualAttachments($shared_attachments, $item, $s, true);
3042 $s = self::addLinkAttachment($shared_uri_id ?: $item['uri-id'], $shared_attachments, $body, $s, true, []);
3043 $s = self::addNonVisualAttachments($shared_attachments, $item, $s, true);
3044 $body = BBCode::removeSharedData($body);
3047 $s = self::addVisualAttachments($attachments, $item, $s, false);
3048 $s = self::addLinkAttachment($item['uri-id'], $attachments, $body, $s, false, $shared_links);
3049 $s = self::addNonVisualAttachments($attachments, $item, $s, false);
3050 $s = self::addQuestions($item, $s);
3053 if (strpos($s, '<div class="map">') !== false && !empty($item['coord'])) {
3054 $x = Map::byCoordinates(trim($item['coord']));
3056 $s = preg_replace('/\<div class\=\"map\"\>/', '$0' . $x, $s);
3060 // Replace friendica image url size with theme preference.
3061 if (!empty($a->getThemeInfoValue('item_image_size'))) {
3062 $ps = $a->getThemeInfoValue('item_image_size');
3063 $s = preg_replace('|(<img[^>]+src="[^"]+/photo/[0-9a-f]+)-[0-9]|', "$1-" . $ps, $s);
3066 $s = HTML::applyContentFilter($s, $filter_reasons);
3068 $hook_data = ['item' => $item, 'html' => $s];
3069 Hook::callAll('prepare_body_final', $hook_data);
3071 return $hook_data['html'];
3075 * Check if the body contains a link
3077 * @param string $body
3078 * @param string $url
3082 public static function containsLink(string $body, string $url, int $type = 0): bool
3084 // Make sure that for example site parameters aren't used when testing if the link is contained in the body
3085 $urlparts = parse_url($url);
3086 if (!empty($urlparts)) {
3087 unset($urlparts['query']);
3088 unset($urlparts['fragment']);
3089 $url = (string)Uri::fromParts($urlparts);
3094 // Remove media links to only search in embedded content
3095 // @todo Check images for image link, audio for audio links, ...
3096 if (in_array($type, [Post\Media::AUDIO, Post\Media::VIDEO, Post\Media::IMAGE])) {
3097 $body = preg_replace("/\[url=[^\[\]]*\](.*)\[\/url\]/Usi", ' $1 ', $body);
3100 if (strpos($body, $url)) {
3103 foreach ([0, 1, 2] as $size) {
3104 if (preg_match('#/photo/.*-' . $size . '\.#ism', $url) &&
3105 strpos(preg_replace('#(/photo/.*)-[012]\.#ism', '$1-' . $size . '.', $body), $url)) {
3113 * Replace visual attachments in the body
3115 * @param array $attachments
3116 * @param string $body
3117 * @return string modified body
3119 private static function replaceVisualAttachments(array $attachments, string $body): string
3121 DI::profiler()->startRecording('rendering');
3123 foreach ($attachments['visual'] as $attachment) {
3124 if (!empty($attachment['preview'])) {
3125 $proxy = Post\Media::getPreviewUrlForId($attachment['id'], Proxy::SIZE_LARGE);
3126 $search = ['[img=' . $attachment['preview'] . ']', ']' . $attachment['preview'] . '[/img]'];
3127 $replace = ['[img=' . $proxy . ']', ']' . $proxy . '[/img]'];
3129 $body = str_replace($search, $replace, $body);
3130 } elseif ($attachment['filetype'] == 'image') {
3131 $proxy = Post\Media::getUrlForId($attachment['id']);
3132 $search = ['[img=' . $attachment['url'] . ']', ']' . $attachment['url'] . '[/img]'];
3133 $replace = ['[img=' . $proxy . ']', ']' . $proxy . '[/img]'];
3135 $body = str_replace($search, $replace, $body);
3138 DI::profiler()->stopRecording();
3143 * Add visual attachments to the content
3145 * @param array $attachments
3146 * @param array $item
3147 * @param string $content
3148 * @return string modified content
3150 private static function addVisualAttachments(array $attachments, array $item, string $content, bool $shared): string
3152 DI::profiler()->startRecording('rendering');
3156 // @todo In the future we should make a single for the template engine with all media in it. This allows more flexibilty.
3157 foreach ($attachments['visual'] as $attachment) {
3158 if (self::containsLink($item['body'], $attachment['preview'] ?? $attachment['url'], $attachment['type'])) {
3162 if (!empty($attachment['preview'])) {
3163 $preview_url = Post\Media::getPreviewUrlForId($attachment['id'], Proxy::SIZE_LARGE);
3168 if (($attachment['filetype'] == 'video')) {
3169 /// @todo Move the template to /content as well
3170 $media = Renderer::replaceMacros(Renderer::getMarkupTemplate('video_top.tpl'), [
3172 'id' => $attachment['id'],
3173 'src' => $attachment['url'],
3174 'name' => $attachment['name'] ?: $attachment['url'],
3175 'preview' => $preview_url,
3176 'mime' => $attachment['mimetype'],
3179 if (($item['post-type'] ?? null) == Item::PT_VIDEO) {
3182 $trailing .= $media;
3184 } elseif ($attachment['filetype'] == 'audio') {
3185 $media = Renderer::replaceMacros(Renderer::getMarkupTemplate('content/audio.tpl'), [
3187 'id' => $attachment['id'],
3188 'src' => $attachment['url'],
3189 'name' => $attachment['name'] ?: $attachment['url'],
3190 'mime' => $attachment['mimetype'],
3193 if (($item['post-type'] ?? null) == Item::PT_AUDIO) {
3196 $trailing .= $media;
3198 } elseif ($attachment['filetype'] == 'image') {
3199 $media = Renderer::replaceMacros(Renderer::getMarkupTemplate('content/image.tpl'), [
3201 'src' => Post\Media::getUrlForId($attachment['id']),
3202 'preview' => Post\Media::getPreviewUrlForId($attachment['id'], ($attachment['width'] > $attachment['height']) ? Proxy::SIZE_MEDIUM : Proxy::SIZE_LARGE),
3203 'attachment' => $attachment,
3206 // On Diaspora posts the attached pictures are leading
3207 if ($item['network'] == Protocol::DIASPORA) {
3210 $trailing .= $media;
3216 $content = str_replace(BBCode::TOP_ANCHOR, '<div class="body-attach">' . $leading . '<div class="clear"></div></div>' . BBCode::TOP_ANCHOR, $content);
3217 $content = str_replace(BBCode::BOTTOM_ANCHOR, '<div class="body-attach">' . $trailing . '<div class="clear"></div></div>' . BBCode::BOTTOM_ANCHOR, $content);
3219 if ($leading != '') {
3220 $content = '<div class="body-attach">' . $leading . '<div class="clear"></div></div>' . $content;
3223 if ($trailing != '') {
3224 $content .= '<div class="body-attach">' . $trailing . '<div class="clear"></div></div>';
3228 DI::profiler()->stopRecording();
3233 * Add link attachment to the content
3235 * @param array $attachments
3236 * @param string $body
3237 * @param string $content
3238 * @param bool $shared
3239 * @param array $ignore_links A list of URLs to ignore
3240 * @return string modified content
3242 private static function addLinkAttachment(int $uriid, array $attachments, string $body, string $content, bool $shared, array $ignore_links): string
3244 DI::profiler()->startRecording('rendering');
3245 // Don't show a preview when there is a visual attachment (audio or video)
3246 $types = array_column($attachments['visual'], 'type');
3247 $preview = !in_array(Post\Media::IMAGE, $types) && !in_array(Post\Media::VIDEO, $types);
3249 if (!empty($attachments['link'])) {
3250 foreach ($attachments['link'] as $link) {
3252 foreach ($ignore_links as $ignore_link) {
3253 if (Strings::compareLink($link['url'], $ignore_link)) {
3257 // @todo Judge between the links to use the one with most information
3258 if (!$found && (empty($attachment) || !empty($link['author-name']) ||
3259 (empty($attachment['name']) && !empty($link['name'])) ||
3260 (empty($attachment['description']) && !empty($link['description'])) ||
3261 (empty($attachment['preview']) && !empty($link['preview'])))) {
3262 $attachment = $link;
3267 if (!empty($attachment)) {
3270 'author_name' => $attachment['author-name'] ?? '',
3271 'author_url' => $attachment['author-url'] ?? '',
3272 'description' => $attachment['description'] ?? '',
3275 'provider_name' => $attachment['publisher-name'] ?? '',
3276 'provider_url' => $attachment['publisher-url'] ?? '',
3278 'title' => $attachment['name'] ?? '',
3280 'url' => $attachment['url']];
3282 if ($preview && !empty($attachment['preview'])) {
3283 if ($attachment['preview-width'] >= 500) {
3284 $data['image'] = Post\Media::getPreviewUrlForId($attachment['id'], Proxy::SIZE_MEDIUM);
3286 $data['preview'] = Post\Media::getPreviewUrlForId($attachment['id'], Proxy::SIZE_MEDIUM);
3290 if (!empty($data['description']) && !empty($content)) {
3291 similar_text($data['description'], $content, $percent);
3296 if (!empty($data['description']) && (($data['title'] == $data['description']) || ($percent > 95) || (strpos($content, $data['description']) !== false))) {
3297 $data['description'] = '';
3300 if (($data['author_name'] ?? '') == ($data['provider_name'] ?? '')) {
3301 $data['author_name'] = '';
3304 if (($data['author_url'] ?? '') == ($data['provider_url'] ?? '')) {
3305 $data['author_url'] = '';
3307 } elseif (preg_match("/.*(\[attachment.*?\].*?\[\/attachment\]).*/ism", $body, $match)) {
3308 $data = BBCode::getAttachmentData($match[1]);
3310 DI::profiler()->stopRecording();
3312 if (isset($data['url']) && !in_array(strtolower($data['url']), $ignore_links)) {
3313 if (!empty($data['description']) || !empty($data['image']) || !empty($data['preview'])) {
3314 $parts = parse_url($data['url']);
3315 if (!empty($parts['scheme']) && !empty($parts['host'])) {
3316 if (empty($data['provider_name'])) {
3317 $data['provider_name'] = $parts['host'];
3319 if (empty($data['provider_url']) || empty(parse_url($data['provider_url'], PHP_URL_SCHEME))) {
3320 $data['provider_url'] = $parts['scheme'] . '://' . $parts['host'];
3322 if (!empty($parts['port'])) {
3323 $data['provider_url'] .= ':' . $parts['port'];
3328 // @todo Use a template
3329 $rendered = BBCode::convertAttachment('', BBCode::INTERNAL, false, $data, $uriid);
3330 } elseif (!self::containsLink($content, $data['url'], Post\Media::HTML)) {
3331 $rendered = Renderer::replaceMacros(Renderer::getMarkupTemplate('content/link.tpl'), [
3332 '$url' => $data['url'],
3333 '$title' => $data['title'],
3340 return str_replace(BBCode::BOTTOM_ANCHOR, BBCode::BOTTOM_ANCHOR . $rendered, $content);
3342 return $content . $rendered;
3349 * Add non visual attachments to the content
3351 * @param array $attachments
3352 * @param array $item
3353 * @param string $content
3354 * @return string modified content
3356 private static function addNonVisualAttachments(array $attachments, array $item, string $content): string
3358 DI::profiler()->startRecording('rendering');
3360 foreach ($attachments['additional'] as $attachment) {
3361 if (strpos($item['body'], $attachment['url'])) {
3365 $author = ['uid' => 0, 'id' => $item['author-id'],
3366 'network' => $item['author-network'], 'url' => $item['author-link']];
3367 $the_url = Contact::magicLinkByContact($author, $attachment['url']);
3369 $title = Strings::escapeHtml(trim(($attachment['description'] ?? '') ?: $attachment['url']));
3371 if (!empty($attachment['size'])) {
3372 $title .= ' ' . $attachment['size'] . ' ' . DI::l10n()->t('bytes');
3375 /// @todo Use a template
3376 $icon = '<div class="attachtype icon s22 type-' . $attachment['filetype'] . ' subtype-' . $attachment['subtype'] . '"></div>';
3377 $trailing .= '<a href="' . strip_tags($the_url) . '" title="' . $title . '" class="attachlink" target="_blank" rel="noopener noreferrer" >' . $icon . '</a>';
3380 if ($trailing != '') {
3381 $content .= '<div class="body-attach">' . $trailing . '<div class="clear"></div></div>';
3384 DI::profiler()->stopRecording();
3388 private static function addQuestions(array $item, string $content): string
3390 DI::profiler()->startRecording('rendering');
3391 if (!empty($item['question-id'])) {
3393 'id' => $item['question-id'],
3394 'multiple' => $item['question-multiple'],
3395 'voters' => $item['question-voters'],
3396 'endtime' => $item['question-end-time']
3399 $options = Post\QuestionOption::getByURIId($item['uri-id']);
3400 foreach ($options as $key => $option) {
3401 if ($question['voters'] > 0) {
3402 $percent = $option['replies'] / $question['voters'] * 100;
3403 $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));
3405 $options[$key]['vote'] = DI::l10n()->tt('%2$s (%1$d vote)', '%2$s (%1$d votes)', $option['replies'], $option['name']);
3409 if (!empty($question['voters']) && !empty($question['endtime'])) {
3410 $summary = DI::l10n()->tt('%d voter. Poll end: %s', '%d voters. Poll end: %s', $question['voters'], Temporal::getRelativeDate($question['endtime']));
3411 } elseif (!empty($question['voters'])) {
3412 $summary = DI::l10n()->tt('%d voter.', '%d voters.', $question['voters']);
3413 } elseif (!empty($question['endtime'])) {
3414 $summary = DI::l10n()->t('Poll end: %s', Temporal::getRelativeDate($question['endtime']));
3419 $content .= Renderer::replaceMacros(Renderer::getMarkupTemplate('content/question.tpl'), [
3420 '$question' => $question,
3421 '$options' => $options,
3422 '$summary' => $summary,
3425 DI::profiler()->stopRecording();
3430 * get private link for item
3432 * @param array $item
3433 * @return boolean|array False if item has not plink, otherwise array('href'=>plink url, 'title'=>translated title)
3434 * @throws \Exception
3436 public static function getPlink(array $item)
3438 if (!empty($item['plink']) && Network::isValidHttpUrl($item['plink'])) {
3439 $plink = $item['plink'];
3440 } elseif (!empty($item['uri']) && Network::isValidHttpUrl($item['uri']) && !Network::isLocalLink($item['uri'])) {
3441 $plink = $item['uri'];
3444 if (DI::userSession()->getLocalUserId()) {
3446 'href' => "display/" . $item['guid'],
3447 'orig' => "display/" . $item['guid'],
3448 'title' => DI::l10n()->t('View on separate page'),
3449 'orig_title' => DI::l10n()->t('View on separate page'),
3452 if (!empty($plink) && ($item['private'] == self::PRIVATE)) {
3453 $author = ['uid' => 0, 'id' => $item['author-id'],
3454 'network' => $item['author-network'], 'url' => $item['author-link']];
3455 $plink = Contact::magicLinkByContact($author, $plink);
3458 if (!empty($plink)) {
3459 $ret['href'] = DI::baseUrl()->remove($plink);
3460 $ret['title'] = DI::l10n()->t('Link to source');
3462 } elseif (!empty($plink) && ($item['private'] != self::PRIVATE)) {
3466 'title' => DI::l10n()->t('Link to source'),
3467 'orig_title' => DI::l10n()->t('Link to source'),
3477 * Does the given uri-id belongs to a post that is sent as starting post to a forum?
3479 * @param int $uri_id
3481 * @return boolean "true" when it is a forum post
3483 public static function isForumPost(int $uri_id): bool
3485 foreach (Tag::getByURIId($uri_id, [Tag::EXCLUSIVE_MENTION]) as $tag) {
3486 if (DBA::exists('contact', ['uid' => 0, 'nurl' => Strings::normaliseLink($tag['url']), 'contact-type' => Contact::TYPE_COMMUNITY])) {
3494 * Search item id for given URI or plink
3496 * @param string $uri
3497 * @param integer $uid
3499 * @return integer item id
3501 public static function searchByLink(string $uri, int $uid = 0): int
3503 $ssl_uri = str_replace('http://', 'https://', $uri);
3504 $uris = [$uri, $ssl_uri, Strings::normaliseLink($uri)];
3506 $item = Post::selectFirst(['id'], ['uri' => $uris, 'uid' => $uid]);
3507 if (DBA::isResult($item)) {
3511 $item = Post::selectFirst(['id'], ['plink' => $uris, 'uid' => $uid]);
3512 if (DBA::isResult($item)) {
3520 * Return the URI for a link to the post
3522 * @param string $uri URI or link to post
3524 * @return string URI
3526 public static function getURIByLink(string $uri): string
3528 $ssl_uri = str_replace('http://', 'https://', $uri);
3529 $uris = [$uri, $ssl_uri, Strings::normaliseLink($uri)];
3531 $item = Post::selectFirst(['uri'], ['uri' => $uris]);
3532 if (DBA::isResult($item)) {
3533 return $item['uri'];
3536 $item = Post::selectFirst(['uri'], ['plink' => $uris]);
3537 if (DBA::isResult($item)) {
3538 return $item['uri'];
3545 * Fetches item for given URI or plink
3547 * @param string $uri
3548 * @param integer $uid
3550 * @return integer item id
3552 public static function fetchByLink(string $uri, int $uid = 0): int
3554 Logger::info('Trying to fetch link', ['uid' => $uid, 'uri' => $uri]);
3555 $item_id = self::searchByLink($uri, $uid);
3556 if (!empty($item_id)) {
3557 Logger::info('Link found', ['uid' => $uid, 'uri' => $uri, 'id' => $item_id]);
3567 Hook::callAll('item_by_link', $hookData);
3569 if (isset($hookData['item_id'])) {
3570 return is_numeric($hookData['item_id']) ? $hookData['item_id'] : 0;
3573 $fetched_uri = ActivityPub\Processor::fetchMissingActivity($uri);
3576 $item_id = self::searchByLink($fetched_uri, $uid);
3578 $item_id = Diaspora::fetchByURL($uri);
3581 if (!empty($item_id)) {
3582 Logger::info('Link fetched', ['uid' => $uid, 'uri' => $uri, 'id' => $item_id]);
3586 Logger::info('Link not found', ['uid' => $uid, 'uri' => $uri]);
3591 * Check a prospective item array against user-level permissions
3593 * @param array $item Expected keys: uri, gravity, and
3594 * author-link if is author-id is set,
3595 * owner-link if is owner-id is set,
3596 * causer-link if is causer-id is set.
3597 * @param int $user_id Local user ID
3599 * @throws \Exception
3601 protected static function isAllowedByUser(array $item, int $user_id): bool
3603 if (!empty($item['author-id']) && Contact\User::isBlocked($item['author-id'], $user_id)) {
3604 Logger::notice('Author is blocked by user', ['author-link' => $item['author-link'], 'uid' => $user_id, 'item-uri' => $item['uri']]);
3608 if (!empty($item['owner-id']) && Contact\User::isBlocked($item['owner-id'], $user_id)) {
3609 Logger::notice('Owner is blocked by user', ['owner-link' => $item['owner-link'], 'uid' => $user_id, 'item-uri' => $item['uri']]);
3613 // The causer is set during a thread completion, for example because of a reshare. It countains the responsible actor.
3614 if (!empty($item['causer-id']) && Contact\User::isBlocked($item['causer-id'], $user_id)) {
3615 Logger::notice('Causer is blocked by user', ['causer-link' => $item['causer-link'] ?? $item['causer-id'], 'uid' => $user_id, 'item-uri' => $item['uri']]);
3619 if (!empty($item['causer-id']) && ($item['gravity'] === self::GRAVITY_PARENT) && Contact\User::isIgnored($item['causer-id'], $user_id)) {
3620 Logger::notice('Causer is ignored by user', ['causer-link' => $item['causer-link'] ?? $item['causer-id'], 'uid' => $user_id, 'item-uri' => $item['uri']]);
3628 * Fetch the uri-id of a quote
3630 * @param string $body
3633 private static function getQuoteUriId(string $body): int
3635 $shared = BBCode::fetchShareAttributes($body);
3636 if (empty($shared['message_id'])) {
3639 return ItemURI::getIdByURI($shared['message_id']);