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;
26 use Friendica\Content\Text\BBCode;
27 use Friendica\Content\Text\HTML;
28 use Friendica\Core\Hook;
29 use Friendica\Core\Logger;
30 use Friendica\Core\Protocol;
31 use Friendica\Core\Renderer;
32 use Friendica\Core\System;
33 use Friendica\Model\Tag;
34 use Friendica\Core\Worker;
35 use Friendica\Database\DBA;
37 use Friendica\Protocol\Activity;
38 use Friendica\Protocol\ActivityPub;
39 use Friendica\Protocol\Diaspora;
40 use Friendica\Util\DateTimeFormat;
41 use Friendica\Util\Map;
42 use Friendica\Util\Network;
43 use Friendica\Util\Proxy;
44 use Friendica\Util\Strings;
45 use Friendica\Util\Temporal;
46 use Friendica\Worker\Delivery;
47 use GuzzleHttp\Psr7\Uri;
48 use LanguageDetection\Language;
52 // Posting types, inspired by https://www.w3.org/TR/activitystreams-vocabulary/#object-types
59 const PT_DOCUMENT = 19;
62 const PT_PERSONAL_NOTE = 128;
64 // Posting reasons (Why had a post been stored for a user?)
71 const PR_FOLLOWER = 69;
72 const PR_ANNOUNCEMENT = 70;
73 const PR_COMMENT = 71;
77 const PR_FETCHED = 75;
78 const PR_COMPLETION = 76;
80 const PR_ACTIVITY = 78;
81 const PR_DISTRIBUTE = 79;
85 // system.accept_only_sharer setting values
86 const COMPLETION_NONE = 1;
87 const COMPLETION_COMMENT = 0;
88 const COMPLETION_LIKE = 2;
90 // Field list that is used to display the items
91 const DISPLAY_FIELDLIST = [
92 'uid', 'id', 'parent', 'guid', 'network', 'gravity',
93 'uri-id', 'uri', 'thr-parent-id', 'thr-parent', 'parent-uri-id', 'parent-uri', 'conversation',
94 'commented', 'created', 'edited', 'received', 'verb', 'object-type', 'postopts', 'plink',
95 'wall', 'private', 'starred', 'origin', 'parent-origin', 'title', 'body', 'language',
96 'content-warning', 'location', 'coord', 'app', 'rendered-hash', 'rendered-html', 'object',
97 'quote-uri', 'quote-uri-id', 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid', 'mention', 'global',
98 'author-id', 'author-link', 'author-name', 'author-avatar', 'author-network', 'author-updated', 'author-gsid', 'author-addr', 'author-uri-id',
99 'owner-id', 'owner-link', 'owner-name', 'owner-avatar', 'owner-network', 'owner-contact-type', 'owner-updated',
100 'causer-id', 'causer-link', 'causer-name', 'causer-avatar', 'causer-contact-type', 'causer-network',
101 'contact-id', 'contact-uid', 'contact-link', 'contact-name', 'contact-avatar',
102 'writable', 'self', 'cid', 'alias',
103 'event-created', 'event-edited', 'event-start', 'event-finish',
104 'event-summary', 'event-desc', 'event-location', 'event-type',
105 'event-nofinish', 'event-ignore', 'event-id',
106 'question-id', 'question-multiple', 'question-voters', 'question-end-time',
107 'has-categories', 'has-media',
108 'delivery_queue_count', 'delivery_queue_done', 'delivery_queue_failed'
111 // Field list that is used to deliver items via the protocols
112 const DELIVER_FIELDLIST = ['uid', 'id', 'parent', 'uri-id', 'uri', 'thr-parent', 'parent-uri', 'guid',
113 'parent-guid', 'conversation', 'received', 'created', 'edited', 'verb', 'object-type', 'object', 'target',
114 'private', 'title', 'body', 'raw-body', 'location', 'coord', 'app',
115 'inform', 'deleted', 'extid', 'post-type', 'post-reason', 'gravity',
116 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid',
117 'author-id', 'author-addr', 'author-link', 'author-name', 'author-avatar', 'owner-id', 'owner-link', 'contact-uid',
118 'signed_text', 'network', 'wall', 'contact-id', 'plink', 'origin',
119 'thr-parent-id', 'parent-uri-id', 'quote-uri', 'quote-uri-id', 'postopts', 'pubmail',
120 'event-created', 'event-edited', 'event-start', 'event-finish',
121 'event-summary', 'event-desc', 'event-location', 'event-type',
122 'event-nofinish', 'event-ignore', 'event-id'];
124 // All fields in the item table
125 const ITEM_FIELDLIST = ['id', 'uid', 'parent', 'uri', 'parent-uri', 'thr-parent',
126 'guid', 'uri-id', 'parent-uri-id', 'thr-parent-id', 'conversation', 'vid',
127 'quote-uri', 'quote-uri-id', 'contact-id', 'wall', 'gravity', 'extid', 'psid',
128 'created', 'edited', 'commented', 'received', 'changed', 'verb',
129 'postopts', 'plink', 'resource-id', 'event-id', 'inform',
130 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid', 'post-type', 'post-reason',
131 'private', 'pubmail', 'visible', 'starred',
132 'unseen', 'deleted', 'origin', 'mention', 'global', 'network',
133 'title', 'content-warning', 'body', 'location', 'coord', 'app',
134 'rendered-hash', 'rendered-html', 'object-type', 'object', 'target-type', 'target',
135 'author-id', 'author-link', 'author-name', 'author-avatar', 'author-network',
136 'owner-id', 'owner-link', 'owner-name', 'owner-avatar', 'causer-id'];
138 // List of all verbs that don't need additional content data.
139 // Never reorder or remove entries from this list. Just add new ones at the end, if needed.
141 Activity::LIKE, Activity::DISLIKE,
142 Activity::ATTEND, Activity::ATTENDNO, Activity::ATTENDMAYBE,
151 // Item weight for query ordering
152 const GRAVITY_PARENT = 0;
153 const GRAVITY_ACTIVITY = 3;
154 const GRAVITY_COMMENT = 6;
155 const GRAVITY_UNKNOWN = 9;
158 * Update existing item entries
160 * @param array $fields The fields that are to be changed
161 * @param array $condition The condition for finding the item entries
163 * In the future we may have to change permissions as well.
164 * Then we had to add the user id as third parameter.
166 * A return value of "0" doesn't mean an error - but that 0 rows had been changed.
168 * @return integer|boolean number of affected rows - or "false" if there was an error
169 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
171 public static function update(array $fields, array $condition)
173 if (empty($condition) || empty($fields)) {
177 if (isset($fields['extid'])) {
178 $fields['external-id'] = ItemURI::getIdByURI($fields['extid']);
181 if (!empty($fields['verb'])) {
182 $fields['vid'] = Verb::getID($fields['verb']);
185 if (!empty($fields['edited'])) {
186 $previous = Post::selectFirst(['edited'], $condition);
189 $rows = Post::update($fields, $condition);
190 if (is_bool($rows)) {
194 // We only need to call the line by line update for specific fields
195 if (empty($fields['body']) && empty($fields['file']) &&
196 empty($fields['attach']) && empty($fields['edited'])) {
200 Logger::info('Updating per single row method', ['fields' => $fields, 'condition' => $condition]);
202 $items = Post::select(['id', 'origin', 'uri-id', 'uid', 'author-network', 'quote-uri-id'], $condition);
206 while ($item = DBA::fetch($items)) {
207 if (!empty($fields['body'])) {
208 if (!empty($item['quote-uri-id'])) {
209 $fields['body'] = BBCode::removeSharedData($fields['body']);
211 if (!empty($fields['raw-body'])) {
212 $fields['raw-body'] = BBCode::removeSharedData($fields['raw-body']);
216 Post\Media::insertFromAttachmentData($item['uri-id'], $fields['body']);
218 $content_fields = ['raw-body' => trim($fields['raw-body'] ?? $fields['body'])];
220 // Remove all media attachments from the body and store them in the post-media table
221 // @todo On shared postings (Diaspora style and commented reshare) don't fetch content from the shared part
222 $content_fields['raw-body'] = Post\Media::insertFromBody($item['uri-id'], $content_fields['raw-body']);
223 $content_fields['raw-body'] = self::setHashtags($content_fields['raw-body']);
225 Post\Media::insertFromRelevantUrl($item['uri-id'], $content_fields['raw-body'], $fields['body'], $item['author-network']);
226 Post\Content::update($item['uri-id'], $content_fields);
229 if (!empty($fields['file'])) {
230 Post\Category::storeTextByURIId($item['uri-id'], $item['uid'], $fields['file']);
233 if (!empty($fields['attach'])) {
234 Post\Media::insertFromAttachment($item['uri-id'], $fields['attach']);
237 // We only need to notfiy others when it is an original entry from us.
238 // Only call the notifier when the item had been edited and records had been changed.
239 if ($item['origin'] && !empty($fields['edited']) && ($previous['edited'] != $fields['edited'])) {
240 $notify_items[] = $item['id'];
246 foreach ($notify_items as $notify_item) {
247 $post = Post::selectFirst(['uri-id', 'uid'], ['id' => $notify_item]);
248 Worker::add(Worker::PRIORITY_HIGH, 'Notifier', Delivery::POST, (int)$post['uri-id'], (int)$post['uid']);
255 * Delete an item and notify others about it - if it was ours
257 * @param array $condition The condition for finding the item entries
258 * @param integer $priority Priority for the notification
260 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
262 public static function markForDeletion(array $condition, int $priority = Worker::PRIORITY_HIGH)
264 $items = Post::select(['id'], $condition);
265 while ($item = Post::fetch($items)) {
266 self::markForDeletionById($item['id'], $priority);
272 * Delete an item for an user and notify others about it - if it was ours
274 * @param array $condition The condition for finding the item entries
275 * @param integer $uid User who wants to delete this item
277 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
279 public static function deleteForUser(array $condition, int $uid)
285 $items = Post::select(['id', 'uid', 'uri-id'], $condition);
286 while ($item = Post::fetch($items)) {
287 if (in_array($item['uid'], [$uid, 0])) {
288 Post\User::update($item['uri-id'], $uid, ['hidden' => true], true);
289 Post\ThreadUser::update($item['uri-id'], $uid, ['hidden' => true], true);
292 if ($item['uid'] == $uid) {
293 self::markForDeletionById($item['id'], Worker::PRIORITY_HIGH);
294 } elseif ($item['uid'] != 0) {
295 Logger::warning('Wrong ownership. Not deleting item', ['id' => $item['id']]);
302 * Mark an item for deletion, delete related data and notify others about it - if it was ours
304 * @param integer $item_id
305 * @param integer $priority Priority for the notification
306 * @return boolean success
307 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
309 public static function markForDeletionById(int $item_id, int $priority = Worker::PRIORITY_HIGH): bool
311 Logger::info('Mark item for deletion by id', ['id' => $item_id, 'callstack' => System::callstack()]);
312 // locate item to be deleted
313 $fields = ['id', 'uri', 'uri-id', 'uid', 'parent', 'parent-uri-id', 'origin',
314 'deleted', 'resource-id', 'event-id',
315 'verb', 'object-type', 'object', 'target', 'contact-id', 'psid', 'gravity'];
316 $item = Post::selectFirst($fields, ['id' => $item_id]);
317 if (!DBA::isResult($item)) {
318 Logger::info('Item not found.', ['id' => $item_id]);
322 if ($item['deleted']) {
323 Logger::info('Item has already been marked for deletion.', ['id' => $item_id]);
327 $parent = Post::selectFirst(['origin'], ['id' => $item['parent']]);
328 if (!DBA::isResult($parent)) {
329 $parent = ['origin' => false];
332 // clean up categories and tags so they don't end up as orphans
333 Post\Category::deleteByURIId($item['uri-id'], $item['uid']);
336 * If item is a link to a photo resource, nuke all the associated photos
337 * (visitors will not have photo resources)
338 * This only applies to photos uploaded from the photos page. Photos inserted into a post do not
339 * generate a resource-id and therefore aren't intimately linked to the item.
341 /// @TODO: this should first check if photo is used elsewhere
342 if ($item['resource-id']) {
343 Photo::delete(['resource-id' => $item['resource-id'], 'uid' => $item['uid']]);
346 // If item is a link to an event, delete the event.
347 if (intval($item['event-id'])) {
348 Event::delete($item['event-id']);
351 // If item has attachments, drop them
352 $attachments = Post\Media::getByURIId($item['uri-id'], [Post\Media::DOCUMENT]);
353 foreach($attachments as $attachment) {
354 if (preg_match('|attach/(\d+)|', $attachment['url'], $matches)) {
355 Attach::delete(['id' => $matches[1], 'uid' => $item['uid']]);
359 // Set the item to "deleted"
360 $item_fields = ['deleted' => true, 'edited' => DateTimeFormat::utcNow(), 'changed' => DateTimeFormat::utcNow()];
361 Post::update($item_fields, ['id' => $item['id']]);
363 Post\Category::storeTextByURIId($item['uri-id'], $item['uid'], '');
365 if (!Post::exists(["`uri-id` = ? AND `uid` != 0 AND NOT `deleted`", $item['uri-id']])) {
366 self::markForDeletion(['uri-id' => $item['uri-id'], 'uid' => 0, 'deleted' => false], $priority);
369 Post\DeliveryData::delete($item['uri-id']);
371 // If it's the parent of a comment thread, kill all the kids
372 if ($item['gravity'] == self::GRAVITY_PARENT) {
373 self::markForDeletion(['parent' => $item['parent'], 'deleted' => false], $priority);
376 // Is it our comment and/or our thread?
377 if (($item['origin'] || $parent['origin']) && ($item['uid'] != 0)) {
378 // When we delete the original post we will delete all existing copies on the server as well
379 self::markForDeletion(['uri-id' => $item['uri-id'], 'deleted' => false], $priority);
381 // send the notification upstream/downstream
383 Worker::add(['priority' => $priority, 'dont_fork' => true], 'Notifier', Delivery::DELETION, (int)$item['uri-id'], (int)$item['uid']);
385 } elseif ($item['uid'] != 0) {
386 Post\User::update($item['uri-id'], $item['uid'], ['hidden' => true]);
387 Post\ThreadUser::update($item['uri-id'], $item['uid'], ['hidden' => true]);
390 DI::notify()->deleteForItem($item['uri-id']);
391 DI::notification()->deleteForItem($item['uri-id']);
393 Logger::info('Item has been marked for deletion.', ['id' => $item_id]);
399 * Get guid from given item record
401 * @param array $item Item record
402 * @param bool Whether to notify (?)
403 * @return string Guid
405 public static function guid(array $item, bool $notify): string
407 if (!empty($item['guid'])) {
408 return trim($item['guid']);
412 // We have to avoid duplicates. So we create the GUID in form of a hash of the plink or uri.
413 // We add the hash of our own host because our host is the original creator of the post.
414 $prefix_host = DI::baseUrl()->getHostname();
418 // We are only storing the post so we create a GUID from the original hostname.
419 if (!empty($item['author-link'])) {
420 $parsed = parse_url($item['author-link']);
421 if (!empty($parsed['host'])) {
422 $prefix_host = $parsed['host'];
426 if (empty($prefix_host) && !empty($item['plink'])) {
427 $parsed = parse_url($item['plink']);
428 if (!empty($parsed['host'])) {
429 $prefix_host = $parsed['host'];
433 if (empty($prefix_host) && !empty($item['uri'])) {
434 $parsed = parse_url($item['uri']);
435 if (!empty($parsed['host'])) {
436 $prefix_host = $parsed['host'];
440 // Is it in the format data@host.tld? - Used for mail contacts
441 if (empty($prefix_host) && !empty($item['author-link']) && strstr($item['author-link'], '@')) {
442 $mailparts = explode('@', $item['author-link']);
443 $prefix_host = array_pop($mailparts);
447 if (!empty($item['plink'])) {
448 $guid = self::guidFromUri($item['plink'], $prefix_host);
449 } elseif (!empty($item['uri'])) {
450 $guid = self::guidFromUri($item['uri'], $prefix_host);
452 $guid = System::createUUID(hash('crc32', $prefix_host));
459 * Returns contact id from given item record
461 * @param array $item Item record
462 * @return int Contact id
464 private static function contactId(array $item): int
466 if ($item['uid'] == 0) {
467 return $item['author-id'];
470 if ($item['origin']) {
471 $owner = User::getOwnerDataById($item['uid']);
475 if (!empty($item['causer-id']) && Contact::isSharing($item['causer-id'], $item['uid'], true)) {
476 $cdata = Contact::getPublicAndUserContactID($item['causer-id'], $item['uid']);
477 if (!empty($cdata['user'])) {
478 return $cdata['user'];
482 if ($item['gravity'] == self::GRAVITY_PARENT) {
483 if (Contact::isSharingByURL($item['owner-link'], $item['uid'], true)) {
484 $contact_id = Contact::getIdForURL($item['owner-link'], $item['uid']);
486 $contact_id = Contact::getIdForURL($item['owner-link']);
488 if (!empty($contact_id)) {
493 if (Contact::isSharingByURL($item['author-link'], $item['uid'], true)) {
494 $contact_id = Contact::getIdForURL($item['author-link'], $item['uid']);
496 $contact_id = Contact::getIdForURL($item['author-link']);
499 if (!empty($contact_id)) {
503 Logger::warning('contact-id could not be fetched, using self contact instead.', ['uid' => $item['uid'], 'item' => $item]);
504 $self = Contact::selectFirst(['id'], ['self' => true, 'uid' => $item['uid']]);
509 * Write an item array into a spool file to be inserted later.
510 * This command is called whenever there are issues storing an item.
512 * @param array $item The item fields that are to be inserted
515 private static function spool(array $item)
517 // Now we store the data in the spool directory
518 // We use "microtime" to keep the arrival order and "mt_rand" to avoid duplicates
519 $file = 'item-' . round(microtime(true) * 10000) . '-' . mt_rand() . '.msg';
521 $spoolpath = System::getSpoolPath();
522 if ($spoolpath != '') {
523 $spool = $spoolpath . '/' . $file;
525 file_put_contents($spool, json_encode($item));
526 Logger::warning("Item wasn't stored - Item was spooled into file", ['file' => $file]);
531 * Check if the item array is a duplicate
533 * @param array $item Item record
534 * @return boolean is it a duplicate?
536 private static function isDuplicate(array $item): bool
538 // Checking if there is already an item with the same guid
539 $condition = ['guid' => $item['guid'], 'network' => $item['network'], 'uid' => $item['uid']];
540 if (Post::exists($condition)) {
541 Logger::notice('Found already existing item', $condition);
545 $condition = ['uri-id' => $item['uri-id'], 'uid' => $item['uid'],
546 'network' => [$item['network'], Protocol::DFRN]];
547 if (Post::exists($condition)) {
548 Logger::notice('duplicated item with the same uri found.', $condition);
552 // On Friendica and Diaspora the GUID is unique
553 if (in_array($item['network'], [Protocol::DFRN, Protocol::DIASPORA])) {
554 $condition = ['guid' => $item['guid'], 'uid' => $item['uid']];
555 if (Post::exists($condition)) {
556 Logger::notice('duplicated item with the same guid found.', $condition);
559 } elseif ($item['network'] == Protocol::OSTATUS) {
560 // Check for an existing post with the same content. There seems to be a problem with OStatus.
561 $condition = ["`body` = ? AND `network` = ? AND `created` = ? AND `contact-id` = ? AND `uid` = ?",
562 $item['body'], $item['network'], $item['created'], $item['contact-id'], $item['uid']];
563 if (Post::exists($condition)) {
564 Logger::notice('duplicated item with the same body found.', $item);
570 * Check for already added items.
571 * There is a timing issue here that sometimes creates double postings.
572 * An unique index would help - but the limitations of MySQL (maximum size of index values) prevent this.
574 if (($item['uid'] == 0) && Post::exists(['uri-id' => $item['uri-id'], 'uid' => 0])) {
575 Logger::notice('Global item already stored.', ['uri-id' => $item['uri-id'], 'network' => $item['network']]);
583 * Check if the item array is valid
585 * @param array $item Item record
586 * @return boolean item is valid
588 public static function isValid(array $item): bool
590 // When there is no content then we don't post it
591 if (($item['body'] . $item['title'] == '') && empty($item['quote-uri-id']) && (empty($item['uri-id']) || !Post\Media::existsByURIId($item['uri-id']))) {
592 Logger::notice('No body, no title.');
596 if (!empty($item['uid'])) {
597 $owner = User::getOwnerDataById($item['uid'], false);
599 Logger::warning('Missing item user owner data', ['uid' => $item['uid']]);
603 if ($owner['account_expired'] || $owner['account_removed']) {
604 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']]);
609 if (!empty($item['author-id']) && Contact::isBlocked($item['author-id'])) {
610 Logger::notice('Author is blocked node-wide', ['author-link' => $item['author-link'], 'item-uri' => $item['uri']]);
614 if (!empty($item['author-link']) && Network::isUrlBlocked($item['author-link'])) {
615 Logger::notice('Author server is blocked', ['author-link' => $item['author-link'], 'item-uri' => $item['uri']]);
619 if (!empty($item['owner-id']) && Contact::isBlocked($item['owner-id'])) {
620 Logger::notice('Owner is blocked node-wide', ['owner-link' => $item['owner-link'], 'item-uri' => $item['uri']]);
624 if (!empty($item['owner-link']) && Network::isUrlBlocked($item['owner-link'])) {
625 Logger::notice('Owner server is blocked', ['owner-link' => $item['owner-link'], 'item-uri' => $item['uri']]);
629 if (!empty($item['uid']) && !self::isAllowedByUser($item, $item['uid'])) {
633 if ($item['verb'] == Activity::FOLLOW) {
634 if (!$item['origin'] && ($item['author-id'] == Contact::getPublicIdByUserId($item['uid']))) {
635 // Our own follow request can be relayed to us. We don't store it to avoid notification chaos.
636 Logger::info("Follow: Don't store not origin follow request", ['parent-uri' => $item['parent-uri']]);
640 $condition = ['verb' => Activity::FOLLOW, 'uid' => $item['uid'],
641 'parent-uri' => $item['parent-uri'], 'author-id' => $item['author-id']];
642 if (Post::exists($condition)) {
643 // It happens that we receive multiple follow requests by the same author - we only store one.
644 Logger::info('Follow: Found existing follow request from author', ['author-id' => $item['author-id'], 'parent-uri' => $item['parent-uri']]);
653 * Check if the item array is too old
655 * @param array $item Item record
656 * @return boolean item is too old
658 public static function isTooOld(array $item): bool
660 // check for create date and expire time
661 $expire_interval = DI::config()->get('system', 'dbclean-expire-days', 0);
663 $user = DBA::selectFirst('user', ['expire'], ['uid' => $item['uid']]);
664 if (DBA::isResult($user) && ($user['expire'] > 0) && (($user['expire'] < $expire_interval) || ($expire_interval == 0))) {
665 $expire_interval = $user['expire'];
668 if (($expire_interval > 0) && !empty($item['created'])) {
669 $expire_date = time() - ($expire_interval * 86400);
670 $created_date = strtotime($item['created']);
671 if ($created_date < $expire_date) {
672 Logger::notice('Item created before expiration interval.', [
673 'created' => date('c', $created_date),
674 'expired' => date('c', $expire_date),
685 * Return the id of the given item array if it has been stored before
687 * @param array $item Item record
688 * @return integer Item id or zero on error
690 private static function getDuplicateID(array $item): int
692 if (empty($item['network']) || in_array($item['network'], Protocol::FEDERATED)) {
693 $condition = ['`uri-id` = ? AND `uid` = ? AND `network` IN (?, ?, ?, ?)',
696 Protocol::ACTIVITYPUB,
701 $existing = Post::selectFirst(['id', 'network'], $condition);
702 if (DBA::isResult($existing)) {
703 // We only log the entries with a different user id than 0. Otherwise we would have too many false positives
704 if ($item['uid'] != 0) {
705 Logger::notice('Item already existed for user', [
706 'uri-id' => $item['uri-id'],
707 'uid' => $item['uid'],
708 'network' => $item['network'],
709 'existing_id' => $existing['id'],
710 'existing_network' => $existing['network']
714 return $existing['id'];
721 * Fetch the uri-id of the parent for the given uri-id
723 * @param integer $uriid
726 public static function getParent(int $uriid): int
728 $thread_parent = Post::selectFirstPost(['thr-parent-id', 'gravity'], ['uri-id' => $uriid]);
729 if (empty($thread_parent)) {
733 if ($thread_parent['gravity'] == Item::GRAVITY_PARENT) {
737 return self::getParent($thread_parent['thr-parent-id']);
741 * Fetch top-level parent data for the given item array
744 * @return array item array with parent data
747 private static function getTopLevelParent(array $item): array
749 $fields = ['uid', 'uri', 'parent-uri', 'id', 'deleted',
750 'uri-id', 'parent-uri-id',
751 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid',
752 'wall', 'private', 'origin', 'author-id'];
753 $condition = ['uri-id' => [$item['thr-parent-id'], $item['parent-uri-id']], 'uid' => $item['uid']];
754 $params = ['order' => ['id' => false]];
755 $parent = Post::selectFirst($fields, $condition, $params);
757 if (!DBA::isResult($parent) && Post::exists(['uri-id' => [$item['thr-parent-id'], $item['parent-uri-id']], 'uid' => 0])) {
758 $stored = Item::storeForUserByUriId($item['thr-parent-id'], $item['uid'], ['post-reason' => Item::PR_COMPLETION]);
759 if (!$stored && ($item['thr-parent-id'] != $item['parent-uri-id'])) {
760 $stored = Item::storeForUserByUriId($item['parent-uri-id'], $item['uid'], ['post-reason' => Item::PR_COMPLETION]);
763 Logger::info('Stored thread parent item for user', ['uri-id' => $item['thr-parent-id'], 'uid' => $item['uid'], 'stored' => $stored]);
764 $parent = Post::selectFirst($fields, $condition, $params);
768 if (!DBA::isResult($parent)) {
769 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)]);
773 if ($parent['uri-id'] == $parent['parent-uri-id']) {
777 $condition = ['uri-id' => $parent['parent-uri-id'],
778 'parent-uri-id' => $parent['parent-uri-id'],
779 'uid' => $parent['uid']];
780 $params = ['order' => ['id' => false]];
781 $toplevel_parent = Post::selectFirst($fields, $condition, $params);
783 if (!DBA::isResult($toplevel_parent) && $item['origin']) {
784 $stored = Item::storeForUserByUriId($item['parent-uri-id'], $item['uid'], ['post-reason' => Item::PR_COMPLETION]);
785 Logger::info('Stored parent item for user', ['uri-id' => $item['parent-uri-id'], 'uid' => $item['uid'], 'stored' => $stored]);
786 $toplevel_parent = Post::selectFirst($fields, $condition, $params);
789 if (!DBA::isResult($toplevel_parent)) {
790 Logger::notice('item top level parent was not found - ignoring item', ['parent-uri-id' => $parent['parent-uri-id'], 'uid' => $parent['uid']]);
794 return $toplevel_parent;
798 * Get the gravity for the given item array
801 * @return integer gravity
803 private static function getGravity(array $item): int
805 $activity = DI::activity();
807 if (isset($item['gravity'])) {
808 return intval($item['gravity']);
809 } elseif ($item['parent-uri-id'] === $item['uri-id']) {
810 return self::GRAVITY_PARENT;
811 } elseif ($activity->match($item['verb'], Activity::POST)) {
812 return self::GRAVITY_COMMENT;
813 } elseif ($activity->match($item['verb'], Activity::FOLLOW)) {
814 return self::GRAVITY_ACTIVITY;
815 } elseif ($activity->match($item['verb'], Activity::ANNOUNCE)) {
816 return self::GRAVITY_ACTIVITY;
819 Logger::info('Unknown gravity for verb', ['verb' => $item['verb']]);
820 return self::GRAVITY_UNKNOWN; // Should not happen
823 private static function prepareOriginPost(array $item): array
827 $item['network'] = Protocol::DFRN;
828 $item['protocol'] = Conversation::PARCEL_DIRECT;
829 $item['direction'] = Conversation::PUSH;
831 $owner = User::getOwnerDataById($item['uid']);
833 if (empty($item['contact-id'])) {
834 $item['contact-id'] = $owner['id'];
837 if (empty($item['author-link']) && empty($item['author-id'])) {
838 $item['author-link'] = $owner['url'];
839 $item['author-name'] = $owner['name'];
840 $item['author-avatar'] = $owner['thumb'];
843 if (empty($item['owner-link']) && empty($item['owner-id'])) {
844 $item['owner-link'] = $item['author-link'];
845 $item['owner-name'] = $item['author-name'];
846 $item['owner-avatar'] = $item['author-avatar'];
849 // Setting the object type if not defined before
850 if (empty($item['object-type'])) {
851 $item['object-type'] = Activity\ObjectType::NOTE; // Default value
852 $objectdata = BBCode::getAttachedData($item['body']);
854 if ($objectdata['type'] == 'link') {
855 $item['object-type'] = Activity\ObjectType::BOOKMARK;
856 } elseif ($objectdata['type'] == 'video') {
857 $item['object-type'] = Activity\ObjectType::VIDEO;
858 } elseif ($objectdata['type'] == 'photo') {
859 $item['object-type'] = Activity\ObjectType::IMAGE;
867 * Inserts item record
869 * @param array $item Item array to be inserted
870 * @param int $notify Notification (type?)
871 * @param bool $post_local (???)
872 * @return int Zero means error, otherwise primary key (id) is being returned
874 public static function insert(array $item, int $notify = 0, bool $post_local = true): int
878 $priority = Worker::PRIORITY_HIGH;
880 // If it is a posting where users should get notifications, then define it as wall posting
882 $item = self::prepareOriginPost($item);
884 if (is_int($notify) && in_array($notify, Worker::PRIORITIES)) {
888 $item['network'] = trim(($item['network'] ?? '') ?: Protocol::PHANTOM);
891 $uid = intval($item['uid']);
893 $item['guid'] = self::guid($item, $notify);
894 $item['uri'] = substr(trim($item['uri'] ?? '') ?: self::newURI($item['guid']), 0, 255);
897 $item['uri-id'] = ItemURI::insert(['uri' => $item['uri'], 'guid' => $item['guid']]);
899 // Backward compatibility: parent-uri used to be the direct parent uri.
900 // If it is provided without a thr-parent, it probably is the old behavior.
901 if (empty($item['thr-parent']) || empty($item['parent-uri'])) {
902 $item['thr-parent'] = trim($item['thr-parent'] ?? $item['parent-uri'] ?? $item['uri']);
903 $item['parent-uri'] = $item['thr-parent'];
906 $item['thr-parent-id'] = ItemURI::getIdByURI($item['thr-parent']);
907 $item['parent-uri-id'] = ItemURI::getIdByURI($item['parent-uri']);
909 // Store conversation data
910 $source = $item['source'] ?? '';
911 unset($item['conversation-uri']);
912 unset($item['conversation-href']);
913 unset($item['source']);
916 * Do we already have this item?
917 * We have to check several networks since Friendica posts could be repeated
918 * via OStatus (maybe Diasporsa as well)
920 $duplicate = self::getDuplicateID($item);
925 // Additional duplicate checks
926 /// @todo Check why the first duplication check returns the item number and the second a 0
927 if (self::isDuplicate($item)) {
931 if (!isset($item['post-type'])) {
932 $item['post-type'] = empty($item['title']) ? self::PT_NOTE : self::PT_ARTICLE;
935 $item['wall'] = intval($item['wall'] ?? 0);
936 $item['extid'] = trim($item['extid'] ?? '');
937 $item['author-name'] = trim($item['author-name'] ?? '');
938 $item['author-link'] = trim($item['author-link'] ?? '');
939 $item['author-avatar'] = trim($item['author-avatar'] ?? '');
940 $item['owner-name'] = trim($item['owner-name'] ?? '');
941 $item['owner-link'] = trim($item['owner-link'] ?? '');
942 $item['owner-avatar'] = trim($item['owner-avatar'] ?? '');
943 $item['received'] = (isset($item['received']) ? DateTimeFormat::utc($item['received']) : DateTimeFormat::utcNow());
944 $item['created'] = (isset($item['created']) ? DateTimeFormat::utc($item['created']) : $item['received']);
945 $item['edited'] = (isset($item['edited']) ? DateTimeFormat::utc($item['edited']) : $item['created']);
946 $item['changed'] = (isset($item['changed']) ? DateTimeFormat::utc($item['changed']) : $item['created']);
947 $item['commented'] = (isset($item['commented']) ? DateTimeFormat::utc($item['commented']) : $item['created']);
948 $item['title'] = substr(trim($item['title'] ?? ''), 0, 255);
949 $item['location'] = trim($item['location'] ?? '');
950 $item['coord'] = trim($item['coord'] ?? '');
951 $item['visible'] = (isset($item['visible']) ? intval($item['visible']) : 1);
952 $item['deleted'] = 0;
953 $item['verb'] = trim($item['verb'] ?? '');
954 $item['object-type'] = trim($item['object-type'] ?? '');
955 $item['object'] = trim($item['object'] ?? '');
956 $item['target-type'] = trim($item['target-type'] ?? '');
957 $item['target'] = trim($item['target'] ?? '');
958 $item['plink'] = substr(trim($item['plink'] ?? ''), 0, 255);
959 $item['allow_cid'] = trim($item['allow_cid'] ?? '');
960 $item['allow_gid'] = trim($item['allow_gid'] ?? '');
961 $item['deny_cid'] = trim($item['deny_cid'] ?? '');
962 $item['deny_gid'] = trim($item['deny_gid'] ?? '');
963 $item['private'] = intval($item['private'] ?? self::PUBLIC);
964 $item['body'] = trim($item['body'] ?? '');
965 $item['raw-body'] = trim($item['raw-body'] ?? $item['body']);
966 $item['app'] = trim($item['app'] ?? '');
967 $item['origin'] = intval($item['origin'] ?? 0);
968 $item['postopts'] = trim($item['postopts'] ?? '');
969 $item['resource-id'] = trim($item['resource-id'] ?? '');
970 $item['event-id'] = intval($item['event-id'] ?? 0);
971 $item['inform'] = trim($item['inform'] ?? '');
972 $item['file'] = trim($item['file'] ?? '');
974 // Communities aren't working with the Diaspora protoccol
975 if (($uid != 0) && ($item['network'] == Protocol::DIASPORA)) {
976 $user = User::getById($uid, ['account-type']);
977 if ($user['account-type'] == Contact::TYPE_COMMUNITY) {
978 Logger::info('Community posts are not supported via Diaspora');
983 // Items cannot be stored before they happen ...
984 if ($item['created'] > DateTimeFormat::utcNow()) {
985 $item['created'] = DateTimeFormat::utcNow();
988 // We haven't invented time travel by now.
989 if ($item['edited'] > DateTimeFormat::utcNow()) {
990 $item['edited'] = DateTimeFormat::utcNow();
993 $item['plink'] = ($item['plink'] ?? '') ?: DI::baseUrl() . '/display/' . urlencode($item['guid']);
995 $item['gravity'] = self::getGravity($item);
997 $default = ['url' => $item['author-link'], 'name' => $item['author-name'],
998 'photo' => $item['author-avatar'], 'network' => $item['network']];
999 $item['author-id'] = ($item['author-id'] ?? 0) ?: Contact::getIdForURL($item['author-link'], 0, null, $default);
1001 $default = ['url' => $item['owner-link'], 'name' => $item['owner-name'],
1002 'photo' => $item['owner-avatar'], 'network' => $item['network']];
1003 $item['owner-id'] = ($item['owner-id'] ?? 0) ?: Contact::getIdForURL($item['owner-link'], 0, null, $default);
1005 $item['post-reason'] = self::getPostReason($item);
1007 // Ensure that there is an avatar cache
1008 Contact::checkAvatarCache($item['author-id']);
1009 Contact::checkAvatarCache($item['owner-id']);
1011 $item['contact-id'] = self::contactId($item);
1013 if (!empty($item['direction']) && in_array($item['direction'], [Conversation::PUSH, Conversation::RELAY]) &&
1014 empty($item['origin']) && self::isTooOld($item)) {
1015 Logger::info('Item is too old', ['item' => $item]);
1019 if (!self::isValid($item)) {
1023 if ($item['gravity'] !== self::GRAVITY_PARENT) {
1024 $toplevel_parent = self::getTopLevelParent($item);
1025 if (empty($toplevel_parent)) {
1029 // If the thread originated from this node, we check the permission against the thread starter
1030 $condition = ['uri-id' => $toplevel_parent['uri-id'], 'wall' => true];
1031 $localTopLevelParent = Post::selectFirst(['uid'], $condition);
1032 if (!empty($localTopLevelParent['uid']) && !self::isAllowedByUser($item, $localTopLevelParent['uid'])) {
1036 $parent_id = $toplevel_parent['id'];
1037 $item['parent-uri'] = $toplevel_parent['uri'];
1038 $item['parent-uri-id'] = $toplevel_parent['uri-id'];
1039 $item['deleted'] = $toplevel_parent['deleted'];
1040 $item['wall'] = $toplevel_parent['wall'];
1042 // Reshares have to keep their permissions to allow forums to work
1043 if (!$item['origin'] || ($item['verb'] != Activity::ANNOUNCE)) {
1044 $item['allow_cid'] = $toplevel_parent['allow_cid'];
1045 $item['allow_gid'] = $toplevel_parent['allow_gid'];
1046 $item['deny_cid'] = $toplevel_parent['deny_cid'];
1047 $item['deny_gid'] = $toplevel_parent['deny_gid'];
1050 $parent_origin = $toplevel_parent['origin'];
1052 // Don't federate received participation messages
1053 if ($item['verb'] != Activity::FOLLOW) {
1054 $item['wall'] = $toplevel_parent['wall'];
1056 $item['wall'] = false;
1057 // Participations are technical messages, so they are set to "seen" automatically
1058 $item['unseen'] = false;
1062 * If the parent is private, force privacy for the entire conversation
1063 * This differs from the above settings as it subtly allows comments from
1064 * email correspondents to be private even if the overall thread is not.
1066 if ($toplevel_parent['private']) {
1067 $item['private'] = $toplevel_parent['private'];
1070 // If its a post that originated here then tag the thread as "mention"
1071 if ($item['origin'] && $item['uid']) {
1072 DBA::update('post-thread-user', ['mention' => true], ['uri-id' => $item['parent-uri-id'], 'uid' => $item['uid']]);
1073 Logger::info('tagged thread as mention', ['parent' => $parent_id, 'parent-uri-id' => $item['parent-uri-id'], 'uid' => $item['uid']]);
1076 // Update the contact relations
1077 Contact\Relation::store($toplevel_parent['author-id'], $item['author-id'], $item['created']);
1080 $parent_origin = $item['origin'];
1082 if ($item['wall'] && empty($item['conversation'])) {
1083 $item['conversation'] = $item['parent-uri'] . '#context';
1087 $item['parent-uri-id'] = ItemURI::getIdByURI($item['parent-uri']);
1088 $item['thr-parent-id'] = ItemURI::getIdByURI($item['thr-parent']);
1090 if (!empty($item['conversation']) && empty($item['conversation-id'])) {
1091 $item['conversation-id'] = ItemURI::getIdByURI($item['conversation']);
1094 // Is this item available in the global items (with uid=0)?
1095 if ($item['uid'] == 0) {
1096 $item['global'] = true;
1098 // Set the global flag on all items if this was a global item entry
1099 Post::update(['global' => true], ['uri-id' => $item['uri-id']]);
1101 $item['global'] = Post::exists(['uid' => 0, 'uri-id' => $item['uri-id']]);
1105 if (!empty($item['allow_cid'] . $item['allow_gid'] . $item['deny_cid'] . $item['deny_gid'])) {
1106 $item['private'] = self::PRIVATE;
1109 if ($notify && $post_local) {
1110 $item['edit'] = false;
1111 $item['parent'] = $parent_id;
1113 // Trigger automatic reactions for addons
1114 if (!isset($item['api_source'])) {
1115 $item['api_source'] = true;
1118 // We have to tell the hooks who we are - this really should be improved
1119 if (!DI::userSession()->getLocalUserId()) {
1120 $_SESSION['authenticated'] = true;
1121 $_SESSION['uid'] = $uid;
1122 $dummy_session = true;
1124 $dummy_session = false;
1127 Hook::callAll('post_local', $item);
1129 if ($dummy_session) {
1130 unset($_SESSION['authenticated']);
1131 unset($_SESSION['uid']);
1133 } elseif (!$notify) {
1134 Hook::callAll('post_remote', $item);
1137 if (!empty($item['cancel'])) {
1138 Logger::notice('post cancelled by addon.');
1142 if (empty($item['vid']) && !empty($item['verb'])) {
1143 $item['vid'] = Verb::getID($item['verb']);
1146 // Creates or assigns the permission set
1147 $item['psid'] = DI::permissionSet()->selectOrCreate(
1148 DI::permissionSetFactory()->createFromString(
1156 if (!empty($item['extid'])) {
1157 $item['external-id'] = ItemURI::getIdByURI($item['extid']);
1160 if ($item['verb'] == Activity::ANNOUNCE) {
1161 self::setOwnerforResharedItem($item);
1164 if (isset($item['attachments'])) {
1165 foreach ($item['attachments'] as $attachment) {
1166 $attachment['uri-id'] = $item['uri-id'];
1167 Post\Media::insert($attachment);
1169 unset($item['attachments']);
1172 if (empty($item['quote-uri-id'])) {
1173 $quote_id = self::getQuoteUriId($item['body']);
1174 if (!empty($quote_id)) {
1175 // This is one of these "should not happen" situations.
1176 // The protocol implementations should already have done this job.
1177 Logger::notice('Quote-uri-id detected in post', ['id' => $quote_id, 'guid' => $item['guid'], 'uri-id' => $item['uri-id'], 'callstack' => System::callstack(20)]);
1178 $item['quote-uri-id'] = $quote_id;
1182 if (!empty($item['quote-uri-id'])) {
1183 $item['raw-body'] = BBCode::removeSharedData($item['raw-body']);
1184 $item['body'] = BBCode::removeSharedData($item['body']);
1187 Post\Media::insertFromAttachmentData($item['uri-id'], $item['body']);
1189 // Remove all media attachments from the body and store them in the post-media table
1190 $item['raw-body'] = Post\Media::insertFromBody($item['uri-id'], $item['raw-body']);
1191 $item['raw-body'] = self::setHashtags($item['raw-body']);
1193 $author = Contact::getById($item['author-id'], ['network']);
1194 Post\Media::insertFromRelevantUrl($item['uri-id'], $item['raw-body'], $item['body'], $author['network'] ?? '');
1196 // Check for hashtags in the body and repair or add hashtag links
1197 $item['body'] = self::setHashtags($item['body']);
1199 $item['language'] = self::getLanguage($item);
1201 $notify_type = Delivery::POST;
1203 // Filling item related side tables
1204 if (!empty($item['attach'])) {
1205 Post\Media::insertFromAttachment($item['uri-id'], $item['attach']);
1208 if (empty($item['event-id'])) {
1209 unset($item['event-id']);
1211 $ev = Event::fromBBCode($item['body']);
1212 if ((!empty($ev['desc']) || !empty($ev['summary'])) && !empty($ev['start'])) {
1213 Logger::info('Event found.');
1214 $ev['cid'] = $item['contact-id'];
1215 $ev['uid'] = $item['uid'];
1216 $ev['uri'] = $item['uri'];
1217 $ev['edited'] = $item['edited'];
1218 $ev['private'] = $item['private'];
1219 $ev['guid'] = $item['guid'];
1220 $ev['plink'] = $item['plink'];
1221 $ev['network'] = $item['network'];
1222 $ev['protocol'] = $item['protocol'] ?? Conversation::PARCEL_UNKNOWN;
1223 $ev['direction'] = $item['direction'] ?? Conversation::UNKNOWN;
1224 $ev['source'] = $item['source'] ?? '';
1226 $event = DBA::selectFirst('event', ['id'], ['uri' => $item['uri'], 'uid' => $item['uid']]);
1227 if (DBA::isResult($event)) {
1228 $ev['id'] = $event['id'];
1231 $event_id = Event::store($ev);
1232 $item = Event::getItemArrayForImportedId($event_id, $item);
1234 Logger::info('Event was stored', ['id' => $event_id]);
1238 if (empty($item['causer-id'])) {
1239 unset($item['causer-id']);
1242 if (in_array($item['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN])) {
1243 $content_warning = BBCode::getAbstract($item['body'], Protocol::ACTIVITYPUB);
1244 if (!empty($content_warning) && empty($item['content-warning'])) {
1245 $item['content-warning'] = BBCode::toPlaintext($content_warning);
1249 Post::insert($item['uri-id'], $item);
1251 if ($item['gravity'] == self::GRAVITY_PARENT) {
1252 Post\Thread::insert($item['uri-id'], $item);
1255 if (!in_array($item['verb'], self::ACTIVITIES)) {
1256 Post\Content::insert($item['uri-id'], $item);
1259 // Create Diaspora signature
1260 if ($item['origin'] && empty($item['diaspora_signed_text']) && ($item['gravity'] != self::GRAVITY_PARENT)) {
1261 $signed = Diaspora::createCommentSignature($item);
1262 if (!empty($signed)) {
1263 $item['diaspora_signed_text'] = json_encode($signed);
1267 if (!empty($item['diaspora_signed_text'])) {
1268 DBA::replace('diaspora-interaction', ['uri-id' => $item['uri-id'], 'interaction' => $item['diaspora_signed_text']]);
1271 // Attached file links
1272 if (!empty($item['file'])) {
1273 Post\Category::storeTextByURIId($item['uri-id'], $item['uid'], $item['file']);
1276 // Delivery relevant data
1277 $delivery_data = Post\DeliveryData::extractFields($item);
1279 if (!empty($item['origin']) || !empty($item['wall']) || !empty($delivery_data['postopts']) || !empty($delivery_data['inform'])) {
1280 Post\DeliveryData::insert($item['uri-id'], $delivery_data);
1283 // Store tags from the body if this hadn't been handled previously in the protocol classes
1284 if (!Tag::existsForPost($item['uri-id'])) {
1285 Tag::storeFromBody($item['uri-id'], $item['body']);
1288 $condition = ['uri-id' => $item['uri-id'], 'uid' => $item['uid']];
1289 if (Post::exists($condition)) {
1290 Logger::notice('Item is already inserted - aborting', $condition);
1294 $post_user_id = Post\User::insert($item['uri-id'], $item['uid'], $item);
1295 if (!$post_user_id) {
1296 Logger::notice('Post-User is already inserted - aborting', ['uid' => $item['uid'], 'uri-id' => $item['uri-id']]);
1300 if ($item['gravity'] == self::GRAVITY_PARENT) {
1301 $item['post-user-id'] = $post_user_id;
1302 Post\ThreadUser::insert($item['uri-id'], $item['uid'], $item);
1305 Logger::notice('created item', ['post-id' => $post_user_id, 'uid' => $item['uid'], 'network' => $item['network'], 'uri-id' => $item['uri-id'], 'guid' => $item['guid']]);
1307 $posted_item = Post::selectFirst(self::ITEM_FIELDLIST, ['post-user-id' => $post_user_id]);
1308 if (!DBA::isResult($posted_item)) {
1309 // On failure store the data into a spool file so that the "SpoolPost" worker can try again later.
1310 Logger::warning('Could not store item. it will be spooled', ['id' => $post_user_id]);
1311 self::spool($orig_item);
1315 // update the commented timestamp on the parent
1316 if (DI::config()->get('system', 'like_no_comment')) {
1317 // Update when it is a comment
1318 $update_commented = in_array($posted_item['gravity'], [self::GRAVITY_PARENT, self::GRAVITY_COMMENT]);
1320 // Update when it isn't a follow or tag verb
1321 $update_commented = !in_array($posted_item['verb'], [Activity::FOLLOW, Activity::TAG]);
1324 if ($update_commented) {
1325 $fields = ['commented' => DateTimeFormat::utcNow(), 'changed' => DateTimeFormat::utcNow()];
1327 $fields = ['changed' => DateTimeFormat::utcNow()];
1330 Post::update($fields, ['uri-id' => $posted_item['parent-uri-id'], 'uid' => $posted_item['uid']]);
1332 // In that function we check if this is a forum post. Additionally we delete the item under certain circumstances
1333 if (self::tagDeliver($posted_item['uid'], $post_user_id)) {
1334 // Get the user information for the logging
1335 $user = User::getById($uid);
1337 Logger::notice('Item had been deleted', ['id' => $post_user_id, 'user' => $uid, 'account-type' => $user['account-type']]);
1342 if (!\Friendica\Content\Feature::isEnabled($posted_item['uid'], 'explicit_mentions') && ($posted_item['gravity'] == self::GRAVITY_COMMENT)) {
1343 Tag::createImplicitMentions($posted_item['uri-id'], $posted_item['thr-parent-id']);
1345 Hook::callAll('post_local_end', $posted_item);
1347 Hook::callAll('post_remote_end', $posted_item);
1350 if ($posted_item['gravity'] === self::GRAVITY_PARENT) {
1351 self::addShadow($post_user_id);
1353 self::addShadowPost($post_user_id);
1356 self::updateContact($posted_item);
1358 Post\UserNotification::setNotification($posted_item['uri-id'], $posted_item['uid']);
1360 // Distribute items to users who subscribed to their tags
1361 self::distributeByTags($posted_item);
1363 // Automatically reshare the item if the "remote_self" option is selected
1364 self::autoReshare($posted_item);
1366 $transmit = $notify || ($posted_item['visible'] && ($parent_origin || $posted_item['origin']));
1369 // Don't relay participation messages
1370 if (($posted_item['verb'] == Activity::FOLLOW) &&
1371 (!$posted_item['origin'] || ($posted_item['author-id'] != Contact::getPublicIdByUserId($uid)))) {
1372 Logger::info('Participation messages will not be relayed', ['item' => $posted_item['id'], 'uri' => $posted_item['uri'], 'verb' => $posted_item['verb']]);
1377 if (!empty($source) && ($transmit || DI::config()->get('debug', 'store_source'))) {
1378 Post\Activity::insert($item['uri-id'], $source);
1382 Worker::add(['priority' => $priority, 'dont_fork' => true], 'Notifier', $notify_type, (int)$posted_item['uri-id'], (int)$posted_item['uid']);
1385 // Fill the cache with the rendered content.
1386 if (in_array($posted_item['gravity'], [self::GRAVITY_PARENT, self::GRAVITY_COMMENT]) && ($posted_item['uid'] == 0)) {
1387 self::updateDisplayCache($posted_item['uri-id']);
1390 return $post_user_id;
1394 * Fetch the post reason for a given item array
1396 * @param array $item
1400 public static function getPostReason(array $item): int
1402 $actor = ($item['gravity'] == self::GRAVITY_PARENT) ? $item['owner-id'] : $item['author-id'];
1403 if (empty($item['origin']) && ($item['uid'] != 0) && Contact::isSharing($actor, $item['uid'])) {
1404 return self::PR_FOLLOWER;
1407 if (!empty($item['origin']) && empty($item['post-reason'])) {
1408 return self::PR_LOCAL;
1411 return $item['post-reason'] ?? self::PR_NONE;
1415 * Update the display cache
1417 * @param integer $uri_id
1420 public static function updateDisplayCache(int $uri_id)
1422 $item = Post::selectFirst(self::DISPLAY_FIELDLIST, ['uri-id' => $uri_id]);
1423 self::prepareBody($item, false, false, true);
1427 * Change the owner of a parent item if it had been shared by a forum
1429 * (public) forum posts in the new format consist of the regular post by the author
1430 * followed by an announce message sent from the forum account.
1431 * Changing the owner helps in grouping forum posts.
1433 * @param array $item
1436 private static function setOwnerforResharedItem(array $item)
1438 $parent = Post::selectFirst(['id', 'causer-id', 'owner-id', 'author-id', 'author-link', 'origin', 'post-reason'],
1439 ['uri-id' => $item['thr-parent-id'], 'uid' => $item['uid']]);
1440 if (!DBA::isResult($parent)) {
1441 Logger::error('Parent not found', ['uri-id' => $item['thr-parent-id'], 'uid' => $item['uid']]);
1445 $author = Contact::selectFirst(['url', 'contact-type', 'network'], ['id' => $item['author-id']]);
1446 if (!DBA::isResult($author)) {
1447 Logger::error('Author not found', ['id' => $item['author-id']]);
1451 $self_contact = Contact::selectFirst(['id'], ['uid' => $item['uid'], 'self' => true]);
1452 $self = !empty($self_contact) ? $self_contact['id'] : 0;
1454 $cid = Contact::getIdForURL($author['url'], $item['uid']);
1455 if (empty($cid) || (!Contact::isSharing($cid, $item['uid']) && ($cid != $self))) {
1456 Logger::info('The resharer is not a following contact: quit', ['resharer' => $author['url'], 'uid' => $item['uid'], 'cid' => $cid]);
1460 if ($author['contact-type'] != Contact::TYPE_COMMUNITY) {
1461 if ($parent['post-reason'] == self::PR_ANNOUNCEMENT) {
1462 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']]);
1466 if (Contact::isSharing($parent['owner-id'], $item['uid'])) {
1467 Logger::info('The resharer is no forum: quit', ['resharer' => $item['author-id'], 'owner' => $parent['owner-id'], 'author' => $parent['author-id'], 'uid' => $item['uid']]);
1472 self::update(['post-reason' => self::PR_ANNOUNCEMENT, 'causer-id' => $item['author-id']], ['id' => $parent['id']]);
1473 Logger::info('Set announcement post-reason', ['uri-id' => $item['uri-id'], 'thr-parent-id' => $item['thr-parent-id'], 'uid' => $item['uid']]);
1477 * Distribute the given item to users who subscribed to their tags
1479 * @param array $item Processed item
1481 private static function distributeByTags(array $item)
1483 if (($item['uid'] != 0) || ($item['gravity'] != self::GRAVITY_PARENT) || !in_array($item['network'], Protocol::FEDERATED)) {
1487 $uids = Tag::getUIDListByURIId($item['uri-id']);
1488 foreach ($uids as $uid) {
1489 $stored = self::storeForUserByUriId($item['uri-id'], $uid, ['post-reason' => self::PR_TAG]);
1490 Logger::info('Stored item for users', ['uri-id' => $item['uri-id'], 'uid' => $uid, 'stored' => $stored]);
1495 * Distributes public items to the receivers
1497 * @param integer $itemid Item ID that should be added
1498 * @param string $signed_text Original text (for Diaspora signatures), JSON encoded.
1499 * @throws \Exception
1501 public static function distribute(int $itemid, string $signed_text = '')
1503 $condition = ["`id` IN (SELECT `parent` FROM `post-user-view` WHERE `id` = ?)", $itemid];
1504 $parent = Post::selectFirst(['owner-id'], $condition);
1505 if (!DBA::isResult($parent)) {
1506 Logger::warning('Item not found', ['condition' => $condition]);
1510 // Only distribute public items from native networks
1511 $condition = ['id' => $itemid, 'uid' => 0,
1512 'network' => array_merge(Protocol::FEDERATED ,['']),
1513 'visible' => true, 'deleted' => false, 'private' => [self::PUBLIC, self::UNLISTED]];
1514 $item = Post::selectFirst(array_merge(self::ITEM_FIELDLIST, ['protocol']), $condition);
1515 if (!DBA::isResult($item)) {
1516 Logger::warning('Item not found', ['condition' => $condition]);
1520 $origin = $item['origin'];
1524 /// @todo add a field "pcid" in the contact table that referrs to the public contact id.
1525 $owner = DBA::selectFirst('contact', ['url', 'nurl', 'alias'], ['id' => $parent['owner-id']]);
1526 if (!DBA::isResult($owner)) {
1530 $condition = ['nurl' => $owner['nurl'], 'rel' => [Contact::SHARING, Contact::FRIEND]];
1531 $contacts = DBA::select('contact', ['uid'], $condition);
1532 while ($contact = DBA::fetch($contacts)) {
1533 if ($contact['uid'] == 0) {
1537 $users[$contact['uid']] = $contact['uid'];
1539 DBA::close($contacts);
1541 $condition = ['alias' => $owner['url'], 'rel' => [Contact::SHARING, Contact::FRIEND]];
1542 $contacts = DBA::select('contact', ['uid'], $condition);
1543 while ($contact = DBA::fetch($contacts)) {
1544 if ($contact['uid'] == 0) {
1548 $users[$contact['uid']] = $contact['uid'];
1550 DBA::close($contacts);
1552 if (!empty($owner['alias'])) {
1553 $condition = ['nurl' => Strings::normaliseLink($owner['alias']), 'rel' => [Contact::SHARING, Contact::FRIEND]];
1554 $contacts = DBA::select('contact', ['uid'], $condition);
1555 while ($contact = DBA::fetch($contacts)) {
1556 if ($contact['uid'] == 0) {
1560 $users[$contact['uid']] = $contact['uid'];
1562 DBA::close($contacts);
1567 if ($item['uri-id'] != $item['parent-uri-id']) {
1568 $parents = Post::select(['uid', 'origin'], ["`uri-id` = ? AND `uid` != 0", $item['parent-uri-id']]);
1569 while ($parent = Post::fetch($parents)) {
1570 $users[$parent['uid']] = $parent['uid'];
1571 if ($parent['origin'] && !$origin) {
1572 $origin_uid = $parent['uid'];
1575 DBA::close($parents);
1578 foreach ($users as $uid) {
1579 if ($origin_uid == $uid) {
1580 $item['diaspora_signed_text'] = $signed_text;
1582 $item['post-reason'] = self::PR_DISTRIBUTE;
1583 self::storeForUser($item, $uid);
1588 * Store a public item defined by their URI-ID for the given users
1590 * @param integer $uri_id URI-ID of the given item
1591 * @param integer $uid The user that will receive the item entry
1592 * @param array $fields Additional fields to be stored
1593 * @param integer $source_uid User id of the source post
1594 * @return integer stored item id
1596 public static function storeForUserByUriId(int $uri_id, int $uid, array $fields = [], int $source_uid = 0): int
1598 if ($uid == $source_uid) {
1599 Logger::warning('target UID must not be be equal to the source UID', ['uri-id' => $uri_id, 'uid' => $uid]);
1603 $item = Post::selectFirst(array_merge(self::ITEM_FIELDLIST, ['protocol']), ['uri-id' => $uri_id, 'uid' => $source_uid]);
1604 if (!DBA::isResult($item)) {
1605 Logger::warning('Item could not be fetched', ['uri-id' => $uri_id, 'uid' => $source_uid]);
1609 if (($uid != 0) && ($item['gravity'] == self::GRAVITY_PARENT)) {
1610 $owner = User::getOwnerDataById($uid);
1611 if (($owner['contact-type'] == User::ACCOUNT_TYPE_COMMUNITY) && !Tag::isMentioned($uri_id, $owner['url'])) {
1612 Logger::info('Target user is a forum but is not mentioned here, thread will not be stored', ['uid' => $uid, 'uri-id' => $uri_id]);
1617 if (($source_uid == 0) && (($item['private'] == self::PRIVATE) || !in_array($item['network'], Protocol::FEDERATED))) {
1618 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']]);
1622 $item['post-reason'] = self::PR_STORED;
1624 $item = array_merge($item, $fields);
1626 if (($uid != 0) && Contact::isSharing(($item['gravity'] == Item::GRAVITY_PARENT) ? $item['owner-id'] : $item['author-id'], $uid)) {
1627 $item['post-reason'] = self::PR_FOLLOWER;
1630 $is_reshare = ($item['gravity'] == self::GRAVITY_ACTIVITY) && ($item['verb'] == Activity::ANNOUNCE);
1632 if (($uid != 0) && (($item['gravity'] == self::GRAVITY_PARENT) || $is_reshare) &&
1633 DI::pConfig()->get($uid, 'system', 'accept_only_sharer') == self::COMPLETION_NONE &&
1634 !in_array($item['post-reason'], [self::PR_FOLLOWER, self::PR_TAG, self::PR_TO, self::PR_CC])) {
1635 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']]);
1639 $causer = $item['causer-id'] ?: $item['author-id'];
1641 if (($uri_id != $item['parent-uri-id']) && ($item['gravity'] == self::GRAVITY_COMMENT) && !Post::exists(['uri-id' => $item['parent-uri-id'], 'uid' => $uid])) {
1642 if (!self::fetchParent($item['parent-uri-id'], $uid, $causer)) {
1643 Logger::info('Parent post had not been added', ['uri-id' => $item['parent-uri-id'], 'uid' => $uid, 'causer' => $causer]);
1646 Logger::info('Fetched parent post', ['uri-id' => $item['parent-uri-id'], 'uid' => $uid, 'causer' => $causer]);
1647 } elseif (($uri_id != $item['thr-parent-id']) && $is_reshare && !Post::exists(['uri-id' => $item['thr-parent-id'], 'uid' => $uid])) {
1648 if (!self::fetchParent($item['thr-parent-id'], $uid, $causer)) {
1649 Logger::info('Thread parent had not been added', ['uri-id' => $item['thr-parent-id'], 'uid' => $uid, 'causer' => $causer]);
1652 Logger::info('Fetched thread parent', ['uri-id' => $item['thr-parent-id'], 'uid' => $uid, 'causer' => $causer]);
1655 $stored = self::storeForUser($item, $uid);
1656 Logger::info('Item stored for user', ['uri-id' => $item['uri-id'], 'uid' => $uid, 'causer' => $causer, 'source-uid' => $source_uid, 'stored' => $stored]);
1661 * Fetch the parent with the given uri-id
1663 * @param integer $uri_id
1664 * @param integer $uid
1665 * @param integer $causer
1669 private static function fetchParent(int $uri_id, int $uid, int $causer): int
1671 // Fetch the origin user for the post
1672 $origin_uid = self::GetOriginUidForUriId($uri_id, $uid);
1673 if (is_null($origin_uid)) {
1674 Logger::info('Origin item was not found', ['uid' => $uid, 'uri-id' => $uri_id]);
1678 return self::storeForUserByUriId($uri_id, $uid, ['causer-id' => $causer, 'post-reason' => self::PR_FETCHED], $origin_uid);
1682 * Returns the origin uid of a post if the given user is allowed to see it.
1688 private static function GetOriginUidForUriId(int $uriid, int $uid)
1690 if (Post::exists(['uri-id' => $uriid, 'uid' => $uid])) {
1694 $post = Post::selectFirst(['uid', 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid', 'private'], ['uri-id' => $uriid, 'origin' => true]);
1695 if (!empty($post)) {
1696 if (in_array($post['private'], [Item::PUBLIC, Item::UNLISTED])) {
1697 return $post['uid'];
1700 $pcid = Contact::getPublicIdByUserId($uid);
1705 foreach (Item::enumeratePermissions($post, true) as $receiver) {
1706 if ($receiver == $pcid) {
1707 return $post['uid'];
1714 if (Post::exists(['uri-id' => $uriid, 'uid' => 0])) {
1718 // When the post belongs to a a forum then all forum users are allowed to access it
1719 foreach (Tag::getByURIId($uriid, [Tag::MENTION, Tag::EXCLUSIVE_MENTION]) as $tag) {
1720 if (DBA::exists('contact', ['uid' => $uid, 'nurl' => Strings::normaliseLink($tag['url']), 'contact-type' => Contact::TYPE_COMMUNITY])) {
1721 $target_uid = User::getIdForURL($tag['url']);
1722 if (!empty($target_uid)) {
1732 * Store a public item array for the given users
1734 * @param array $item The item entry that will be stored
1735 * @param integer $uid The user that will receive the item entry
1736 * @return integer stored item id
1737 * @throws \Exception
1739 private static function storeForUser(array $item, int $uid): int
1741 $post = Post::selectFirst(['id'], ['uri-id' => $item['uri-id'], 'uid' => $uid]);
1742 if (!empty($post['id'])) {
1743 if (!empty($item['event-id'])) {
1744 $event_post = Post::selectFirst(['event-id'], ['uri-id' => $item['uri-id'], 'uid' => $uid]);
1745 if (!empty($event_post['event-id'])) {
1746 $event = DBA::selectFirst('event', ['edited', 'start', 'finish', 'summary', 'desc', 'location', 'nofinish', 'adjust'], ['id' => $item['event-id']]);
1747 if (!empty($event)) {
1748 // We aren't using "Event::store" here, since we don't want to trigger any further action
1749 $ret = DBA::update('event', $event, ['id' => $event_post['event-id']]);
1750 Logger::info('Event updated', ['uid' => $uid, 'source-event' => $item['event-id'], 'target-event' => $event_post['event-id'], 'ret' => $ret]);
1754 Logger::info('Item already exists', ['uri-id' => $item['uri-id'], 'uid' => $uid, 'id' => $post['id']]);
1758 // Data from the "post-user" table
1760 unset($item['mention']);
1761 unset($item['starred']);
1762 unset($item['unseen']);
1763 unset($item['psid']);
1764 unset($item['pinned']);
1765 unset($item['ignored']);
1766 unset($item['pubmail']);
1767 unset($item['event-id']);
1768 unset($item['hidden']);
1769 unset($item['notification-type']);
1771 // Data from the "post-delivery-data" table
1772 unset($item['postopts']);
1773 unset($item['inform']);
1775 $item['uid'] = $uid;
1776 $item['origin'] = 0;
1779 $item['contact-id'] = self::contactId($item);
1782 if ($item['gravity'] == self::GRAVITY_PARENT) {
1783 $contact = DBA::selectFirst('contact', [], ['id' => $item['contact-id'], 'self' => false]);
1784 if (DBA::isResult($contact)) {
1785 $notify = self::isRemoteSelf($contact, $item);
1789 $distributed = self::insert($item, $notify);
1791 if (!$distributed) {
1792 Logger::info("Distributed item wasn't stored", ['uri-id' => $item['uri-id'], 'user' => $uid]);
1794 Logger::info('Distributed item was stored', ['uri-id' => $item['uri-id'], 'user' => $uid, 'stored' => $distributed]);
1796 return $distributed;
1800 * Add a shadow entry for a given item id that is a thread starter
1802 * We store every public item entry additionally with the user id "0".
1803 * This is used for the community page and for the search.
1804 * It is planned that in the future we will store public item entries only once.
1806 * @param integer $itemid Item ID that should be added
1807 * @throws \Exception
1809 private static function addShadow(int $itemid)
1811 $fields = ['uid', 'private', 'visible', 'deleted', 'network', 'uri-id'];
1812 $condition = ['id' => $itemid, 'gravity' => self::GRAVITY_PARENT];
1813 $item = Post::selectFirst($fields, $condition);
1815 if (!DBA::isResult($item)) {
1819 // is it already a copy?
1820 if (($itemid == 0) || ($item['uid'] == 0)) {
1824 // Is it a visible public post?
1825 if (!$item["visible"] || $item["deleted"] || ($item["private"] == self::PRIVATE)) {
1829 // is it an entry from a connector? Only add an entry for natively connected networks
1830 if (!in_array($item["network"], array_merge(Protocol::FEDERATED ,['']))) {
1834 if (Post::exists(['uri-id' => $item['uri-id'], 'uid' => 0])) {
1838 $item = Post::selectFirst(array_merge(self::ITEM_FIELDLIST, ['protocol']), ['id' => $itemid]);
1840 if (DBA::isResult($item)) {
1841 // Preparing public shadow (removing user specific data)
1844 unset($item['parent']);
1845 unset($item['wall']);
1846 unset($item['mention']);
1847 unset($item['origin']);
1848 unset($item['starred']);
1849 unset($item['postopts']);
1850 unset($item['inform']);
1851 unset($item['post-reason']);
1852 if ($item['uri-id'] == $item['parent-uri-id']) {
1853 $item['contact-id'] = $item['owner-id'];
1855 $item['contact-id'] = $item['author-id'];
1858 $public_shadow = self::insert($item);
1860 Logger::info('Stored public shadow', ['thread' => $itemid, 'id' => $public_shadow]);
1865 * Add a shadow entry for a given item id that is a comment
1867 * This function does the same like the function above - but for comments
1869 * @param integer $itemid Item ID that should be added
1870 * @throws \Exception
1872 private static function addShadowPost(int $itemid)
1874 $item = Post::selectFirst(array_merge(self::ITEM_FIELDLIST, ['protocol']), ['id' => $itemid]);
1875 if (!DBA::isResult($item)) {
1879 // Is it a toplevel post?
1880 if ($item['gravity'] == self::GRAVITY_PARENT) {
1881 self::addShadow($itemid);
1885 // Is this a shadow entry?
1886 if ($item['uid'] == 0) {
1890 // Is there a shadow parent?
1891 if (!Post::exists(['uri-id' => $item['parent-uri-id'], 'uid' => 0])) {
1895 // Is there already a shadow entry?
1896 if (Post::exists(['uri-id' => $item['uri-id'], 'uid' => 0])) {
1900 // Save "origin" and "parent" state
1901 $origin = $item['origin'];
1902 $parent = $item['parent'];
1904 // Preparing public shadow (removing user specific data)
1907 unset($item['parent']);
1908 unset($item['wall']);
1909 unset($item['mention']);
1910 unset($item['origin']);
1911 unset($item['starred']);
1912 unset($item['postopts']);
1913 unset($item['inform']);
1914 unset($item['post-reason']);
1915 $item['contact-id'] = Contact::getIdForURL($item['author-link']);
1917 $public_shadow = self::insert($item);
1919 Logger::info('Stored public shadow', ['uri-id' => $item['uri-id'], 'id' => $public_shadow]);
1921 // If this was a comment to a Diaspora post we don't get our comment back.
1922 // This means that we have to distribute the comment by ourselves.
1923 if ($origin && Post::exists(['id' => $parent, 'network' => Protocol::DIASPORA])) {
1924 self::distribute($public_shadow);
1929 * Adds a language specification in a "language" element of given $arr.
1930 * Expects "body" element to exist in $arr.
1932 * @param array $item
1933 * @return string detected language
1934 * @throws \Text_LanguageDetect_Exception
1936 private static function getLanguage(array $item): string
1938 if (!empty($item['language'])) {
1939 return $item['language'];
1942 if (!in_array($item['gravity'], [self::GRAVITY_PARENT, self::GRAVITY_COMMENT]) || empty($item['body'])) {
1946 $languages = self::getLanguageArray(trim($item['title'] . "\n" . $item['body']), 3);
1947 if (empty($languages)) {
1951 return json_encode($languages);
1955 * Get a language array from a given text
1957 * @param string $body
1958 * @param integer $count
1961 public static function getLanguageArray(string $body, int $count): array
1963 // Convert attachments to links
1964 $naked_body = BBCode::removeAttachment($body);
1965 if (empty($naked_body)) {
1969 // Remove links and pictures
1970 $naked_body = BBCode::removeLinks($naked_body);
1972 // Convert the title and the body to plain text
1973 $naked_body = BBCode::toPlaintext($naked_body);
1975 // Remove possibly remaining links
1976 $naked_body = preg_replace(Strings::autoLinkRegEx(), '', $naked_body);
1978 if (empty($naked_body)) {
1982 $naked_body = self::getDominantLanguage($naked_body);
1984 $availableLanguages = DI::l10n()->getAvailableLanguages();
1985 // See https://github.com/friendica/friendica/issues/10511
1986 // Persian is manually added to language detection until a persian translation is provided for the interface, at
1987 // which point it will be automatically available through `getAvailableLanguages()` and this should be removed.
1988 $availableLanguages['fa'] = 'fa';
1990 $ld = new Language(array_keys($availableLanguages));
1991 return $ld->detect($naked_body)->limit(0, $count)->close() ?: [];
1995 * Check if latin or non latin are dominant in the body and only return the dominant one
1997 * @param string $body
2000 private static function getDominantLanguage(string $body): string
2004 for ($i = 0; $i < mb_strlen($body); $i++) {
2005 $character = mb_substr($body, $i, 1);
2006 $ord = mb_ord($character);
2008 // We add the most common characters to both strings.
2009 if (($ord <= 64) || ($ord >= 91 && $ord <= 96) || ($ord >= 123 && $ord <= 191) || in_array($ord, [215, 247]) || ($ord >= 697 && $ord <= 735) || ($ord > 65535)) {
2010 $latin .= $character;
2011 $non_latin .= $character;
2012 } elseif ($ord < 768) {
2013 $latin .= $character;
2015 $non_latin .= $character;
2018 return (mb_strlen($latin) > mb_strlen($non_latin)) ? $latin : $non_latin;
2021 public static function getLanguageMessage(array $item): string
2023 $iso639 = new \Matriphe\ISO639\ISO639;
2025 $used_languages = '';
2026 foreach (json_decode($item['language'], true) as $language => $reliability) {
2027 $used_languages .= $iso639->languageByCode1($language) . ' (' . $language . "): " . number_format($reliability, 5) . '\n';
2029 $used_languages = DI::l10n()->t('Detected languages in this post:\n%s', $used_languages);
2030 return $used_languages;
2034 * Creates an unique guid out of a given uri.
2035 * This function is used for messages outside the fediverse (Connector posts, feeds, Mails, ...)
2036 * Posts that are created on this system are using System::createUUID.
2037 * Received ActivityPub posts are using Processor::getGUIDByURL.
2039 * @param string $uri uri of an item entry
2040 * @param string|null $host hostname for the GUID prefix
2041 * @return string Unique guid
2043 public static function guidFromUri(string $uri, string $host = null): string
2045 // Our regular guid routine is using this kind of prefix as well
2046 // We have to avoid that different routines could accidentally create the same value
2047 $parsed = parse_url($uri);
2049 // Remove the scheme to make sure that "https" and "http" doesn't make a difference
2050 unset($parsed['scheme']);
2052 // Glue it together to be able to make a hash from it
2053 $host_id = implode('/', $parsed);
2055 // Use a mixture of several hashes to provide some GUID like experience
2056 return hash('crc32', $host) . '-'. hash('joaat', $host_id) . '-'. hash('fnv164', $host_id);
2060 * generate an unique URI
2062 * @param string $guid An existing GUID (Otherwise it will be generated)
2065 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2067 public static function newURI(string $guid = ''): string
2070 $guid = System::createUUID();
2073 return DI::baseUrl()->get() . '/objects/' . $guid;
2077 * Set "success_update" and "last-item" to the date of the last time we heard from this contact
2079 * This can be used to filter for inactive contacts.
2080 * Only do this for public postings to avoid privacy problems, since poco data is public.
2081 * Don't set this value if it isn't from the owner (could be an author that we don't know)
2083 * @param array $arr Contains the just posted item record
2084 * @throws \Exception
2086 private static function updateContact(array $arr)
2088 // Unarchive the author
2089 $contact = DBA::selectFirst('contact', [], ['id' => $arr["author-id"]]);
2090 if (DBA::isResult($contact)) {
2091 Contact::unmarkForArchival($contact);
2094 // Unarchive the contact if it's not our own contact
2095 $contact = DBA::selectFirst('contact', [], ['id' => $arr["contact-id"], 'self' => false]);
2096 if (DBA::isResult($contact)) {
2097 Contact::unmarkForArchival($contact);
2100 /// @todo On private posts we could obfuscate the date
2101 $update = ($arr['private'] != self::PRIVATE) || in_array($arr['network'], Protocol::FEDERATED);
2103 // Is it a forum? Then we don't care about the rules from above
2104 if (!$update && in_array($arr["network"], [Protocol::ACTIVITYPUB, Protocol::DFRN]) && ($arr["parent-uri-id"] === $arr["uri-id"])) {
2105 if (DBA::exists('contact', ['id' => $arr['contact-id'], 'forum' => true])) {
2111 // The "self" contact id is used (for example in the connectors) when the contact is unknown
2112 // So we have to ensure to only update the last item when it had been our own post,
2113 // or it had been done by a "regular" contact.
2114 if (!empty($arr['wall'])) {
2115 $condition = ['id' => $arr['contact-id']];
2117 $condition = ['id' => $arr['contact-id'], 'self' => false];
2119 Contact::update(['failed' => false, 'local-data' => true, 'success_update' => $arr['received'], 'last-item' => $arr['received']], $condition);
2121 // Now do the same for the system wide contacts with uid=0
2122 if ($arr['private'] != self::PRIVATE) {
2123 Contact::update(['failed' => false, 'local-data' => true, 'success_update' => $arr['received'], 'last-item' => $arr['received']],
2124 ['id' => $arr['owner-id']]);
2126 if ($arr['owner-id'] != $arr['author-id']) {
2127 Contact::update(['failed' => false, 'local-data' => true, 'success_update' => $arr['received'], 'last-item' => $arr['received']],
2128 ['id' => $arr['author-id']]);
2133 public static function setHashtags(string $body): string
2135 $body = BBCode::performWithEscapedTags($body, ['noparse', 'pre', 'code', 'img'], function ($body) {
2136 $tags = BBCode::getTags($body);
2139 if (!count($tags)) {
2143 // This sorting is important when there are hashtags that are part of other hashtags
2144 // Otherwise there could be problems with hashtags like #test and #test2
2145 // Because of this we are sorting from the longest to the shortest tag.
2146 usort($tags, function ($a, $b) {
2147 return strlen($b) <=> strlen($a);
2150 $URLSearchString = "^\[\]";
2152 // All hashtags should point to the home server if "local_tags" is activated
2153 if (DI::config()->get('system', 'local_tags')) {
2154 $body = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
2155 "#[url=" . DI::baseUrl() . "/search?tag=$2]$2[/url]", $body);
2158 // mask hashtags inside of url, bookmarks and attachments to avoid urls in urls
2159 $body = preg_replace_callback("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
2161 return ("[url=" . str_replace("#", "#", $match[1]) . "]" . str_replace("#", "#", $match[2]) . "[/url]");
2164 $body = preg_replace_callback("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism",
2166 return ("[bookmark=" . str_replace("#", "#", $match[1]) . "]" . str_replace("#", "#", $match[2]) . "[/bookmark]");
2169 $body = preg_replace_callback("/\[attachment (.*?)\](.*?)\[\/attachment\]/ism",
2171 return ("[attachment " . str_replace("#", "#", $match[1]) . "]" . $match[2] . "[/attachment]");
2174 // Repair recursive urls
2175 $body = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
2178 foreach ($tags as $tag) {
2179 if ((strpos($tag, '#') !== 0) || strpos($tag, '[url=') || strlen($tag) < 2 || $tag[1] == '#') {
2183 $basetag = str_replace('_', ' ', substr($tag, 1));
2184 $newtag = '#[url=' . DI::baseUrl() . '/search?tag=' . $basetag . ']' . $basetag . '[/url]';
2186 $body = str_replace($tag, $newtag, $body);
2189 // Convert back the masked hashtags
2190 $body = str_replace("#", "#", $body);
2199 * look for mention tags and setup a second delivery chain for forum/community posts if appropriate
2202 * @param int $item_id
2203 * @return boolean true if item was deleted, else false
2204 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2205 * @throws \ImagickException
2207 private static function tagDeliver(int $uid, int $item_id): bool
2211 $owner = User::getOwnerDataById($uid);
2212 if (!DBA::isResult($owner)) {
2213 Logger::warning('User not found, quitting here.', ['uid' => $uid]);
2217 if ($owner['contact-type'] != User::ACCOUNT_TYPE_COMMUNITY) {
2218 Logger::debug('Owner is no community, quitting here.', ['uid' => $uid, 'id' => $item_id]);
2222 $item = Post::selectFirst(self::ITEM_FIELDLIST, ['id' => $item_id, 'gravity' => [self::GRAVITY_PARENT, self::GRAVITY_COMMENT], 'origin' => false]);
2223 if (!DBA::isResult($item)) {
2224 Logger::debug('Post is an activity or origin or not found at all, quitting here.', ['id' => $item_id]);
2228 if ($item['gravity'] == self::GRAVITY_PARENT) {
2229 if (Tag::isMentioned($item['uri-id'], $owner['url'])) {
2230 Logger::info('Mention found in tag.', ['uri' => $item['uri'], 'uid' => $uid, 'id' => $item_id, 'uri-id' => $item['uri-id'], 'guid' => $item['guid']]);
2232 Logger::info('Top-level post without mention is deleted.', ['uri' => $item['uri'], $uid, 'id' => $item_id, 'uri-id' => $item['uri-id'], 'guid' => $item['guid']]);
2233 Post\User::delete(['uri-id' => $item['uri-id'], 'uid' => $item['uid']]);
2237 $arr = ['item' => $item, 'user' => $owner];
2239 Hook::callAll('tagged', $arr);
2241 if (Tag::isMentioned($item['parent-uri-id'], $owner['url'])) {
2242 Logger::info('Mention found in parent tag.', ['uri' => $item['uri'], 'uid' => $uid, 'id' => $item_id, 'uri-id' => $item['uri-id'], 'guid' => $item['guid']]);
2244 Logger::debug('No mentions found in parent, quitting here.', ['id' => $item_id, 'uri-id' => $item['uri-id'], 'guid' => $item['guid']]);
2249 Logger::info('Community post will be distributed', ['uri' => $item['uri'], 'uid' => $uid, 'id' => $item_id, 'uri-id' => $item['uri-id'], 'guid' => $item['guid']]);
2251 if ($owner['page-flags'] == User::PAGE_FLAGS_PRVGROUP) {
2253 $allow_gid = '<' . Group::FOLLOWERS . '>';
2256 self::performActivity($item['id'], 'announce', $uid, $allow_cid, $allow_gid, $deny_cid, $deny_gid);
2258 self::performActivity($item['id'], 'announce', $uid);
2261 Logger::info('Community post had been distributed', ['uri' => $item['uri'], 'uid' => $uid, 'id' => $item_id, 'uri-id' => $item['uri-id'], 'guid' => $item['guid']]);
2266 * Automatically reshare the item if the "remote_self" option is selected
2268 * @param array $item
2271 private static function autoReshare(array $item)
2273 if ($item['gravity'] != self::GRAVITY_PARENT) {
2277 $cdata = Contact::getPublicAndUserContactID($item['author-id'], $item['uid']);
2278 if (empty($cdata['user']) || ($cdata['user'] != $item['contact-id'])) {
2282 if (!DBA::exists('contact', ['id' => $item['contact-id'], 'remote_self' => Contact::MIRROR_NATIVE_RESHARE])) {
2286 if (!in_array($item['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN])) {
2290 Logger::info('Automatically reshare item', ['uid' => $item['uid'], 'id' => $item['id'], 'guid' => $item['guid'], 'uri-id' => $item['uri-id']]);
2292 self::performActivity($item['id'], 'announce', $item['uid']);
2295 public static function isRemoteSelf(array $contact, array &$datarray): bool
2297 if ($contact['remote_self'] != Contact::MIRROR_OWN_POST) {
2301 // Prevent the forwarding of posts that are forwarded
2302 if (!empty($datarray['extid']) && ($datarray['extid'] == Protocol::DFRN)) {
2303 Logger::info('Already forwarded');
2307 // Prevent to forward already forwarded posts
2308 if ($datarray['app'] == DI::baseUrl()->getHostname()) {
2309 Logger::info('Already forwarded (second test)');
2313 // Only forward posts
2314 if ($datarray['verb'] != Activity::POST) {
2315 Logger::info('No post');
2319 if (($contact['network'] != Protocol::FEED) && ($datarray['private'] == self::PRIVATE)) {
2320 Logger::info('Not public');
2324 $datarray2 = $datarray;
2325 Logger::info('remote-self start', ['contact' => $contact['url'], 'remote_self'=> $contact['remote_self'], 'item' => $datarray]);
2327 $self = DBA::selectFirst('contact', ['id', 'name', 'url', 'thumb'],
2328 ['uid' => $contact['uid'], 'self' => true]);
2329 if (!DBA::isResult($self)) {
2330 Logger::error('Self contact not found', ['uid' => $contact['uid']]);
2334 $datarray['contact-id'] = $self['id'];
2336 $datarray['author-name'] = $datarray['owner-name'] = $self['name'];
2337 $datarray['author-link'] = $datarray['owner-link'] = $self['url'];
2338 $datarray['author-avatar'] = $datarray['owner-avatar'] = $self['thumb'];
2340 unset($datarray['edited']);
2342 unset($datarray['network']);
2343 unset($datarray['owner-id']);
2344 unset($datarray['author-id']);
2346 if ($contact['network'] != Protocol::FEED) {
2347 $old_uri_id = $datarray['uri-id'] ?? 0;
2348 $datarray['guid'] = System::createUUID();
2349 unset($datarray['plink']);
2350 $datarray['uri'] = self::newURI($datarray['guid']);
2351 $datarray['uri-id'] = ItemURI::getIdByURI($datarray['uri']);
2352 $datarray['extid'] = Protocol::DFRN;
2353 $urlpart = parse_url($datarray2['author-link']);
2354 $datarray['app'] = $urlpart['host'];
2355 if (!empty($old_uri_id)) {
2356 Post\Media::copy($old_uri_id, $datarray['uri-id']);
2359 unset($datarray['parent-uri']);
2360 unset($datarray['thr-parent']);
2362 // Store the original post
2363 $result = self::insert($datarray2);
2364 Logger::info('remote-self post original item', ['contact' => $contact['url'], 'result'=> $result, 'item' => $datarray2]);
2366 $datarray['private'] = self::PUBLIC;
2367 $datarray['app'] = 'Feed';
2371 return (bool)$result;
2378 * @param array $item
2381 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2382 * @throws \ImagickException
2384 public static function fixPrivatePhotos(string $s, int $uid, array $item = null, int $cid = 0): string
2386 if (DI::config()->get('system', 'disable_embedded')) {
2390 Logger::info('check for photos');
2391 $site = substr(DI::baseUrl(), strpos(DI::baseUrl(), '://'));
2396 $img_start = strpos($orig_body, '[img');
2397 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
2398 $img_len = ($img_start !== false ? strpos(substr($orig_body, $img_start + $img_st_close + 1), '[/img]') : false);
2400 while (($img_st_close !== false) && ($img_len !== false)) {
2401 $img_st_close++; // make it point to AFTER the closing bracket
2402 $image = substr($orig_body, $img_start + $img_st_close, $img_len);
2404 Logger::info('found photo', ['image' => $image]);
2406 if (stristr($image, $site . '/photo/')) {
2407 // Only embed locally hosted photos
2409 $i = basename($image);
2410 $i = str_replace(['.jpg', '.png', '.gif'], ['', '', ''], $i);
2411 $x = strpos($i, '-');
2414 $res = substr($i, $x + 1);
2415 $i = substr($i, 0, $x);
2416 $photo = Photo::getPhotoForUser($uid, $i, $res);
2417 if (DBA::isResult($photo)) {
2419 * Check to see if we should replace this photo link with an embedded image
2420 * 1. No need to do so if the photo is public
2421 * 2. If there's a contact-id provided, see if they're in the access list
2422 * for the photo. If so, embed it.
2423 * 3. Otherwise, if we have an item, see if the item permissions match the photo
2424 * permissions, regardless of order but first check to see if they're an exact
2425 * match to save some processing overhead.
2427 if (self::hasPermissions($photo)) {
2429 $recips = self::enumeratePermissions($photo);
2430 if (in_array($cid, $recips)) {
2434 if (self::samePermissions($uid, $item, $photo)) {
2440 $photo_img = Photo::getImageForPhoto($photo);
2441 // If a custom width and height were specified, apply before embedding
2442 if (preg_match("/\[img\=([0-9]*)x([0-9]*)\]/is", substr($orig_body, $img_start, $img_st_close), $match)) {
2443 Logger::info('scaling photo');
2445 $width = intval($match[1]);
2446 $height = intval($match[2]);
2448 $photo_img->scaleDown(max($width, $height));
2451 $data = $photo_img->asString();
2452 $type = $photo_img->getType();
2454 Logger::info('replacing photo');
2455 $image = 'data:' . $type . ';base64,' . base64_encode($data);
2456 Logger::debug('replaced', ['image' => $image]);
2462 $new_body = $new_body . substr($orig_body, 0, $img_start + $img_st_close) . $image . '[/img]';
2463 $orig_body = substr($orig_body, $img_start + $img_st_close + $img_len + strlen('[/img]'));
2464 if ($orig_body === false) {
2468 $img_start = strpos($orig_body, '[img');
2469 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
2470 $img_len = ($img_start !== false ? strpos(substr($orig_body, $img_start + $img_st_close + 1), '[/img]') : false);
2473 $new_body = $new_body . $orig_body;
2478 private static function hasPermissions(array $obj)
2480 return !empty($obj['allow_cid']) || !empty($obj['allow_gid']) ||
2481 !empty($obj['deny_cid']) || !empty($obj['deny_gid']);
2484 // @TODO $uid is unused parameter
2485 private static function samePermissions($uid, array $obj1, array $obj2): bool
2487 // first part is easy. Check that these are exactly the same.
2488 if (($obj1['allow_cid'] == $obj2['allow_cid'])
2489 && ($obj1['allow_gid'] == $obj2['allow_gid'])
2490 && ($obj1['deny_cid'] == $obj2['deny_cid'])
2491 && ($obj1['deny_gid'] == $obj2['deny_gid'])) {
2495 // This is harder. Parse all the permissions and compare the resulting set.
2496 $recipients1 = self::enumeratePermissions($obj1);
2497 $recipients2 = self::enumeratePermissions($obj2);
2501 /// @TODO Comparison of arrays, maybe use array_diff_assoc() here?
2502 return ($recipients1 == $recipients2);
2506 * Returns an array of contact-ids that are allowed to see this object
2508 * @param array $obj Item array with at least uid, allow_cid, allow_gid, deny_cid and deny_gid
2509 * @param bool $check_dead Prunes unavailable contacts from the result
2511 * @throws \Exception
2513 public static function enumeratePermissions(array $obj, bool $check_dead = false): array
2515 $aclFormater = DI::aclFormatter();
2517 $allow_people = $aclFormater->expand($obj['allow_cid']);
2518 $allow_groups = Group::expand($obj['uid'], $aclFormater->expand($obj['allow_gid']), $check_dead);
2519 $deny_people = $aclFormater->expand($obj['deny_cid']);
2520 $deny_groups = Group::expand($obj['uid'], $aclFormater->expand($obj['deny_gid']), $check_dead);
2521 $recipients = array_unique(array_merge($allow_people, $allow_groups));
2522 $deny = array_unique(array_merge($deny_people, $deny_groups));
2523 $recipients = array_diff($recipients, $deny);
2527 public static function expire(int $uid, int $days, string $network = "", bool $force = false)
2529 if (!$uid || ($days < 1)) {
2533 $condition = ["`uid` = ? AND NOT `deleted` AND `gravity` = ?",
2534 $uid, self::GRAVITY_PARENT];
2537 * $expire_network_only = save your own wall posts
2538 * and just expire conversations started by others
2540 $expire_network_only = DI::pConfig()->get($uid, 'expire', 'network_only', false);
2542 if ($expire_network_only) {
2543 $condition[0] .= " AND NOT `wall`";
2546 if ($network != "") {
2547 $condition[0] .= " AND `network` = ?";
2548 $condition[] = $network;
2551 $condition[0] .= " AND `received` < ?";
2552 $condition[] = DateTimeFormat::utc('now - ' . $days . ' day');
2554 $items = Post::select(['resource-id', 'starred', 'id', 'post-type', 'uid', 'uri-id'], $condition);
2556 if (!DBA::isResult($items)) {
2560 $expire_items = (bool)DI::pConfig()->get($uid, 'expire', 'items', true);
2562 // Forcing expiring of items - but not notes and marked items
2564 $expire_items = true;
2567 $expire_notes = (bool)DI::pConfig()->get($uid, 'expire', 'notes', true);
2568 $expire_starred = (bool)DI::pConfig()->get($uid, 'expire', 'starred', true);
2569 $expire_photos = (bool)DI::pConfig()->get($uid, 'expire', 'photos', false);
2573 $priority = DI::config()->get('system', 'expire-notify-priority');
2575 while ($item = Post::fetch($items)) {
2576 // don't expire filed items
2577 if (DBA::exists('post-category', ['uri-id' => $item['uri-id'], 'uid' => $item['uid'], 'type' => Post\Category::FILE])) {
2581 // Only expire posts, not photos and photo comments
2583 if (!$expire_photos && !empty($item['resource-id'])) {
2585 } elseif (!$expire_starred && intval($item['starred'])) {
2587 } elseif (!$expire_notes && ($item['post-type'] == self::PT_PERSONAL_NOTE)) {
2589 } elseif (!$expire_items && ($item['post-type'] != self::PT_PERSONAL_NOTE)) {
2593 self::markForDeletionById($item['id'], $priority);
2598 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]);
2601 public static function firstPostDate(int $uid, bool $wall = false)
2603 $user = User::getById($uid, ['register_date']);
2608 $condition = ["`uid` = ? AND `wall` = ? AND NOT `deleted` AND `visible` AND `received` >= ?",
2609 $uid, $wall, $user['register_date']];
2610 $params = ['order' => ['received' => false]];
2611 $thread = Post::selectFirstThread(['received'], $condition, $params);
2612 if (DBA::isResult($thread)) {
2613 $postdate = substr(DateTimeFormat::local($thread['received']), 0, 10);
2620 * add/remove activity to an item
2622 * Toggle activities as like,dislike,attend of an item
2624 * @param int $item_id
2625 * @param string $verb
2626 * Activity verb. One of
2627 * like, unlike, dislike, undislike, attendyes, unattendyes,
2628 * attendno, unattendno, attendmaybe, unattendmaybe,
2629 * announce, unannouce
2631 * @param string $allow_cid
2632 * @param string $allow_gid
2633 * @param string $deny_cid
2634 * @param string $deny_gid
2636 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2637 * @throws \ImagickException
2638 * @hook 'post_local_end'
2640 * 'post_id' => ID of posted item
2642 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
2648 Logger::notice('Start create activity', ['verb' => $verb, 'item' => $item_id, 'user' => $uid]);
2650 $item = Post::selectFirst(self::ITEM_FIELDLIST, ['id' => $item_id]);
2651 if (!DBA::isResult($item)) {
2652 Logger::warning('Post had not been fetched', ['id' => $item_id]);
2656 $uri_id = $item['uri-id'];
2658 if (!in_array($item['uid'], [0, $uid])) {
2662 if (!Post::exists(['uri-id' => $item['parent-uri-id'], 'uid' => $uid])) {
2663 $stored = self::storeForUserByUriId($item['parent-uri-id'], $uid, ['post-reason' => Item::PR_ACTIVITY]);
2664 if (($item['parent-uri-id'] == $item['uri-id']) && !empty($stored)) {
2665 $item = Post::selectFirst(self::ITEM_FIELDLIST, ['id' => $stored]);
2666 if (!DBA::isResult($item)) {
2667 Logger::info('Could not fetch just created item - should not happen', ['stored' => $stored, 'uid' => $uid, 'uri-id' => $uri_id]);
2673 // Retrieves the local post owner
2674 $owner = User::getOwnerDataById($uid);
2675 if (empty($owner)) {
2676 Logger::info('Empty owner for user', ['uid' => $uid]);
2680 // Retrieve the current logged in user's public contact
2681 $author_id = Contact::getPublicIdByUserId($uid);
2682 if (empty($author_id)) {
2683 Logger::info('Empty public contact');
2691 $activity = Activity::LIKE;
2695 $activity = Activity::DISLIKE;
2699 $activity = Activity::ATTEND;
2703 $activity = Activity::ATTENDNO;
2706 case 'unattendmaybe':
2707 $activity = Activity::ATTENDMAYBE;
2711 $activity = Activity::FOLLOW;
2715 $activity = Activity::ANNOUNCE;
2718 Logger::warning('unknown verb', ['verb' => $verb, 'item' => $item_id]);
2722 $mode = Strings::startsWith($verb, 'un') ? 'delete' : 'create';
2724 // Enable activity toggling instead of on/off
2725 $event_verb_flag = $activity === Activity::ATTEND || $activity === Activity::ATTENDNO || $activity === Activity::ATTENDMAYBE;
2727 // Look for an existing verb row
2728 // Event participation activities are mutually exclusive, only one of them can exist at all times.
2729 if ($event_verb_flag) {
2730 $verbs = [Activity::ATTEND, Activity::ATTENDNO, Activity::ATTENDMAYBE];
2732 // Translate to the index based activity index
2734 foreach ($verbs as $verb) {
2735 $vids[] = Verb::getID($verb);
2738 $vids = Verb::getID($activity);
2741 $condition = ['vid' => $vids, 'deleted' => false, 'gravity' => self::GRAVITY_ACTIVITY,
2742 'author-id' => $author_id, 'uid' => $uid, 'thr-parent-id' => $uri_id];
2743 $like_item = Post::selectFirst(['id', 'guid', 'verb'], $condition);
2745 if (DBA::isResult($like_item)) {
2747 * Truth table for existing activities
2749 * | Inputs || Outputs |
2750 * |----------------------------||-------------------|
2751 * | Mode | Event | Same verb || Delete? | Return? |
2752 * |--------|-------|-----------||---------|---------|
2753 * | create | Yes | Yes || No | Yes |
2754 * | create | Yes | No || Yes | No |
2755 * | create | No | Yes || No | Yes |
2756 * | create | No | No || N/A†|
2757 * | delete | Yes | Yes || Yes | N/A‡ |
2758 * | delete | Yes | No || No | N/A‡ |
2759 * | delete | No | Yes || Yes | N/A‡ |
2760 * | delete | No | No || N/A†|
2761 * |--------|-------|-----------||---------|---------|
2762 * | A | B | C || A xor C | !B or C |
2764 * †Can't happen: It's impossible to find an existing non-event activity without
2765 * the same verb because we are only looking for this single verb.
2767 * ‡ The "mode = delete" is returning early whether an existing activity was found or not.
2769 if ($mode == 'create' xor $like_item['verb'] == $activity) {
2770 self::markForDeletionById($like_item['id']);
2773 if (!$event_verb_flag || $like_item['verb'] == $activity) {
2778 // No need to go further if we aren't creating anything
2779 if ($mode == 'delete') {
2783 $objtype = $item['resource-id'] ? Activity\ObjectType::IMAGE : Activity\ObjectType::NOTE;
2786 'guid' => System::createUUID(),
2787 'uri' => self::newURI(),
2789 'contact-id' => $owner['id'],
2790 'wall' => $item['wall'],
2792 'network' => Protocol::DFRN,
2793 'protocol' => Conversation::PARCEL_DIRECT,
2794 'direction' => Conversation::PUSH,
2795 'gravity' => self::GRAVITY_ACTIVITY,
2796 'parent' => $item['id'],
2797 'thr-parent' => $item['uri'],
2798 'owner-id' => $author_id,
2799 'author-id' => $author_id,
2800 'body' => $activity,
2801 'verb' => $activity,
2802 'object-type' => $objtype,
2803 'allow_cid' => $allow_cid ?? $item['allow_cid'],
2804 'allow_gid' => $allow_gid ?? $item['allow_gid'],
2805 'deny_cid' => $deny_cid ?? $item['deny_cid'],
2806 'deny_gid' => $deny_gid ?? $item['deny_gid'],
2811 if (in_array($activity, [Activity::LIKE, Activity::DISLIKE])) {
2812 $signed = Diaspora::createLikeSignature($uid, $new_item);
2813 if (!empty($signed)) {
2814 $new_item['diaspora_signed_text'] = json_encode($signed);
2818 self::insert($new_item, true);
2820 // If the parent item isn't visible then set it to visible
2821 // @todo Check if this is still needed
2822 if (!$item['visible']) {
2823 self::update(['visible' => true], ['id' => $item['id']]);
2829 * Fetch the SQL condition for the given user id
2831 * @param integer $owner_id User ID for which the permissions should be fetched
2832 * @return array condition
2834 public static function getPermissionsConditionArrayByUserId(int $owner_id): array
2836 $local_user = DI::userSession()->getLocalUserId();
2837 $remote_user = DI::userSession()->getRemoteContactID($owner_id);
2839 // default permissions - anonymous user
2840 $condition = ["`private` != ?", self::PRIVATE];
2842 if ($local_user && ($local_user == $owner_id)) {
2843 // Profile owner - everything is visible
2845 } elseif ($remote_user) {
2846 // Authenticated visitor - fetch the matching permissionsets
2847 $permissionSets = DI::permissionSet()->selectByContactId($remote_user, $owner_id);
2849 $condition = ["(`private` != ? OR (`private` = ? AND `wall`
2850 AND `psid` IN (" . implode(', ', array_fill(0, count($set), '?')) . ")))",
2851 self::PRIVATE, self::PRIVATE];
2852 $condition = array_merge($condition, $permissionSets->column('id'));
2860 * Get a permission SQL string for the given user
2862 * @param int $owner_id
2863 * @param string $table
2866 public static function getPermissionsSQLByUserId(int $owner_id, string $table = ''): string
2868 $local_user = DI::userSession()->getLocalUserId();
2869 $remote_user = DI::userSession()->getRemoteContactID($owner_id);
2871 if (!empty($table)) {
2872 $table = DBA::quoteIdentifier($table) . '.';
2876 * Construct permissions
2878 * default permissions - anonymous user
2880 $sql = sprintf(" AND " . $table . "`private` != %d", self::PRIVATE);
2882 // Profile owner - everything is visible
2883 if ($local_user && ($local_user == $owner_id)) {
2885 } elseif ($remote_user) {
2887 * Authenticated visitor. Unless pre-verified,
2888 * check that the contact belongs to this $owner_id
2889 * and load the groups the visitor belongs to.
2890 * If pre-verified, the caller is expected to have already
2891 * done this and passed the groups into this function.
2893 $permissionSets = DI::permissionSet()->selectByContactId($remote_user, $owner_id);
2896 $sql_set = sprintf(" OR (" . $table . "`private` = %d AND " . $table . "`wall` AND " . $table . "`psid` IN (", self::PRIVATE) . implode(',', $permissionSets->column('id')) . "))";
2901 $sql = sprintf(" AND (" . $table . "`private` != %d", self::PRIVATE) . $sql_set . ")";
2908 * get translated item type
2910 * @param array $item
2911 * @param \Friendica\Core\L10n $l10n
2914 public static function postType(array $item, \Friendica\Core\L10n $l10n): string
2916 if (!empty($item['event-id'])) {
2917 return $l10n->t('event');
2918 } elseif (!empty($item['resource-id'])) {
2919 return $l10n->t('photo');
2920 } elseif ($item['gravity'] == self::GRAVITY_ACTIVITY) {
2921 return $l10n->t('activity');
2922 } elseif ($item['gravity'] == self::GRAVITY_COMMENT) {
2923 return $l10n->t('comment');
2926 return $l10n->t('post');
2930 * Sets the "rendered-html" field of the provided item
2932 * Body is preserved to avoid side-effects as we modify it just-in-time for spoilers and private image links
2934 * @param array $item
2936 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2937 * @todo Remove reference, simply return "rendered-html" and "rendered-hash"
2939 private static function putInCache(&$item)
2941 // Save original body to prevent addons to modify it
2942 $body = $item['body'];
2944 $rendered_hash = $item['rendered-hash'] ?? '';
2945 $rendered_html = $item['rendered-html'] ?? '';
2947 if ($rendered_hash == ''
2948 || $rendered_html == ''
2949 || $rendered_hash != hash('md5', BBCode::VERSION . '::' . $body)
2950 || DI::config()->get('system', 'ignore_cache')
2952 $item['rendered-html'] = BBCode::convertForUriId($item['uri-id'], $item['body']);
2953 $item['rendered-hash'] = hash('md5', BBCode::VERSION . '::' . $body);
2955 $hook_data = ['item' => $item, 'rendered-html' => $item['rendered-html'], 'rendered-hash' => $item['rendered-hash']];
2956 Hook::callAll('put_item_in_cache', $hook_data);
2957 $item['rendered-html'] = $hook_data['rendered-html'];
2958 $item['rendered-hash'] = $hook_data['rendered-hash'];
2961 // Update if the generated values differ from the existing ones
2962 if ((($rendered_hash != $item['rendered-hash']) || ($rendered_html != $item['rendered-html'])) && !empty($item['id'])) {
2965 'rendered-html' => $item['rendered-html'],
2966 'rendered-hash' => $item['rendered-hash']
2968 ['id' => $item['id']]
2973 $item['body'] = $body;
2977 * Given an item array, convert the body element from bbcode to html and add smilie icons.
2978 * If attach is true, also add icons for item attachments.
2980 * @param array $item Record from item table
2981 * @param boolean $attach If true, add icons for item attachments as well
2982 * @param boolean $is_preview Whether this is a preview
2983 * @param boolean $only_cache Whether only cached HTML should be updated
2984 * @return string item body html
2985 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2986 * @throws \ImagickException
2987 * @hook prepare_body_init item array before any work
2988 * @hook prepare_body_content_filter ('item'=>item array, 'filter_reasons'=>string array) before first bbcode to html
2989 * @hook prepare_body ('item'=>item array, 'html'=>body string, 'is_preview'=>boolean, 'filter_reasons'=>string array) after first bbcode to html
2990 * @hook prepare_body_final ('item'=>item array, 'html'=>body string) after attach icons and blockquote special case handling (spoiler, author)
2992 public static function prepareBody(array &$item, bool $attach = false, bool $is_preview = false, bool $only_cache = false): string
2995 Hook::callAll('prepare_body_init', $item);
2998 // In order to provide theme developers more possibilities, event items
2999 // are treated differently.
3000 if ($item['object-type'] === Activity\ObjectType::EVENT && isset($item['event-id'])) {
3001 $ev = Event::getItemHTML($item);
3005 $tags = Tag::populateFromItem($item);
3007 $item['tags'] = $tags['tags'];
3008 $item['hashtags'] = $tags['hashtags'];
3009 $item['mentions'] = $tags['mentions'];
3011 $body = $item['body'] = Post\Media::removeFromEndOfBody($item['body'] ?? '');
3013 $fields = ['uri-id', 'uri', 'body', 'title', 'author-name', 'author-link', 'author-avatar', 'guid', 'created', 'plink', 'network', 'has-media', 'quote-uri-id', 'post-type'];
3018 $shared = DI::contentItem()->getSharedPost($item, $fields);
3019 if (!empty($shared['post'])) {
3020 $shared_item = $shared['post'];
3021 $quote_uri_id = $shared['post']['uri-id'];
3022 $shared_links[] = strtolower($shared['post']['uri']);
3023 $item['body'] = BBCode::removeSharedData($item['body']);
3024 } elseif (empty($shared_item['uri-id']) && empty($item['quote-uri-id']) && ($item['network'] != Protocol::DIASPORA)) {
3025 $media = Post\Media::getByURIId($item['uri-id'], [Post\Media::ACTIVITY]);
3026 if (!empty($media)) {
3027 $shared_item = Post::selectFirst($fields, ['plink' => $media[0]['url'], 'uid' => [$item['uid'], 0]]);
3029 if (empty($shared_item['uri-id'])) {
3030 $shared_item = Post::selectFirst($fields, ['uri' => $media[0]['url'], 'uid' => [$item['uid'], 0]]);
3031 $shared_links[] = strtolower($media[0]['url']);
3034 $quote_uri_id = $shared_item['uri-id'] ?? 0;
3038 if (!empty($quote_uri_id)) {
3039 $item['body'] .= "\n" . DI::contentItem()->createSharedBlockByArray($shared_item);
3042 if (!empty($shared_item['uri-id'])) {
3043 $shared_uri_id = $shared_item['uri-id'];
3044 $shared_links[] = strtolower($shared_item['plink']);
3045 $shared_attachments = Post\Media::splitAttachments($shared_uri_id, [], $shared_item['has-media']);
3046 $shared_links = array_merge($shared_links, array_column($shared_attachments['visual'], 'url'));
3047 $shared_links = array_merge($shared_links, array_column($shared_attachments['link'], 'url'));
3048 $shared_links = array_merge($shared_links, array_column($shared_attachments['additional'], 'url'));
3049 $item['body'] = self::replaceVisualAttachments($shared_attachments, $item['body']);
3052 $attachments = Post\Media::splitAttachments($item['uri-id'], $shared_links, $item['has-media'] ?? false);
3053 $item['body'] = self::replaceVisualAttachments($attachments, $item['body'] ?? '');
3055 $item['body'] = preg_replace("/\s*\[attachment .*?\].*?\[\/attachment\]\s*/ism", "\n", $item['body']);
3057 self::putInCache($item);
3058 $item['body'] = $body;
3059 $s = $item["rendered-html"];
3065 // Compile eventual content filter reasons
3066 $filter_reasons = [];
3067 if (!$is_preview && DI::userSession()->getPublicContactId() != $item['author-id']) {
3068 if (!empty($item['content-warning']) && (!DI::userSession()->getLocalUserId() || !DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'system', 'disable_cw', false))) {
3069 $filter_reasons[] = DI::l10n()->t('Content warning: %s', $item['content-warning']);
3072 $item['attachments'] = $attachments;
3076 'filter_reasons' => $filter_reasons
3078 Hook::callAll('prepare_body_content_filter', $hook_data);
3079 $filter_reasons = $hook_data['filter_reasons'];
3086 'preview' => $is_preview,
3087 'filter_reasons' => $filter_reasons
3089 Hook::callAll('prepare_body', $hook_data);
3093 // Replace the blockquotes with quotes that are used in mails.
3094 $mailquote = '<blockquote type="cite" class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex;">';
3095 $s = str_replace(['<blockquote>', '<blockquote class="spoiler">', '<blockquote class="author">'], [$mailquote, $mailquote, $mailquote], $s);
3099 if (!empty($shared_attachments)) {
3100 $s = self::addVisualAttachments($shared_attachments, $shared_item, $s, true);
3101 $s = self::addLinkAttachment($shared_uri_id ?: $item['uri-id'], $shared_attachments, $body, $s, true, []);
3102 $s = self::addNonVisualAttachments($shared_attachments, $item, $s, true);
3103 $body = BBCode::removeSharedData($body);
3106 $s = self::addVisualAttachments($attachments, $item, $s, false);
3107 $s = self::addLinkAttachment($item['uri-id'], $attachments, $body, $s, false, $shared_links);
3108 $s = self::addNonVisualAttachments($attachments, $item, $s, false);
3109 $s = self::addQuestions($item, $s);
3112 if (strpos($s, '<div class="map">') !== false && !empty($item['coord'])) {
3113 $x = Map::byCoordinates(trim($item['coord']));
3115 $s = preg_replace('/\<div class\=\"map\"\>/', '$0' . $x, $s);
3119 // Replace friendica image url size with theme preference.
3120 if (!empty($a->getThemeInfoValue('item_image_size'))) {
3121 $ps = $a->getThemeInfoValue('item_image_size');
3122 $s = preg_replace('|(<img[^>]+src="[^"]+/photo/[0-9a-f]+)-[0-9]|', "$1-" . $ps, $s);
3125 $s = HTML::applyContentFilter($s, $filter_reasons);
3127 if (count($attachments['visual']) > 1) {
3128 // make imgae grid only for multiple images
3129 $s = self::cutAttachedImages($s);
3130 $grid = self::make_image_grid($item, $attachments);
3134 $hook_data = ['item' => $item, 'html' => $s];
3135 Hook::callAll('prepare_body_final', $hook_data);
3136 return $hook_data['html'];
3140 * This function removes images at the very end of a post based on the assumption that this images are interpreted
3142 * @param array $rendered_html
3145 private function cutAttachedImages($rendered_html)
3147 $doc = new DOMDocument('1.0', 'UTF-8');
3148 libxml_use_internal_errors(true);
3149 $doc->loadHTML(mb_convert_encoding($rendered_html, 'html-entities', 'utf-8'));
3150 libxml_clear_errors();
3152 $root = $doc->getElementsByTagName("p")[0];
3154 $lastTextNode = null;
3155 if ($root && $root->childNodes) {
3156 foreach ($root->childNodes as $node) {
3157 if ($node->nodeName == "#text" && strlen(trim($node->nodeValue)) > 0) {
3158 $lastTextNode = $node;
3163 if ($lastTextNode == null) {
3164 // no text at all, return nothing:
3168 $toremove = array();
3169 if ($lastTextNode) {
3170 $sibling = $lastTextNode->nextSibling;
3172 $toremove[] = array($sibling);
3173 $sibling = $sibling->nextSibling;
3175 foreach ($toremove as $remove) {
3176 $root->removeChild($remove[0]);
3179 foreach ($root->childNodes as $node) {
3180 $html .= $node->ownerDocument->saveHTML($node);
3185 return $rendered_html;
3189 * @param array $data
3190 * @return string|void
3191 * @throws \Friendica\Network\HTTPException\ServiceUnavailableException
3193 private function make_image_grid(array $item, array $attachments)
3195 if ($item['has-media']) {
3196 if (count($attachments['visual']) > 1) {
3198 $img_tags_landscape = array();
3199 $img_tags_portrait = array();
3200 foreach ($attachments['visual'] as $attachment) {
3201 $src_url = Post\Media::getUrlForId($attachment['id']);
3202 $preview_url = Post\Media::getPreviewUrlForId($attachment['id'], ($attachment['width'] > $attachment['height']) ? Proxy::SIZE_MEDIUM : Proxy::SIZE_LARGE);
3206 'preview' => $preview_url,
3207 'attachment' => $attachment,
3209 ($attachment['width'] > $attachment['height']) ? ($img_tags_landscape[] = $img_tag) : ($img_tags_portrait[] = $img_tag);
3212 $landscapesCount = count($img_tags_landscape);
3213 $portraitsCount = count($img_tags_portrait);
3215 // @todo add some fany ai to divide images equally on both columns
3216 $img_tags_fc = array();
3217 $img_tags_sc = array();
3218 if ($landscapesCount == 0) {
3220 for ($i = 0; $i < $portraitsCount; $i++) {
3221 ($i % 2 == 0) ? ($img_tags_fc[] = $img_tags_portrait[$i]) : ($img_tags_sc[] = $img_tags_portrait[$i]);
3224 if ($portraitsCount == 0) {
3226 for ($i = 0; $i < $landscapesCount; $i++) {
3227 ($i % 2 == 0) ? ($img_tags_fc[] = $img_tags_landscape[$i]) : ($img_tags_sc[] = $img_tags_landscape[$i]);
3231 return Renderer::replaceMacros(Renderer::getMarkupTemplate('content/image_grid.tpl'), [
3233 'fc' => $img_tags_fc,
3234 'sc' => $img_tags_sc,
3243 * Check if the body contains a link
3245 * @param string $body
3246 * @param string $url
3250 public static function containsLink(string $body, string $url, int $type = 0): bool
3252 // Make sure that for example site parameters aren't used when testing if the link is contained in the body
3253 $urlparts = parse_url($url);
3254 if (empty($urlparts)) {
3258 unset($urlparts['query']);
3259 unset($urlparts['fragment']);
3262 $url = (string)Uri::fromParts($urlparts);
3263 } catch (\InvalidArgumentException $e) {
3264 DI::logger()->notice('Invalid URL', ['$url' => $url, '$urlparts' => $urlparts]);
3265 /* See https://github.com/friendica/friendica/issues/12113
3266 * Malformed URLs will result in a Fatal Error
3271 // Remove media links to only search in embedded content
3272 // @todo Check images for image link, audio for audio links, ...
3273 if (in_array($type, [Post\Media::AUDIO, Post\Media::VIDEO, Post\Media::IMAGE])) {
3274 $body = preg_replace("/\[url=[^\[\]]*\](.*)\[\/url\]/Usi", ' $1 ', $body);
3277 if (strpos($body, $url)) {
3281 foreach ([0, 1, 2] as $size) {
3282 if (preg_match('#/photo/.*-' . $size . '\.#ism', $url) &&
3283 strpos(preg_replace('#(/photo/.*)-[012]\.#ism', '$1-' . $size . '.', $body), $url)) {
3292 * Replace visual attachments in the body
3294 * @param array $attachments
3295 * @param string $body
3296 * @return string modified body
3298 private static function replaceVisualAttachments(array $attachments, string $body): string
3300 DI::profiler()->startRecording('rendering');
3302 foreach ($attachments['visual'] as $attachment) {
3303 if (!empty($attachment['preview'])) {
3304 $proxy = Post\Media::getPreviewUrlForId($attachment['id'], Proxy::SIZE_LARGE);
3305 $search = ['[img=' . $attachment['preview'] . ']', ']' . $attachment['preview'] . '[/img]'];
3306 $replace = ['[img=' . $proxy . ']', ']' . $proxy . '[/img]'];
3308 $body = str_replace($search, $replace, $body);
3309 } elseif ($attachment['filetype'] == 'image') {
3310 $proxy = Post\Media::getUrlForId($attachment['id']);
3311 $search = ['[img=' . $attachment['url'] . ']', ']' . $attachment['url'] . '[/img]'];
3312 $replace = ['[img=' . $proxy . ']', ']' . $proxy . '[/img]'];
3314 $body = str_replace($search, $replace, $body);
3317 DI::profiler()->stopRecording();
3322 * Add visual attachments to the content
3324 * @param array $attachments
3325 * @param array $item
3326 * @param string $content
3327 * @return string modified content
3329 private static function addVisualAttachments(array $attachments, array $item, string $content, bool $shared): string
3331 DI::profiler()->startRecording('rendering');
3336 // @todo In the future we should make a single for the template engine with all media in it. This allows more flexibilty.
3337 foreach ($attachments['visual'] as $attachment) {
3338 if (self::containsLink($item['body'], $attachment['preview'] ?? $attachment['url'], $attachment['type'])) {
3342 if ($attachment['filetype'] == 'image') {
3343 $preview_url = Post\Media::getPreviewUrlForId($attachment['id'], ($attachment['width'] > $attachment['height']) ? Proxy::SIZE_MEDIUM : Proxy::SIZE_LARGE);
3344 } elseif (!empty($attachment['preview'])) {
3345 $preview_url = Post\Media::getPreviewUrlForId($attachment['id'], Proxy::SIZE_LARGE);
3350 if ($preview_url && self::containsLink($item['body'], $preview_url)) {
3354 if (($attachment['filetype'] == 'video')) {
3355 /// @todo Move the template to /content as well
3356 $media = Renderer::replaceMacros(Renderer::getMarkupTemplate('video_top.tpl'), [
3358 'id' => $attachment['id'],
3359 'src' => $attachment['url'],
3360 'name' => $attachment['name'] ?: $attachment['url'],
3361 'preview' => $preview_url,
3362 'mime' => $attachment['mimetype'],
3365 if (($item['post-type'] ?? null) == Item::PT_VIDEO) {
3368 $trailing .= $media;
3370 } elseif ($attachment['filetype'] == 'audio') {
3371 $media = Renderer::replaceMacros(Renderer::getMarkupTemplate('content/audio.tpl'), [
3373 'id' => $attachment['id'],
3374 'src' => $attachment['url'],
3375 'name' => $attachment['name'] ?: $attachment['url'],
3376 'mime' => $attachment['mimetype'],
3379 if (($item['post-type'] ?? null) == Item::PT_AUDIO) {
3382 $trailing .= $media;
3384 } elseif ($attachment['filetype'] == 'image') {
3385 $src_url = Post\Media::getUrlForId($attachment['id']);
3386 if (self::containsLink($item['body'], $src_url)) {
3389 $images[] = ['src' => $src_url, 'preview' => $preview_url, 'attachment' => $attachment];
3393 foreach ($images as $image) {
3394 $media = Renderer::replaceMacros(Renderer::getMarkupTemplate('content/image.tpl'), [
3397 // On Diaspora posts the attached pictures are leading
3398 if ($item['network'] == Protocol::DIASPORA) {
3401 $trailing .= $media;
3406 $content = str_replace(BBCode::TOP_ANCHOR, '<div class="body-attach">' . $leading . '<div class="clear"></div></div>' . BBCode::TOP_ANCHOR, $content);
3407 $content = str_replace(BBCode::BOTTOM_ANCHOR, '<div class="body-attach">' . $trailing . '<div class="clear"></div></div>' . BBCode::BOTTOM_ANCHOR, $content);
3409 if ($leading != '') {
3410 $content = '<div class="body-attach">' . $leading . '<div class="clear"></div></div>' . $content;
3413 if ($trailing != '') {
3414 $content .= '<div class="body-attach">' . $trailing . '<div class="clear"></div></div>';
3418 DI::profiler()->stopRecording();
3423 * Add link attachment to the content
3425 * @param array $attachments
3426 * @param string $body
3427 * @param string $content
3428 * @param bool $shared
3429 * @param array $ignore_links A list of URLs to ignore
3430 * @return string modified content
3432 private static function addLinkAttachment(int $uriid, array $attachments, string $body, string $content, bool $shared, array $ignore_links): string
3434 DI::profiler()->startRecording('rendering');
3435 // Don't show a preview when there is a visual attachment (audio or video)
3436 $types = array_column($attachments['visual'], 'type');
3437 $preview = !in_array(Post\Media::IMAGE, $types) && !in_array(Post\Media::VIDEO, $types);
3439 if (!empty($attachments['link'])) {
3440 foreach ($attachments['link'] as $link) {
3442 foreach ($ignore_links as $ignore_link) {
3443 if (Strings::compareLink($link['url'], $ignore_link)) {
3447 // @todo Judge between the links to use the one with most information
3448 if (!$found && (empty($attachment) || !empty($link['author-name']) ||
3449 (empty($attachment['name']) && !empty($link['name'])) ||
3450 (empty($attachment['description']) && !empty($link['description'])) ||
3451 (empty($attachment['preview']) && !empty($link['preview'])))) {
3452 $attachment = $link;
3457 if (!empty($attachment)) {
3460 'author_name' => $attachment['author-name'] ?? '',
3461 'author_url' => $attachment['author-url'] ?? '',
3462 'description' => $attachment['description'] ?? '',
3465 'provider_name' => $attachment['publisher-name'] ?? '',
3466 'provider_url' => $attachment['publisher-url'] ?? '',
3468 'title' => $attachment['name'] ?? '',
3470 'url' => $attachment['url']];
3472 if ($preview && !empty($attachment['preview'])) {
3473 if ($attachment['preview-width'] >= 500) {
3474 $data['image'] = Post\Media::getPreviewUrlForId($attachment['id'], Proxy::SIZE_MEDIUM);
3476 $data['preview'] = Post\Media::getPreviewUrlForId($attachment['id'], Proxy::SIZE_MEDIUM);
3480 if (!empty($data['description']) && !empty($content)) {
3481 similar_text($data['description'], $content, $percent);
3486 if (!empty($data['description']) && (($data['title'] == $data['description']) || ($percent > 95) || (strpos($content, $data['description']) !== false))) {
3487 $data['description'] = '';
3490 if (($data['author_name'] ?? '') == ($data['provider_name'] ?? '')) {
3491 $data['author_name'] = '';
3494 if (($data['author_url'] ?? '') == ($data['provider_url'] ?? '')) {
3495 $data['author_url'] = '';
3497 } elseif (preg_match("/.*(\[attachment.*?\].*?\[\/attachment\]).*/ism", $body, $match)) {
3498 $data = BBCode::getAttachmentData($match[1]);
3500 DI::profiler()->stopRecording();
3502 if (isset($data['url']) && !in_array(strtolower($data['url']), $ignore_links)) {
3503 if (!empty($data['description']) || !empty($data['image']) || !empty($data['preview'])) {
3504 $parts = parse_url($data['url']);
3505 if (!empty($parts['scheme']) && !empty($parts['host'])) {
3506 if (empty($data['provider_name'])) {
3507 $data['provider_name'] = $parts['host'];
3509 if (empty($data['provider_url']) || empty(parse_url($data['provider_url'], PHP_URL_SCHEME))) {
3510 $data['provider_url'] = $parts['scheme'] . '://' . $parts['host'];
3512 if (!empty($parts['port'])) {
3513 $data['provider_url'] .= ':' . $parts['port'];
3518 // @todo Use a template
3519 $preview_mode = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'system', 'preview_mode', BBCode::PREVIEW_LARGE);
3520 if ($preview_mode != BBCode::PREVIEW_NONE) {
3521 $rendered = BBCode::convertAttachment('', BBCode::INTERNAL, false, $data, $uriid, $preview_mode);
3523 } elseif (!self::containsLink($content, $data['url'], Post\Media::HTML)) {
3524 $rendered = Renderer::replaceMacros(Renderer::getMarkupTemplate('content/link.tpl'), [
3525 '$url' => $data['url'],
3526 '$title' => $data['title'],
3533 return str_replace(BBCode::BOTTOM_ANCHOR, BBCode::BOTTOM_ANCHOR . $rendered, $content);
3535 return $content . $rendered;
3542 * Add non visual attachments to the content
3544 * @param array $attachments
3545 * @param array $item
3546 * @param string $content
3547 * @return string modified content
3549 private static function addNonVisualAttachments(array $attachments, array $item, string $content): string
3551 DI::profiler()->startRecording('rendering');
3553 foreach ($attachments['additional'] as $attachment) {
3554 if (strpos($item['body'], $attachment['url'])) {
3558 $author = ['uid' => 0, 'id' => $item['author-id'],
3559 'network' => $item['author-network'], 'url' => $item['author-link']];
3560 $the_url = Contact::magicLinkByContact($author, $attachment['url']);
3562 $title = Strings::escapeHtml(trim(($attachment['description'] ?? '') ?: $attachment['url']));
3564 if (!empty($attachment['size'])) {
3565 $title .= ' ' . $attachment['size'] . ' ' . DI::l10n()->t('bytes');
3568 /// @todo Use a template
3569 $icon = '<div class="attachtype icon s22 type-' . $attachment['filetype'] . ' subtype-' . $attachment['subtype'] . '"></div>';
3570 $trailing .= '<a href="' . strip_tags($the_url) . '" title="' . $title . '" class="attachlink" target="_blank" rel="noopener noreferrer" >' . $icon . '</a>';
3573 if ($trailing != '') {
3574 $content .= '<div class="body-attach">' . $trailing . '<div class="clear"></div></div>';
3577 DI::profiler()->stopRecording();
3581 private static function addQuestions(array $item, string $content): string
3583 DI::profiler()->startRecording('rendering');
3584 if (!empty($item['question-id'])) {
3586 'id' => $item['question-id'],
3587 'multiple' => $item['question-multiple'],
3588 'voters' => $item['question-voters'],
3589 'endtime' => $item['question-end-time']
3592 $options = Post\QuestionOption::getByURIId($item['uri-id']);
3593 foreach ($options as $key => $option) {
3594 if ($question['voters'] > 0) {
3595 $percent = $option['replies'] / $question['voters'] * 100;
3596 $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));
3598 $options[$key]['vote'] = DI::l10n()->tt('%2$s (%1$d vote)', '%2$s (%1$d votes)', $option['replies'], $option['name']);
3602 if (!empty($question['voters']) && !empty($question['endtime'])) {
3603 $summary = DI::l10n()->tt('%d voter. Poll end: %s', '%d voters. Poll end: %s', $question['voters'], Temporal::getRelativeDate($question['endtime']));
3604 } elseif (!empty($question['voters'])) {
3605 $summary = DI::l10n()->tt('%d voter.', '%d voters.', $question['voters']);
3606 } elseif (!empty($question['endtime'])) {
3607 $summary = DI::l10n()->t('Poll end: %s', Temporal::getRelativeDate($question['endtime']));
3612 $content .= Renderer::replaceMacros(Renderer::getMarkupTemplate('content/question.tpl'), [
3613 '$question' => $question,
3614 '$options' => $options,
3615 '$summary' => $summary,
3618 DI::profiler()->stopRecording();
3623 * get private link for item
3625 * @param array $item
3626 * @return boolean|array False if item has not plink, otherwise array('href'=>plink url, 'title'=>translated title)
3627 * @throws \Exception
3629 public static function getPlink(array $item)
3631 if (!empty($item['plink']) && Network::isValidHttpUrl($item['plink'])) {
3632 $plink = $item['plink'];
3633 } elseif (!empty($item['uri']) && Network::isValidHttpUrl($item['uri']) && !Network::isLocalLink($item['uri'])) {
3634 $plink = $item['uri'];
3637 if (DI::userSession()->getLocalUserId()) {
3639 'href' => "display/" . $item['guid'],
3640 'orig' => "display/" . $item['guid'],
3641 'title' => DI::l10n()->t('View on separate page'),
3642 'orig_title' => DI::l10n()->t('View on separate page'),
3645 if (!empty($plink) && ($item['private'] == self::PRIVATE)) {
3646 $author = ['uid' => 0, 'id' => $item['author-id'],
3647 'network' => $item['author-network'], 'url' => $item['author-link']];
3648 $plink = Contact::magicLinkByContact($author, $plink);
3651 if (!empty($plink)) {
3652 $ret['href'] = DI::baseUrl()->remove($plink);
3653 $ret['title'] = DI::l10n()->t('Link to source');
3655 } elseif (!empty($plink) && ($item['private'] != self::PRIVATE)) {
3659 'title' => DI::l10n()->t('Link to source'),
3660 'orig_title' => DI::l10n()->t('Link to source'),
3670 * Does the given uri-id belongs to a post that is sent as starting post to a forum?
3672 * @param int $uri_id
3674 * @return boolean "true" when it is a forum post
3676 public static function isForumPost(int $uri_id): bool
3678 foreach (Tag::getByURIId($uri_id, [Tag::EXCLUSIVE_MENTION]) as $tag) {
3679 if (DBA::exists('contact', ['uid' => 0, 'nurl' => Strings::normaliseLink($tag['url']), 'contact-type' => Contact::TYPE_COMMUNITY])) {
3687 * Search item id for given URI or plink
3689 * @param string $uri
3690 * @param integer $uid
3692 * @return integer item id
3694 public static function searchByLink(string $uri, int $uid = 0): int
3696 $ssl_uri = str_replace('http://', 'https://', $uri);
3697 $uris = [$uri, $ssl_uri, Strings::normaliseLink($uri)];
3699 $item = Post::selectFirst(['id'], ['uri' => $uris, 'uid' => $uid]);
3700 if (DBA::isResult($item)) {
3704 $item = Post::selectFirst(['id'], ['plink' => $uris, 'uid' => $uid]);
3705 if (DBA::isResult($item)) {
3713 * Return the URI for a link to the post
3715 * @param string $uri URI or link to post
3717 * @return string URI
3719 public static function getURIByLink(string $uri): string
3721 $ssl_uri = str_replace('http://', 'https://', $uri);
3722 $uris = [$uri, $ssl_uri, Strings::normaliseLink($uri)];
3724 $item = Post::selectFirst(['uri'], ['uri' => $uris]);
3725 if (DBA::isResult($item)) {
3726 return $item['uri'];
3729 $item = Post::selectFirst(['uri'], ['plink' => $uris]);
3730 if (DBA::isResult($item)) {
3731 return $item['uri'];
3738 * Fetches item for given URI or plink
3740 * @param string $uri
3741 * @param integer $uid
3743 * @return integer item id
3745 public static function fetchByLink(string $uri, int $uid = 0): int
3747 Logger::info('Trying to fetch link', ['uid' => $uid, 'uri' => $uri]);
3748 $item_id = self::searchByLink($uri, $uid);
3749 if (!empty($item_id)) {
3750 Logger::info('Link found', ['uid' => $uid, 'uri' => $uri, 'id' => $item_id]);
3760 Hook::callAll('item_by_link', $hookData);
3762 if (isset($hookData['item_id'])) {
3763 return is_numeric($hookData['item_id']) ? $hookData['item_id'] : 0;
3766 $fetched_uri = ActivityPub\Processor::fetchMissingActivity($uri);
3769 $item_id = self::searchByLink($fetched_uri, $uid);
3771 $item_id = Diaspora::fetchByURL($uri);
3774 if (!empty($item_id)) {
3775 Logger::info('Link fetched', ['uid' => $uid, 'uri' => $uri, 'id' => $item_id]);
3779 Logger::info('Link not found', ['uid' => $uid, 'uri' => $uri]);
3784 * Check a prospective item array against user-level permissions
3786 * @param array $item Expected keys: uri, gravity, and
3787 * author-link if is author-id is set,
3788 * owner-link if is owner-id is set,
3789 * causer-link if is causer-id is set.
3790 * @param int $user_id Local user ID
3792 * @throws \Exception
3794 protected static function isAllowedByUser(array $item, int $user_id): bool
3796 if (!empty($item['author-id']) && Contact\User::isBlocked($item['author-id'], $user_id)) {
3797 Logger::notice('Author is blocked by user', ['author-link' => $item['author-link'], 'uid' => $user_id, 'item-uri' => $item['uri']]);
3801 if (!empty($item['owner-id']) && Contact\User::isBlocked($item['owner-id'], $user_id)) {
3802 Logger::notice('Owner is blocked by user', ['owner-link' => $item['owner-link'], 'uid' => $user_id, 'item-uri' => $item['uri']]);
3806 // The causer is set during a thread completion, for example because of a reshare. It countains the responsible actor.
3807 if (!empty($item['causer-id']) && Contact\User::isBlocked($item['causer-id'], $user_id)) {
3808 Logger::notice('Causer is blocked by user', ['causer-link' => $item['causer-link'] ?? $item['causer-id'], 'uid' => $user_id, 'item-uri' => $item['uri']]);
3812 if (!empty($item['causer-id']) && ($item['gravity'] === self::GRAVITY_PARENT) && Contact\User::isIgnored($item['causer-id'], $user_id)) {
3813 Logger::notice('Causer is ignored by user', ['causer-link' => $item['causer-link'] ?? $item['causer-id'], 'uid' => $user_id, 'item-uri' => $item['uri']]);
3821 * Fetch the uri-id of a quote
3823 * @param string $body
3826 public static function getQuoteUriId(string $body, int $uid = 0): int
3828 $shared = BBCode::fetchShareAttributes($body);
3829 if (empty($shared['guid']) && empty($shared['message_id'])) {
3833 if (empty($shared['link']) && empty($shared['message_id'])) {
3834 Logger::notice('Invalid share block.', ['share' => $shared]);
3838 if (!empty($shared['guid'])) {
3839 $shared_item = Post::selectFirst(['uri-id'], ['guid' => $shared['guid'], 'uid' => [0, $uid]]);
3840 if (!empty($shared_item['uri-id'])) {
3841 Logger::debug('Found post by guid', ['guid' => $shared['guid'], 'uid' => $uid]);
3842 return $shared_item['uri-id'];
3846 if (!empty($shared['message_id'])) {
3847 $shared_item = Post::selectFirst(['uri-id'], ['uri' => $shared['message_id'], 'uid' => [0, $uid]]);
3848 if (!empty($shared_item['uri-id'])) {
3849 Logger::debug('Found post by message_id', ['message_id' => $shared['message_id'], 'uid' => $uid]);
3850 return $shared_item['uri-id'];
3854 if (!empty($shared['link'])) {
3855 $shared_item = Post::selectFirst(['uri-id'], ['plink' => $shared['link'], 'uid' => [0, $uid]]);
3856 if (!empty($shared_item['uri-id'])) {
3857 Logger::debug('Found post by link', ['link' => $shared['link'], 'uid' => $uid]);
3858 return $shared_item['uri-id'];
3862 $url = $shared['message_id'] ?: $shared['link'];
3863 $id = self::fetchByLink($url);
3865 Logger::notice('Post could not be fetched.', ['url' => $url, 'uid' => $uid]);
3869 $shared_item = Post::selectFirst(['uri-id'], ['id' => $id]);
3870 if (!empty($shared_item['uri-id'])) {
3871 Logger::debug('Fetched shared post', ['id' => $id, 'url' => $url, 'uid' => $uid]);
3872 return $shared_item['uri-id'];
3875 Logger::warning('Post does not exist although it was supposed to had been fetched.', ['id' => $id, 'url' => $url, 'uid' => $uid]);