3 * @copyright Copyright (C) 2010-2021, the Friendica project
5 * @license GNU AGPL version 3 or any later version
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU Affero General Public License as
9 * published by the Free Software Foundation, either version 3 of the
10 * License, or (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU Affero General Public License for more details.
17 * You should have received a copy of the GNU Affero General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
22 namespace Friendica\Model;
24 use Friendica\Content\Text\BBCode;
25 use Friendica\Content\Text\HTML;
26 use Friendica\Core\Hook;
27 use Friendica\Core\Logger;
28 use Friendica\Core\Protocol;
29 use Friendica\Core\Renderer;
30 use Friendica\Core\Session;
31 use Friendica\Core\System;
32 use Friendica\Model\Tag;
33 use Friendica\Core\Worker;
34 use Friendica\Database\DBA;
36 use Friendica\Model\Post;
37 use Friendica\Protocol\Activity;
38 use Friendica\Protocol\ActivityPub;
39 use Friendica\Protocol\Diaspora;
40 use Friendica\Util\DateTimeFormat;
41 use Friendica\Util\HTTPSignature;
42 use Friendica\Util\LDSignature;
43 use Friendica\Util\Map;
44 use Friendica\Util\Network;
45 use Friendica\Util\Proxy;
46 use Friendica\Util\Strings;
47 use Friendica\Worker\Delivery;
48 use LanguageDetection\Language;
52 // Posting types, inspired by https://www.w3.org/TR/activitystreams-vocabulary/#object-types
59 const PT_DOCUMENT = 19;
61 const PT_PERSONAL_NOTE = 128;
63 // Posting reasons (Why had a post been stored for a user?)
70 const PR_FOLLOWER = 69;
71 const PR_ANNOUNCEMENT = 70;
72 const PR_COMMENT = 71;
76 const PR_FETCHED = 75;
78 // Field list that is used to display the items
79 const DISPLAY_FIELDLIST = [
80 'uid', 'id', 'parent', 'guid', 'network', 'gravity',
81 'uri-id', 'uri', 'thr-parent-id', 'thr-parent', 'parent-uri-id', 'parent-uri',
82 'commented', 'created', 'edited', 'received', 'verb', 'object-type', 'postopts', 'plink',
83 'wall', 'private', 'starred', 'origin', 'parent-origin', 'title', 'body', 'language',
84 'content-warning', 'location', 'coord', 'app', 'rendered-hash', 'rendered-html', 'object',
85 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid', 'mention',
86 'author-id', 'author-link', 'author-name', 'author-avatar', 'author-network',
87 'owner-id', 'owner-link', 'owner-name', 'owner-avatar', 'owner-network', 'owner-contact-type',
88 'causer-id', 'causer-link', 'causer-name', 'causer-avatar', 'causer-contact-type', 'causer-network',
89 'contact-id', 'contact-uid', 'contact-link', 'contact-name', 'contact-avatar',
90 'writable', 'self', 'cid', 'alias',
91 'event-created', 'event-edited', 'event-start', 'event-finish',
92 'event-summary', 'event-desc', 'event-location', 'event-type',
93 'event-nofinish', 'event-adjust', 'event-ignore', 'event-id',
94 'delivery_queue_count', 'delivery_queue_done', 'delivery_queue_failed'
97 // Field list that is used to deliver items via the protocols
98 const DELIVER_FIELDLIST = ['uid', 'id', 'parent', 'uri-id', 'uri', 'thr-parent', 'parent-uri', 'guid',
99 'parent-guid', 'received', 'created', 'edited', 'verb', 'object-type', 'object', 'target',
100 'private', 'title', 'body', 'raw-body', 'location', 'coord', 'app',
101 'inform', 'deleted', 'extid', 'post-type', 'post-reason', 'gravity',
102 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid',
103 'author-id', 'author-link', 'author-name', 'author-avatar', 'owner-id', 'owner-link', 'contact-uid',
104 'signed_text', 'network', 'wall', 'contact-id', 'plink', 'forum_mode', 'origin',
105 'thr-parent-id', 'parent-uri-id', 'postopts', 'pubmail',
106 'event-created', 'event-edited', 'event-start', 'event-finish',
107 'event-summary', 'event-desc', 'event-location', 'event-type',
108 'event-nofinish', 'event-adjust', 'event-ignore', 'event-id'];
110 // All fields in the item table
111 const ITEM_FIELDLIST = ['id', 'uid', 'parent', 'uri', 'parent-uri', 'thr-parent',
112 'guid', 'uri-id', 'parent-uri-id', 'thr-parent-id', 'vid',
113 'contact-id', 'wall', 'gravity', 'extid', 'psid',
114 'created', 'edited', 'commented', 'received', 'changed', 'verb',
115 'postopts', 'plink', 'resource-id', 'event-id', 'inform',
116 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid', 'post-type', 'post-reason',
117 'private', 'pubmail', 'visible', 'starred',
118 'unseen', 'deleted', 'origin', 'forum_mode', 'mention', 'global', 'network',
119 'title', 'content-warning', 'body', 'location', 'coord', 'app',
120 'rendered-hash', 'rendered-html', 'object-type', 'object', 'target-type', 'target',
121 'author-id', 'author-link', 'author-name', 'author-avatar', 'author-network',
122 'owner-id', 'owner-link', 'owner-name', 'owner-avatar', 'causer-id'];
124 // List of all verbs that don't need additional content data.
125 // Never reorder or remove entries from this list. Just add new ones at the end, if needed.
127 Activity::LIKE, Activity::DISLIKE,
128 Activity::ATTEND, Activity::ATTENDNO, Activity::ATTENDMAYBE,
137 * Update existing item entries
139 * @param array $fields The fields that are to be changed
140 * @param array $condition The condition for finding the item entries
142 * In the future we may have to change permissions as well.
143 * Then we had to add the user id as third parameter.
145 * A return value of "0" doesn't mean an error - but that 0 rows had been changed.
147 * @return integer|boolean number of affected rows - or "false" if there was an error
148 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
150 public static function update(array $fields, array $condition)
152 if (empty($condition) || empty($fields)) {
156 if (isset($fields['extid'])) {
157 $fields['external-id'] = ItemURI::getIdByURI($fields['extid']);
160 if (!empty($fields['verb'])) {
161 $fields['vid'] = Verb::getID($fields['verb']);
164 if (!empty($fields['edited'])) {
165 $previous = Post::selectFirst(['edited'], $condition);
168 $rows = Post::update($fields, $condition);
169 if (is_bool($rows)) {
173 // We only need to call the line by line update for specific fields
174 if (empty($fields['body']) && empty($fields['file']) &&
175 empty($fields['attach']) && empty($fields['edited'])) {
179 Logger::info('Updating per single row method', ['fields' => $fields, 'condition' => $condition]);
181 $items = Post::select(['id', 'origin', 'uri-id', 'uid', 'author-network'], $condition);
185 while ($item = DBA::fetch($items)) {
186 if (!empty($fields['body'])) {
187 Post\Media::insertFromAttachmentData($item['uri-id'], $fields['body']);
189 $content_fields = ['raw-body' => trim($fields['raw-body'] ?? $fields['body'])];
191 // Remove all media attachments from the body and store them in the post-media table
192 // @todo On shared postings (Diaspora style and commented reshare) don't fetch content from the shared part
193 $content_fields['raw-body'] = Post\Media::insertFromBody($item['uri-id'], $content_fields['raw-body']);
194 $content_fields['raw-body'] = self::setHashtags($content_fields['raw-body']);
196 if ($item['author-network'] != Protocol::DFRN) {
197 Post\Media::insertFromRelevantUrl($item['uri-id'], $content_fields['raw-body']);
200 Post\Content::update($item['uri-id'], $content_fields);
203 if (!empty($fields['file'])) {
204 Post\Category::storeTextByURIId($item['uri-id'], $item['uid'], $fields['file']);
207 if (!empty($fields['attach'])) {
208 Post\Media::insertFromAttachment($item['uri-id'], $fields['attach']);
211 // We only need to notfiy others when it is an original entry from us.
212 // Only call the notifier when the item had been edited and records had been changed.
213 if ($item['origin'] && !empty($fields['edited']) && ($previous['edited'] != $fields['edited'])) {
214 $notify_items[] = $item['id'];
220 foreach ($notify_items as $notify_item) {
221 $post = Post::selectFirst(['uri-id', 'uid'], ['id' => $notify_item]);
222 Worker::add(PRIORITY_HIGH, "Notifier", Delivery::POST, (int)$post['uri-id'], (int)$post['uid']);
229 * Delete an item and notify others about it - if it was ours
231 * @param array $condition The condition for finding the item entries
232 * @param integer $priority Priority for the notification
233 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
235 public static function markForDeletion($condition, $priority = PRIORITY_HIGH)
237 $items = Post::select(['id'], $condition);
238 while ($item = Post::fetch($items)) {
239 self::markForDeletionById($item['id'], $priority);
245 * Delete an item for an user and notify others about it - if it was ours
247 * @param array $condition The condition for finding the item entries
248 * @param integer $uid User who wants to delete this item
249 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
251 public static function deleteForUser($condition, $uid)
257 $items = Post::select(['id', 'uid', 'uri-id'], $condition);
258 while ($item = Post::fetch($items)) {
259 if (in_array($item['uid'], [$uid, 0])) {
260 Post\User::update($item['uri-id'], $uid, ['hidden' => true], true);
261 Post\ThreadUser::update($item['uri-id'], $uid, ['hidden' => true], true);
264 if ($item['uid'] == $uid) {
265 self::markForDeletionById($item['id'], PRIORITY_HIGH);
266 } elseif ($item['uid'] != 0) {
267 Logger::notice('Wrong ownership. Not deleting item', ['id' => $item['id']]);
274 * Mark an item for deletion, delete related data and notify others about it - if it was ours
276 * @param integer $item_id
277 * @param integer $priority Priority for the notification
279 * @return boolean success
280 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
282 public static function markForDeletionById($item_id, $priority = PRIORITY_HIGH)
284 Logger::info('Mark item for deletion by id', ['id' => $item_id, 'callstack' => System::callstack()]);
285 // locate item to be deleted
286 $fields = ['id', 'uri', 'uri-id', 'uid', 'parent', 'parent-uri-id', 'origin',
287 'deleted', 'resource-id', 'event-id',
288 'verb', 'object-type', 'object', 'target', 'contact-id', 'psid', 'gravity'];
289 $item = Post::selectFirst($fields, ['id' => $item_id]);
290 if (!DBA::isResult($item)) {
291 Logger::info('Item not found.', ['id' => $item_id]);
295 if ($item['deleted']) {
296 Logger::info('Item has already been marked for deletion.', ['id' => $item_id]);
300 $parent = Post::selectFirst(['origin'], ['id' => $item['parent']]);
301 if (!DBA::isResult($parent)) {
302 $parent = ['origin' => false];
305 // clean up categories and tags so they don't end up as orphans
306 Post\Category::deleteByURIId($item['uri-id'], $item['uid']);
309 * If item is a link to a photo resource, nuke all the associated photos
310 * (visitors will not have photo resources)
311 * This only applies to photos uploaded from the photos page. Photos inserted into a post do not
312 * generate a resource-id and therefore aren't intimately linked to the item.
314 /// @TODO: this should first check if photo is used elsewhere
315 if (strlen($item['resource-id'])) {
316 Photo::delete(['resource-id' => $item['resource-id'], 'uid' => $item['uid']]);
319 // If item is a link to an event, delete the event.
320 if (intval($item['event-id'])) {
321 Event::delete($item['event-id']);
324 // If item has attachments, drop them
325 $attachments = Post\Media::getByURIId($item['uri-id'], [Post\Media::DOCUMENT]);
326 foreach($attachments as $attachment) {
327 if (preg_match("|attach/(\d+)|", $attachment['url'], $matches)) {
328 Attach::delete(['id' => $matches[1], 'uid' => $item['uid']]);
332 // Set the item to "deleted"
333 $item_fields = ['deleted' => true, 'edited' => DateTimeFormat::utcNow(), 'changed' => DateTimeFormat::utcNow()];
334 Post::update($item_fields, ['id' => $item['id']]);
336 Post\Category::storeTextByURIId($item['uri-id'], $item['uid'], '');
338 if (!Post::exists(["`uri-id` = ? AND `uid` != 0 AND NOT `deleted`", $item['uri-id']])) {
339 self::markForDeletion(['uri-id' => $item['uri-id'], 'uid' => 0, 'deleted' => false], $priority);
342 Post\DeliveryData::delete($item['uri-id']);
344 // If it's the parent of a comment thread, kill all the kids
345 if ($item['gravity'] == GRAVITY_PARENT) {
346 self::markForDeletion(['parent' => $item['parent'], 'deleted' => false], $priority);
349 // Is it our comment and/or our thread?
350 if (($item['origin'] || $parent['origin']) && ($item['uid'] != 0)) {
351 // When we delete the original post we will delete all existing copies on the server as well
352 self::markForDeletion(['uri-id' => $item['uri-id'], 'deleted' => false], $priority);
354 // send the notification upstream/downstream
356 Worker::add(['priority' => $priority, 'dont_fork' => true], "Notifier", Delivery::DELETION, (int)$item['uri-id'], (int)$item['uid']);
358 } elseif ($item['uid'] != 0) {
359 Post\User::update($item['uri-id'], $item['uid'], ['hidden' => true]);
360 Post\ThreadUser::update($item['uri-id'], $item['uid'], ['hidden' => true]);
363 Logger::info('Item has been marked for deletion.', ['id' => $item_id]);
368 private static function guid($item, $notify)
370 if (!empty($item['guid'])) {
371 return Strings::escapeTags(trim($item['guid']));
375 // We have to avoid duplicates. So we create the GUID in form of a hash of the plink or uri.
376 // We add the hash of our own host because our host is the original creator of the post.
377 $prefix_host = DI::baseUrl()->getHostname();
381 // We are only storing the post so we create a GUID from the original hostname.
382 if (!empty($item['author-link'])) {
383 $parsed = parse_url($item['author-link']);
384 if (!empty($parsed['host'])) {
385 $prefix_host = $parsed['host'];
389 if (empty($prefix_host) && !empty($item['plink'])) {
390 $parsed = parse_url($item['plink']);
391 if (!empty($parsed['host'])) {
392 $prefix_host = $parsed['host'];
396 if (empty($prefix_host) && !empty($item['uri'])) {
397 $parsed = parse_url($item['uri']);
398 if (!empty($parsed['host'])) {
399 $prefix_host = $parsed['host'];
403 // Is it in the format data@host.tld? - Used for mail contacts
404 if (empty($prefix_host) && !empty($item['author-link']) && strstr($item['author-link'], '@')) {
405 $mailparts = explode('@', $item['author-link']);
406 $prefix_host = array_pop($mailparts);
410 if (!empty($item['plink'])) {
411 $guid = self::guidFromUri($item['plink'], $prefix_host);
412 } elseif (!empty($item['uri'])) {
413 $guid = self::guidFromUri($item['uri'], $prefix_host);
415 $guid = System::createUUID(hash('crc32', $prefix_host));
421 private static function contactId($item)
423 if (!empty($item['contact-id']) && DBA::exists('contact', ['self' => true, 'id' => $item['contact-id']])) {
424 return $item['contact-id'];
425 } elseif (($item['gravity'] == GRAVITY_PARENT) && !empty($item['uid']) && !empty($item['contact-id']) && Contact::isSharing($item['contact-id'], $item['uid'])) {
426 return $item['contact-id'];
427 } elseif (!empty($item['uid']) && !Contact::isSharing($item['author-id'], $item['uid'])) {
428 return $item['author-id'];
429 } elseif (!empty($item['contact-id'])) {
430 return $item['contact-id'];
432 $contact_id = Contact::getIdForURL($item['author-link'], $item['uid']);
433 if (!empty($contact_id)) {
437 return $item['author-id'];
441 * Write an item array into a spool file to be inserted later.
442 * This command is called whenever there are issues storing an item.
444 * @param array $item The item fields that are to be inserted
447 private static function spool($orig_item)
449 // Now we store the data in the spool directory
450 // We use "microtime" to keep the arrival order and "mt_rand" to avoid duplicates
451 $file = 'item-' . round(microtime(true) * 10000) . '-' . mt_rand() . '.msg';
453 $spoolpath = get_spoolpath();
454 if ($spoolpath != "") {
455 $spool = $spoolpath . '/' . $file;
457 file_put_contents($spool, json_encode($orig_item));
458 Logger::warning("Item wasn't stored - Item was spooled into file", ['file' => $file]);
463 * Check if the item array is a duplicate
466 * @return boolean is it a duplicate?
468 private static function isDuplicate(array $item)
470 // Checking if there is already an item with the same guid
471 $condition = ['guid' => $item['guid'], 'network' => $item['network'], 'uid' => $item['uid']];
472 if (Post::exists($condition)) {
473 Logger::notice('Found already existing item', [
474 'guid' => $item['guid'],
475 'uid' => $item['uid'],
476 'network' => $item['network']
481 $condition = ['uri-id' => $item['uri-id'], 'uid' => $item['uid'],
482 'network' => [$item['network'], Protocol::DFRN]];
483 if (Post::exists($condition)) {
484 Logger::notice('duplicated item with the same uri found.', $item);
488 // On Friendica and Diaspora the GUID is unique
489 if (in_array($item['network'], [Protocol::DFRN, Protocol::DIASPORA])) {
490 $condition = ['guid' => $item['guid'], 'uid' => $item['uid']];
491 if (Post::exists($condition)) {
492 Logger::notice('duplicated item with the same guid found.', $item);
495 } elseif ($item['network'] == Protocol::OSTATUS) {
496 // Check for an existing post with the same content. There seems to be a problem with OStatus.
497 $condition = ["`body` = ? AND `network` = ? AND `created` = ? AND `contact-id` = ? AND `uid` = ?",
498 $item['body'], $item['network'], $item['created'], $item['contact-id'], $item['uid']];
499 if (Post::exists($condition)) {
500 Logger::notice('duplicated item with the same body found.', $item);
506 * Check for already added items.
507 * There is a timing issue here that sometimes creates double postings.
508 * An unique index would help - but the limitations of MySQL (maximum size of index values) prevent this.
510 if (($item['uid'] == 0) && Post::exists(['uri-id' => $item['uri-id'], 'uid' => 0])) {
511 Logger::notice('Global item already stored.', ['uri-id' => $item['uri-id'], 'network' => $item['network']]);
519 * Check if the item array is valid
522 * @return boolean item is valid
524 public static function isValid(array $item)
526 // When there is no content then we don't post it
527 if (($item['body'] . $item['title'] == '') && (empty($item['uri-id']) || !Post\Media::existsByURIId($item['uri-id']))) {
528 Logger::notice('No body, no title.');
532 if (!empty($item['uid'])) {
533 $owner = User::getOwnerDataById($item['uid'], false);
535 Logger::notice('Missing item user owner data', ['uid' => $item['uid']]);
539 if ($owner['account_expired'] || $owner['account_removed']) {
540 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']]);
545 if (!empty($item['author-id']) && Contact::isBlocked($item['author-id'])) {
546 Logger::notice('Author is blocked node-wide', ['author-link' => $item['author-link'], 'item-uri' => $item['uri']]);
547 self::remoteDelete($item);
551 if (!empty($item['author-link']) && Network::isUrlBlocked($item['author-link'])) {
552 Logger::notice('Author server is blocked', ['author-link' => $item['author-link'], 'item-uri' => $item['uri']]);
553 self::remoteDelete($item);
557 if (!empty($item['owner-id']) && Contact::isBlocked($item['owner-id'])) {
558 Logger::notice('Owner is blocked node-wide', ['owner-link' => $item['owner-link'], 'item-uri' => $item['uri']]);
559 self::remoteDelete($item);
563 if (!empty($item['owner-link']) && Network::isUrlBlocked($item['owner-link'])) {
564 Logger::notice('Owner server is blocked', ['owner-link' => $item['owner-link'], 'item-uri' => $item['uri']]);
565 self::remoteDelete($item);
569 if (!empty($item['uid']) && !self::isAllowedByUser($item, $item['uid'])) {
570 self::remoteDelete($item);
574 if ($item['verb'] == Activity::FOLLOW) {
575 if (!$item['origin'] && ($item['author-id'] == Contact::getPublicIdByUserId($item['uid']))) {
576 // Our own follow request can be relayed to us. We don't store it to avoid notification chaos.
577 Logger::info("Follow: Don't store not origin follow request", ['parent-uri' => $item['parent-uri']]);
581 $condition = ['verb' => Activity::FOLLOW, 'uid' => $item['uid'],
582 'parent-uri' => $item['parent-uri'], 'author-id' => $item['author-id']];
583 if (Post::exists($condition)) {
584 // It happens that we receive multiple follow requests by the same author - we only store one.
585 Logger::info('Follow: Found existing follow request from author', ['author-id' => $item['author-id'], 'parent-uri' => $item['parent-uri']]);
594 * Try to delete the remote (unwanted) item
598 private static function remoteDelete(array $item)
600 if ($item['gravity'] == GRAVITY_PARENT) {
605 $owner = User::getOwnerDataById($item['uid']);
606 $contact = Contact::getById($item['contact-id']);
608 if (FContact::getByURL($contact['addr'], false)) {
609 Logger::info('Send Diaspora retraction for post', ['addr' => $contact['addr'], 'item' => $item]);
610 Diaspora::sendRetraction($item, $owner, $contact, in_array($item['private'], [self::UNLISTED, self::PUBLIC]));
611 } elseif ($profile = APContact::getByURL($contact['url'], false)) {
612 Logger::info('Send ActivityPub deletion for post', ['url' => $contact['url'], 'item' => $item]);
613 $data = ['@context' => ActivityPub::CONTEXT,
614 'id' => $item['uri'] . '/Delete',
616 'actor' => $owner['url'],
617 'object' => ['type' => 'Tombstone', 'id' => $item['uri']],
618 'to' => [$profile['url']]];
620 $signed = LDSignature::sign($data, $owner);
621 return HTTPSignature::transmit($signed, $profile['inbox'], $item['uid']);
623 Logger::info('Unsupported protocol for deletion', ['network' => $contact['network']]);
628 * Check if the item array is too old
631 * @return boolean item is too old
633 public static function isTooOld(array $item)
635 // check for create date and expire time
636 $expire_interval = DI::config()->get('system', 'dbclean-expire-days', 0);
638 $user = DBA::selectFirst('user', ['expire'], ['uid' => $item['uid']]);
639 if (DBA::isResult($user) && ($user['expire'] > 0) && (($user['expire'] < $expire_interval) || ($expire_interval == 0))) {
640 $expire_interval = $user['expire'];
643 if (($expire_interval > 0) && !empty($item['created'])) {
644 $expire_date = time() - ($expire_interval * 86400);
645 $created_date = strtotime($item['created']);
646 if ($created_date < $expire_date) {
647 Logger::notice('Item created before expiration interval.', [
648 'created' => date('c', $created_date),
649 'expired' => date('c', $expire_date),
660 * Return the id of the given item array if it has been stored before
663 * @return integer item id
665 private static function getDuplicateID(array $item)
667 if (empty($item['network']) || in_array($item['network'], Protocol::FEDERATED)) {
668 $condition = ["`uri-id` = ? AND `uid` = ? AND `network` IN (?, ?, ?, ?)",
669 $item['uri-id'], $item['uid'],
670 Protocol::ACTIVITYPUB, Protocol::DIASPORA, Protocol::DFRN, Protocol::OSTATUS];
671 $existing = Post::selectFirst(['id', 'network'], $condition);
672 if (DBA::isResult($existing)) {
673 // We only log the entries with a different user id than 0. Otherwise we would have too many false positives
674 if ($item['uid'] != 0) {
675 Logger::notice('Item already existed for user', [
676 'uri-id' => $item['uri-id'],
677 'uid' => $item['uid'],
678 'network' => $item['network'],
679 'existing_id' => $existing["id"],
680 'existing_network' => $existing["network"]
684 return $existing["id"];
691 * Fetch top-level parent data for the given item array
694 * @return array item array with parent data
697 private static function getTopLevelParent(array $item)
699 $fields = ['uid', 'uri', 'parent-uri', 'id', 'deleted',
700 'uri-id', 'parent-uri-id',
701 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid',
702 'wall', 'private', 'forum_mode', 'origin', 'author-id'];
703 $condition = ['uri-id' => $item['thr-parent-id'], 'uid' => $item['uid']];
704 $params = ['order' => ['id' => false]];
705 $parent = Post::selectFirst($fields, $condition, $params);
707 if (!DBA::isResult($parent)) {
708 Logger::notice('item parent was not found - ignoring item', ['thr-parent-id' => $item['thr-parent-id'], 'uid' => $item['uid']]);
712 if ($parent['uri-id'] == $parent['parent-uri-id']) {
716 $condition = ['uri-id' => $parent['parent-uri-id'],
717 'parent-uri-id' => $parent['parent-uri-id'],
718 'uid' => $parent['uid']];
719 $params = ['order' => ['id' => false]];
720 $toplevel_parent = Post::selectFirst($fields, $condition, $params);
721 if (!DBA::isResult($toplevel_parent)) {
722 Logger::notice('item top level parent was not found - ignoring item', ['parent-uri-id' => $parent['parent-uri-id'], 'uid' => $parent['uid']]);
726 return $toplevel_parent;
730 * Get the gravity for the given item array
733 * @return integer gravity
735 private static function getGravity(array $item)
737 $activity = DI::activity();
739 if (isset($item['gravity'])) {
740 return intval($item['gravity']);
741 } elseif ($item['parent-uri-id'] === $item['uri-id']) {
742 return GRAVITY_PARENT;
743 } elseif ($activity->match($item['verb'], Activity::POST)) {
744 return GRAVITY_COMMENT;
745 } elseif ($activity->match($item['verb'], Activity::FOLLOW)) {
746 return GRAVITY_ACTIVITY;
747 } elseif ($activity->match($item['verb'], Activity::ANNOUNCE)) {
748 return GRAVITY_ACTIVITY;
750 Logger::info('Unknown gravity for verb', ['verb' => $item['verb']]);
751 return GRAVITY_UNKNOWN; // Should not happen
754 public static function insert($item, $notify = false, $dontcache = false)
758 $priority = PRIORITY_HIGH;
760 // If it is a posting where users should get notifications, then define it as wall posting
764 $item['network'] = Protocol::DFRN;
765 $item['protocol'] = Conversation::PARCEL_DIRECT;
766 $item['direction'] = Conversation::PUSH;
768 if (in_array($notify, PRIORITIES)) {
772 $item['network'] = trim(($item['network'] ?? '') ?: Protocol::PHANTOM);
775 $uid = intval($item['uid']);
777 $item['guid'] = self::guid($item, $notify);
778 $item['uri'] = substr(trim($item['uri'] ?? '') ?: self::newURI($item['uid'], $item['guid']), 0, 255);
781 $item['uri-id'] = ItemURI::insert(['uri' => $item['uri'], 'guid' => $item['guid']]);
783 // Backward compatibility: parent-uri used to be the direct parent uri.
784 // If it is provided without a thr-parent, it probably is the old behavior.
785 $item['thr-parent'] = trim($item['thr-parent'] ?? $item['parent-uri'] ?? $item['uri']);
786 $item['parent-uri'] = $item['thr-parent'];
788 $item['thr-parent-id'] = $item['parent-uri-id'] = ItemURI::getIdByURI($item['thr-parent']);
790 // Store conversation data
791 $item = Conversation::insert($item);
794 * Do we already have this item?
795 * We have to check several networks since Friendica posts could be repeated
796 * via OStatus (maybe Diasporsa as well)
798 $duplicate = self::getDuplicateID($item);
803 // Additional duplicate checks
804 /// @todo Check why the first duplication check returns the item number and the second a 0
805 if (self::isDuplicate($item)) {
809 if (!isset($item['post-type'])) {
810 $item['post-type'] = empty($item['title']) ? self::PT_NOTE : self::PT_ARTICLE;
813 $item['wall'] = intval($item['wall'] ?? 0);
814 $item['extid'] = trim($item['extid'] ?? '');
815 $item['author-name'] = trim($item['author-name'] ?? '');
816 $item['author-link'] = trim($item['author-link'] ?? '');
817 $item['author-avatar'] = trim($item['author-avatar'] ?? '');
818 $item['owner-name'] = trim($item['owner-name'] ?? '');
819 $item['owner-link'] = trim($item['owner-link'] ?? '');
820 $item['owner-avatar'] = trim($item['owner-avatar'] ?? '');
821 $item['received'] = (isset($item['received']) ? DateTimeFormat::utc($item['received']) : DateTimeFormat::utcNow());
822 $item['created'] = (isset($item['created']) ? DateTimeFormat::utc($item['created']) : $item['received']);
823 $item['edited'] = (isset($item['edited']) ? DateTimeFormat::utc($item['edited']) : $item['created']);
824 $item['changed'] = (isset($item['changed']) ? DateTimeFormat::utc($item['changed']) : $item['created']);
825 $item['commented'] = (isset($item['commented']) ? DateTimeFormat::utc($item['commented']) : $item['created']);
826 $item['title'] = substr(trim($item['title'] ?? ''), 0, 255);
827 $item['location'] = trim($item['location'] ?? '');
828 $item['coord'] = trim($item['coord'] ?? '');
829 $item['visible'] = (isset($item['visible']) ? intval($item['visible']) : 1);
830 $item['deleted'] = 0;
831 $item['verb'] = trim($item['verb'] ?? '');
832 $item['object-type'] = trim($item['object-type'] ?? '');
833 $item['object'] = trim($item['object'] ?? '');
834 $item['target-type'] = trim($item['target-type'] ?? '');
835 $item['target'] = trim($item['target'] ?? '');
836 $item['plink'] = substr(trim($item['plink'] ?? ''), 0, 255);
837 $item['allow_cid'] = trim($item['allow_cid'] ?? '');
838 $item['allow_gid'] = trim($item['allow_gid'] ?? '');
839 $item['deny_cid'] = trim($item['deny_cid'] ?? '');
840 $item['deny_gid'] = trim($item['deny_gid'] ?? '');
841 $item['private'] = intval($item['private'] ?? self::PUBLIC);
842 $item['body'] = trim($item['body'] ?? '');
843 $item['raw-body'] = trim($item['raw-body'] ?? $item['body']);
844 $item['app'] = trim($item['app'] ?? '');
845 $item['origin'] = intval($item['origin'] ?? 0);
846 $item['postopts'] = trim($item['postopts'] ?? '');
847 $item['resource-id'] = trim($item['resource-id'] ?? '');
848 $item['event-id'] = intval($item['event-id'] ?? 0);
849 $item['inform'] = trim($item['inform'] ?? '');
850 $item['file'] = trim($item['file'] ?? '');
852 // Items cannot be stored before they happen ...
853 if ($item['created'] > DateTimeFormat::utcNow()) {
854 $item['created'] = DateTimeFormat::utcNow();
857 // We haven't invented time travel by now.
858 if ($item['edited'] > DateTimeFormat::utcNow()) {
859 $item['edited'] = DateTimeFormat::utcNow();
862 $item['plink'] = ($item['plink'] ?? '') ?: DI::baseUrl() . '/display/' . urlencode($item['guid']);
864 $item['gravity'] = self::getGravity($item);
866 $item['language'] = self::getLanguage($item);
868 $default = ['url' => $item['author-link'], 'name' => $item['author-name'],
869 'photo' => $item['author-avatar'], 'network' => $item['network']];
870 $item['author-id'] = ($item['author-id'] ?? 0) ?: Contact::getIdForURL($item['author-link'], 0, null, $default);
872 $default = ['url' => $item['owner-link'], 'name' => $item['owner-name'],
873 'photo' => $item['owner-avatar'], 'network' => $item['network']];
874 $item['owner-id'] = ($item['owner-id'] ?? 0) ?: Contact::getIdForURL($item['owner-link'], 0, null, $default);
876 $actor = ($item['gravity'] == GRAVITY_PARENT) ? $item['owner-id'] : $item['author-id'];
877 if (!$item['origin'] && ($item['uid'] != 0) && Contact::isSharing($actor, $item['uid'])) {
878 $item['post-reason'] = self::PR_FOLLOWER;
881 // Ensure that there is an avatar cache
882 Contact::checkAvatarCache($item['author-id']);
883 Contact::checkAvatarCache($item['owner-id']);
885 // The contact-id should be set before "self::insert" was called - but there seems to be issues sometimes
886 $item["contact-id"] = self::contactId($item);
888 if (!empty($item['direction']) && in_array($item['direction'], [Conversation::PUSH, Conversation::RELAY]) &&
889 self::isTooOld($item)) {
890 Logger::info('Item is too old', ['item' => $item]);
894 if (!self::isValid($item)) {
898 if ($item['gravity'] !== GRAVITY_PARENT) {
899 $toplevel_parent = self::getTopLevelParent($item);
900 if (empty($toplevel_parent)) {
904 // If the thread originated from this node, we check the permission against the thread starter
905 $condition = ['uri-id' => $toplevel_parent['uri-id'], 'wall' => true];
906 $localTopLevelParent = Post::selectFirst(['uid'], $condition);
907 if (!empty($localTopLevelParent['uid']) && !self::isAllowedByUser($item, $localTopLevelParent['uid'])) {
911 $parent_id = $toplevel_parent['id'];
912 $item['parent-uri'] = $toplevel_parent['uri'];
913 $item['parent-uri-id'] = $toplevel_parent['uri-id'];
914 $item['deleted'] = $toplevel_parent['deleted'];
915 $item['allow_cid'] = $toplevel_parent['allow_cid'];
916 $item['allow_gid'] = $toplevel_parent['allow_gid'];
917 $item['deny_cid'] = $toplevel_parent['deny_cid'];
918 $item['deny_gid'] = $toplevel_parent['deny_gid'];
919 $parent_origin = $toplevel_parent['origin'];
921 // Don't federate received participation messages
922 if ($item['verb'] != Activity::FOLLOW) {
923 $item['wall'] = $toplevel_parent['wall'];
925 $item['wall'] = false;
926 // Participations are technical messages, so they are set to "seen" automatically
927 $item['unseen'] = false;
931 * If the parent is private, force privacy for the entire conversation
932 * This differs from the above settings as it subtly allows comments from
933 * email correspondents to be private even if the overall thread is not.
935 if ($toplevel_parent['private']) {
936 $item['private'] = $toplevel_parent['private'];
940 * Edge case. We host a public forum that was originally posted to privately.
941 * The original author commented, but as this is a comment, the permissions
942 * weren't fixed up so it will still show the comment as private unless we fix it here.
944 if ((intval($toplevel_parent['forum_mode']) == 1) && ($toplevel_parent['private'] != self::PUBLIC)) {
945 $item['private'] = self::PUBLIC;
948 // If its a post that originated here then tag the thread as "mention"
949 if ($item['origin'] && $item['uid']) {
950 DBA::update('post-thread-user', ['mention' => true], ['uri-id' => $item['parent-uri-id'], 'uid' => $item['uid']]);
951 Logger::info('tagged thread as mention', ['parent' => $parent_id, 'parent-uri-id' => $item['parent-uri-id'], 'uid' => $item['uid']]);
954 // Update the contact relations
955 Contact\Relation::store($toplevel_parent['author-id'], $item['author-id'], $item['created']);
958 $parent_origin = $item['origin'];
961 $item['parent-uri-id'] = ItemURI::getIdByURI($item['parent-uri']);
962 $item['thr-parent-id'] = ItemURI::getIdByURI($item['thr-parent']);
964 // Is this item available in the global items (with uid=0)?
965 if ($item["uid"] == 0) {
966 $item["global"] = true;
968 // Set the global flag on all items if this was a global item entry
969 Post::update(['global' => true], ['uri-id' => $item['uri-id']]);
971 $item['global'] = Post::exists(['uid' => 0, 'uri-id' => $item['uri-id']]);
975 if (!empty($item["allow_cid"] . $item["allow_gid"] . $item["deny_cid"] . $item["deny_gid"])) {
976 $item["private"] = self::PRIVATE;
980 $item['edit'] = false;
981 $item['parent'] = $parent_id;
983 // Trigger automatic reactions for addons
984 $item['api_source'] = true;
986 // We have to tell the hooks who we are - this really should be improved
988 $_SESSION['authenticated'] = true;
989 $_SESSION['uid'] = $uid;
990 $dummy_session = true;
992 $dummy_session = false;
995 Hook::callAll('post_local', $item);
997 if ($dummy_session) {
998 unset($_SESSION['authenticated']);
999 unset($_SESSION['uid']);
1002 Hook::callAll('post_remote', $item);
1005 if (!empty($item['cancel'])) {
1006 Logger::log('post cancelled by addon.');
1010 if (empty($item['vid']) && !empty($item['verb'])) {
1011 $item['vid'] = Verb::getID($item['verb']);
1014 // Creates or assigns the permission set
1015 $item['psid'] = PermissionSet::getIdFromACL(
1023 if (!empty($item['extid'])) {
1024 $item['external-id'] = ItemURI::getIdByURI($item['extid']);
1027 if ($item['verb'] == Activity::ANNOUNCE) {
1028 self::setOwnerforResharedItem($item);
1031 if (isset($item['attachments'])) {
1032 foreach ($item['attachments'] as $attachment) {
1033 $attachment['uri-id'] = $item['uri-id'];
1034 Post\Media::insert($attachment);
1036 unset($item['attachments']);
1039 Post\Media::insertFromAttachmentData($item['uri-id'], $item['body']);
1041 // Remove all media attachments from the body and store them in the post-media table
1042 $item['raw-body'] = Post\Media::insertFromBody($item['uri-id'], $item['raw-body']);
1043 $item['raw-body'] = self::setHashtags($item['raw-body']);
1045 if (!DBA::exists('contact', ['id' => $item['author-id'], 'network' => Protocol::DFRN])) {
1046 Post\Media::insertFromRelevantUrl($item['uri-id'], $item['raw-body']);
1049 // Check for hashtags in the body and repair or add hashtag links
1050 $item['body'] = self::setHashtags($item['body']);
1052 if (stristr($item['verb'], Activity::POKE)) {
1053 $notify_type = Delivery::POKE;
1055 $notify_type = Delivery::POST;
1058 // Filling item related side tables
1059 if (!empty($item['attach'])) {
1060 Post\Media::insertFromAttachment($item['uri-id'], $item['attach']);
1063 if (empty($item['event-id'])) {
1064 unset($item['event-id']);
1066 $ev = Event::fromBBCode($item['body']);
1067 if ((!empty($ev['desc']) || !empty($ev['summary'])) && !empty($ev['start'])) {
1068 Logger::info('Event found.');
1069 $ev['cid'] = $item['contact-id'];
1070 $ev['uid'] = $item['uid'];
1071 $ev['uri'] = $item['uri'];
1072 $ev['edited'] = $item['edited'];
1073 $ev['private'] = $item['private'];
1074 $ev['guid'] = $item['guid'];
1075 $ev['plink'] = $item['plink'];
1076 $ev['network'] = $item['network'];
1077 $ev['protocol'] = $item['protocol'];
1078 $ev['direction'] = $item['direction'];
1079 $ev['source'] = $item['source'];
1081 $event = DBA::selectFirst('event', ['id'], ['uri' => $item['uri'], 'uid' => $item['uid']]);
1082 if (DBA::isResult($event)) {
1083 $ev['id'] = $event['id'];
1086 $item['event-id'] = Event::store($ev);
1087 Logger::info('Event was stored', ['id' => $item['event-id']]);
1091 if (empty($item['causer-id'])) {
1092 unset($item['causer-id']);
1095 Post::insert($item['uri-id'], $item);
1097 if ($item['gravity'] == GRAVITY_PARENT) {
1098 Post\Thread::insert($item['uri-id'], $item);
1101 if (!in_array($item['verb'], self::ACTIVITIES)) {
1102 Post\Content::insert($item['uri-id'], $item);
1105 // Create Diaspora signature
1106 if ($item['origin'] && empty($item['diaspora_signed_text']) && ($item['gravity'] != GRAVITY_PARENT)) {
1107 $signed = Diaspora::createCommentSignature($uid, $item);
1108 if (!empty($signed)) {
1109 $item['diaspora_signed_text'] = json_encode($signed);
1113 if (!empty($item['diaspora_signed_text'])) {
1114 DBA::replace('diaspora-interaction', ['uri-id' => $item['uri-id'], 'interaction' => $item['diaspora_signed_text']]);
1117 // Attached file links
1118 if (!empty($item['file'])) {
1119 Post\Category::storeTextByURIId($item['uri-id'], $item['uid'], $item['file']);
1122 // Delivery relevant data
1123 $delivery_data = Post\DeliveryData::extractFields($item);
1125 if (!empty($item['origin']) || !empty($item['wall']) || !empty($delivery_data['postopts']) || !empty($delivery_data['inform'])) {
1126 Post\DeliveryData::insert($item['uri-id'], $delivery_data);
1129 // Store tags from the body if this hadn't been handled previously in the protocol classes
1130 if (!Tag::existsForPost($item['uri-id'])) {
1131 Tag::storeFromBody($item['uri-id'], $item['body']);
1134 $condition = ['uri-id' => $item['uri-id'], 'uid' => $item['uid']];
1135 if (Post::exists($condition)) {
1136 Logger::notice('Item is already inserted - aborting', $condition);
1140 $post_user_id = Post\User::insert($item['uri-id'], $item['uid'], $item);
1141 if (!$post_user_id) {
1142 Logger::notice('Post-User is already inserted - aborting', ['uid' => $item['uid'], 'uri-id' => $item['uri-id']]);
1146 if ($item['gravity'] == GRAVITY_PARENT) {
1147 $item['post-user-id'] = $post_user_id;
1148 Post\ThreadUser::insert($item['uri-id'], $item['uid'], $item);
1151 Logger::notice('created item', ['post-id' => $post_user_id, 'uid' => $item['uid'], 'network' => $item['network'], 'uri-id' => $item['uri-id'], 'guid' => $item['guid']]);
1153 $posted_item = Post::selectFirst(self::ITEM_FIELDLIST, ['post-user-id' => $post_user_id]);
1154 if (!DBA::isResult($posted_item)) {
1155 // On failure store the data into a spool file so that the "SpoolPost" worker can try again later.
1156 Logger::warning('Could not store item. it will be spooled', ['id' => $post_user_id]);
1157 self::spool($orig_item);
1161 // update the commented timestamp on the parent
1162 if (DI::config()->get('system', 'like_no_comment')) {
1163 // Update when it is a comment
1164 $update_commented = in_array($posted_item['gravity'], [GRAVITY_PARENT, GRAVITY_COMMENT]);
1166 // Update when it isn't a follow or tag verb
1167 $update_commented = !in_array($posted_item['verb'], [Activity::FOLLOW, Activity::TAG]);
1170 if ($update_commented) {
1171 $fields = ['commented' => DateTimeFormat::utcNow(), 'changed' => DateTimeFormat::utcNow()];
1173 $fields = ['changed' => DateTimeFormat::utcNow()];
1176 Post::update($fields, ['uri-id' => $posted_item['parent-uri-id'], 'uid' => $posted_item['uid']]);
1178 // In that function we check if this is a forum post. Additionally we delete the item under certain circumstances
1179 if (self::tagDeliver($posted_item['uid'], $post_user_id)) {
1180 // Get the user information for the logging
1181 $user = User::getById($uid);
1183 Logger::notice('Item had been deleted', ['id' => $post_user_id, 'user' => $uid, 'account-type' => $user['account-type']]);
1189 Hook::callAll('post_local_end', $posted_item);
1191 Hook::callAll('post_remote_end', $posted_item);
1195 if ($posted_item['gravity'] === GRAVITY_PARENT) {
1196 self::addShadow($post_user_id);
1198 self::addShadowPost($post_user_id);
1201 self::updateContact($posted_item);
1203 Post\UserNotification::setNotification($posted_item['uri-id'], $posted_item['uid']);
1205 check_user_notification($posted_item['uri-id'], $posted_item['uid']);
1207 // Distribute items to users who subscribed to their tags
1208 self::distributeByTags($posted_item);
1210 // Automatically reshare the item if the "remote_self" option is selected
1211 self::autoReshare($posted_item);
1213 $transmit = $notify || ($posted_item['visible'] && ($parent_origin || $posted_item['origin']));
1216 // Don't relay participation messages
1217 if (($posted_item['verb'] == Activity::FOLLOW) &&
1218 (!$posted_item['origin'] || ($posted_item['author-id'] != Contact::getPublicIdByUserId($uid)))) {
1219 Logger::info('Participation messages will not be relayed', ['item' => $posted_item['id'], 'uri' => $posted_item['uri'], 'verb' => $posted_item['verb']]);
1225 Worker::add(['priority' => $priority, 'dont_fork' => true], 'Notifier', $notify_type, (int)$posted_item['uri-id'], (int)$posted_item['uid']);
1228 return $post_user_id;
1232 * Change the owner of a parent item if it had been shared by a forum
1234 * (public) forum posts in the new format consist of the regular post by the author
1235 * followed by an announce message sent from the forum account.
1236 * Changing the owner helps in grouping forum posts.
1238 * @param array $item
1241 private static function setOwnerforResharedItem(array $item)
1243 $parent = Post::selectFirst(['id', 'causer-id', 'owner-id', 'author-id', 'author-link', 'origin', 'post-reason'],
1244 ['uri-id' => $item['thr-parent-id'], 'uid' => $item['uid']]);
1245 if (!DBA::isResult($parent)) {
1246 Logger::error('Parent not found', ['uri-id' => $item['thr-parent-id'], 'uid' => $item['uid']]);
1250 $author = Contact::selectFirst(['url', 'contact-type', 'network'], ['id' => $item['author-id']]);
1251 if (!DBA::isResult($author)) {
1252 Logger::error('Author not found', ['id' => $item['author-id']]);
1256 $cid = Contact::getIdForURL($author['url'], $item['uid']);
1257 if (empty($cid) || !Contact::isSharing($cid, $item['uid'])) {
1258 Logger::info('The resharer is not a following contact: quit', ['resharer' => $author['url'], 'uid' => $item['uid'], 'cid' => $cid]);
1262 if ($author['contact-type'] != Contact::TYPE_COMMUNITY) {
1263 if ($parent['post-reason'] == self::PR_ANNOUNCEMENT) {
1264 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']]);
1268 if (Contact::isSharing($parent['owner-id'], $item['uid'])) {
1269 Logger::info('The resharer is no forum: quit', ['resharer' => $item['author-id'], 'owner' => $parent['owner-id'], 'author' => $parent['author-id'], 'uid' => $item['uid']]);
1274 self::update(['post-reason' => self::PR_ANNOUNCEMENT, 'causer-id' => $item['author-id']], ['id' => $parent['id']]);
1275 Logger::info('Set announcement post-reason', ['uri-id' => $item['uri-id'], 'thr-parent-id' => $item['thr-parent-id'], 'uid' => $item['uid']]);
1279 * Distribute the given item to users who subscribed to their tags
1281 * @param array $item Processed item
1283 private static function distributeByTags(array $item)
1285 if (($item['uid'] != 0) || ($item['gravity'] != GRAVITY_PARENT) || !in_array($item['network'], Protocol::FEDERATED)) {
1289 $uids = Tag::getUIDListByURIId($item['uri-id']);
1290 foreach ($uids as $uid) {
1291 if (Contact::isSharing($item['author-id'], $uid)) {
1294 $fields = ['post-reason' => self::PR_TAG];
1297 $stored = self::storeForUserByUriId($item['uri-id'], $uid, $fields);
1298 Logger::info('Stored item for users', ['uri-id' => $item['uri-id'], 'uid' => $uid, 'fields' => $fields, 'stored' => $stored]);
1303 * Distributes public items to the receivers
1305 * @param integer $itemid Item ID that should be added
1306 * @param string $signed_text Original text (for Diaspora signatures), JSON encoded.
1307 * @throws \Exception
1309 public static function distribute($itemid, $signed_text = '')
1311 $condition = ["`id` IN (SELECT `parent` FROM `post-user-view` WHERE `id` = ?)", $itemid];
1312 $parent = Post::selectFirst(['owner-id'], $condition);
1313 if (!DBA::isResult($parent)) {
1314 Logger::warning('Item not found', ['condition' => $condition]);
1318 // Only distribute public items from native networks
1319 $condition = ['id' => $itemid, 'uid' => 0,
1320 'network' => array_merge(Protocol::FEDERATED ,['']),
1321 'visible' => true, 'deleted' => false, 'private' => [self::PUBLIC, self::UNLISTED]];
1322 $item = Post::selectFirst(self::ITEM_FIELDLIST, $condition);
1323 if (!DBA::isResult($item)) {
1324 Logger::warning('Item not found', ['condition' => $condition]);
1328 $origin = $item['origin'];
1332 /// @todo add a field "pcid" in the contact table that referrs to the public contact id.
1333 $owner = DBA::selectFirst('contact', ['url', 'nurl', 'alias'], ['id' => $parent['owner-id']]);
1334 if (!DBA::isResult($owner)) {
1338 $condition = ['nurl' => $owner['nurl'], 'rel' => [Contact::SHARING, Contact::FRIEND]];
1339 $contacts = DBA::select('contact', ['uid'], $condition);
1340 while ($contact = DBA::fetch($contacts)) {
1341 if ($contact['uid'] == 0) {
1345 $users[$contact['uid']] = $contact['uid'];
1347 DBA::close($contacts);
1349 $condition = ['alias' => $owner['url'], 'rel' => [Contact::SHARING, Contact::FRIEND]];
1350 $contacts = DBA::select('contact', ['uid'], $condition);
1351 while ($contact = DBA::fetch($contacts)) {
1352 if ($contact['uid'] == 0) {
1356 $users[$contact['uid']] = $contact['uid'];
1358 DBA::close($contacts);
1360 if (!empty($owner['alias'])) {
1361 $condition = ['nurl' => Strings::normaliseLink($owner['alias']), 'rel' => [Contact::SHARING, Contact::FRIEND]];
1362 $contacts = DBA::select('contact', ['uid'], $condition);
1363 while ($contact = DBA::fetch($contacts)) {
1364 if ($contact['uid'] == 0) {
1368 $users[$contact['uid']] = $contact['uid'];
1370 DBA::close($contacts);
1375 if ($item['uri-id'] != $item['parent-uri-id']) {
1376 $parents = Post::select(['uid', 'origin'], ["`uri-id` = ? AND `uid` != 0", $item['parent-uri-id']]);
1377 while ($parent = Post::fetch($parents)) {
1378 $users[$parent['uid']] = $parent['uid'];
1379 if ($parent['origin'] && !$origin) {
1380 $origin_uid = $parent['uid'];
1383 DBA::close($parents);
1386 foreach ($users as $uid) {
1387 if ($origin_uid == $uid) {
1388 $item['diaspora_signed_text'] = $signed_text;
1390 self::storeForUser($item, $uid);
1395 * Store a public item defined by their URI-ID for the given users
1397 * @param integer $uri_id URI-ID of the given item
1398 * @param integer $uid The user that will receive the item entry
1399 * @param array $fields Additional fields to be stored
1400 * @param integer $source_uid User id of the source post
1401 * @return integer stored item id
1403 public static function storeForUserByUriId(int $uri_id, int $uid, array $fields = [], int $source_uid = 0)
1405 if ($uid == $source_uid) {
1406 Logger::warning('target UID must not be be equal to the source UID', ['uri-id' => $uri_id, 'uid' => $uid]);
1410 $item = Post::selectFirst(self::ITEM_FIELDLIST, ['uri-id' => $uri_id, 'uid' => $source_uid]);
1411 if (!DBA::isResult($item)) {
1412 Logger::warning('Item could not be fetched', ['uri-id' => $uri_id, 'uid' => $source_uid]);
1416 if (($source_uid == 0) && (($item['private'] == self::PRIVATE) || !in_array($item['network'], Protocol::FEDERATED))) {
1417 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']]);
1421 $item['post-reason'] = self::PR_STORED;
1423 $item = array_merge($item, $fields);
1425 $is_reshare = ($item['gravity'] == GRAVITY_ACTIVITY) && ($item['verb'] == Activity::ANNOUNCE);
1427 if ((($item['gravity'] == GRAVITY_PARENT) || $is_reshare) &&
1428 DI::pConfig()->get($uid, 'system', 'accept_only_sharer') &&
1429 !Contact::isSharingByURL($item['author-link'], $uid) &&
1430 !Contact::isSharingByURL($item['owner-link'], $uid)) {
1431 Logger::info('Contact is not a follower, thread will not be stored', ['author' => $item['author-link'], 'uid' => $uid]);
1435 if ((($item['gravity'] == GRAVITY_COMMENT) || $is_reshare) && !Post::exists(['uri-id' => $item['thr-parent-id'], 'uid' => $uid])) {
1436 // Only do an auto complete with the source uid "0" to prevent privavy problems
1437 $causer = $item['causer-id'] ?: $item['author-id'];
1438 $result = self::storeForUserByUriId($item['thr-parent-id'], $uid, ['causer-id' => $causer, 'post-reason' => self::PR_FETCHED]);
1439 Logger::info('Fetched thread parent', ['uri-id' => $item['thr-parent-id'], 'uid' => $uid, 'causer' => $causer, 'result' => $result]);
1442 $stored = self::storeForUser($item, $uid);
1443 Logger::info('Item stored for user', ['uri-id' => $item['uri-id'], 'uid' => $uid, 'source-uid' => $source_uid, 'stored' => $stored]);
1448 * Store a public item array for the given users
1450 * @param array $item The item entry that will be stored
1451 * @param integer $uid The user that will receive the item entry
1452 * @return integer stored item id
1453 * @throws \Exception
1455 private static function storeForUser(array $item, int $uid)
1457 if (Post::exists(['uri-id' => $item['uri-id'], 'uid' => $uid])) {
1458 Logger::info('Item already exists', ['uri-id' => $item['uri-id'], 'uid' => $uid]);
1463 unset($item['mention']);
1464 unset($item['starred']);
1465 unset($item['unseen']);
1466 unset($item['psid']);
1467 unset($item['pinned']);
1468 unset($item['ignored']);
1469 unset($item['pubmail']);
1470 unset($item['forum_mode']);
1472 unset($item['event-id']);
1473 unset($item['hidden']);
1474 unset($item['notification-type']);
1476 $item['uid'] = $uid;
1477 $item['origin'] = 0;
1480 if ($item['gravity'] == GRAVITY_PARENT) {
1481 $contact = Contact::getByURLForUser($item['owner-link'], $uid, false, ['id']);
1483 $contact = Contact::getByURLForUser($item['author-link'], $uid, false, ['id']);
1486 if (!empty($contact['id'])) {
1487 $item['contact-id'] = $contact['id'];
1489 // Shouldn't happen at all
1490 Logger::warning('contact-id could not be fetched', ['uid' => $uid, 'item' => $item]);
1491 $self = DBA::selectFirst('contact', ['id'], ['self' => true, 'uid' => $uid]);
1492 if (!DBA::isResult($self)) {
1493 // Shouldn't happen even less
1494 Logger::warning('self contact could not be fetched', ['uid' => $uid, 'item' => $item]);
1497 $item['contact-id'] = $self['id'];
1501 if ($item['gravity'] == GRAVITY_PARENT) {
1502 $contact = DBA::selectFirst('contact', [], ['id' => $item['contact-id'], 'self' => false]);
1503 if (DBA::isResult($contact)) {
1504 $notify = self::isRemoteSelf($contact, $item);
1508 $distributed = self::insert($item, $notify, true);
1510 if (!$distributed) {
1511 Logger::info("Distributed item wasn't stored", ['uri-id' => $item['uri-id'], 'user' => $uid]);
1513 Logger::info('Distributed item was stored', ['uri-id' => $item['uri-id'], 'user' => $uid, 'stored' => $distributed]);
1515 return $distributed;
1519 * Add a shadow entry for a given item id that is a thread starter
1521 * We store every public item entry additionally with the user id "0".
1522 * This is used for the community page and for the search.
1523 * It is planned that in the future we will store public item entries only once.
1525 * @param integer $itemid Item ID that should be added
1526 * @throws \Exception
1528 private static function addShadow($itemid)
1530 $fields = ['uid', 'private', 'visible', 'deleted', 'network', 'uri-id'];
1531 $condition = ['id' => $itemid, 'gravity' => GRAVITY_PARENT];
1532 $item = Post::selectFirst($fields, $condition);
1534 if (!DBA::isResult($item)) {
1538 // is it already a copy?
1539 if (($itemid == 0) || ($item['uid'] == 0)) {
1543 // Is it a visible public post?
1544 if (!$item["visible"] || $item["deleted"] || ($item["private"] == self::PRIVATE)) {
1548 // is it an entry from a connector? Only add an entry for natively connected networks
1549 if (!in_array($item["network"], array_merge(Protocol::FEDERATED ,['']))) {
1553 if (Post::exists(['uri-id' => $item['uri-id'], 'uid' => 0])) {
1557 $item = Post::selectFirst(self::ITEM_FIELDLIST, ['id' => $itemid]);
1559 if (DBA::isResult($item)) {
1560 // Preparing public shadow (removing user specific data)
1563 unset($item['parent']);
1564 unset($item['wall']);
1565 unset($item['mention']);
1566 unset($item['origin']);
1567 unset($item['starred']);
1568 unset($item['postopts']);
1569 unset($item['inform']);
1570 unset($item['post-reason']);
1571 if ($item['uri-id'] == $item['parent-uri-id']) {
1572 $item['contact-id'] = $item['owner-id'];
1574 $item['contact-id'] = $item['author-id'];
1577 $public_shadow = self::insert($item, false, true);
1579 Logger::info('Stored public shadow', ['thread' => $itemid, 'id' => $public_shadow]);
1584 * Add a shadow entry for a given item id that is a comment
1586 * This function does the same like the function above - but for comments
1588 * @param integer $itemid Item ID that should be added
1589 * @throws \Exception
1591 private static function addShadowPost($itemid)
1593 $item = Post::selectFirst(self::ITEM_FIELDLIST, ['id' => $itemid]);
1594 if (!DBA::isResult($item)) {
1598 // Is it a toplevel post?
1599 if ($item['gravity'] == GRAVITY_PARENT) {
1600 self::addShadow($itemid);
1604 // Is this a shadow entry?
1605 if ($item['uid'] == 0) {
1609 // Is there a shadow parent?
1610 if (!Post::exists(['uri-id' => $item['parent-uri-id'], 'uid' => 0])) {
1614 // Is there already a shadow entry?
1615 if (Post::exists(['uri-id' => $item['uri-id'], 'uid' => 0])) {
1619 // Save "origin" and "parent" state
1620 $origin = $item['origin'];
1621 $parent = $item['parent'];
1623 // Preparing public shadow (removing user specific data)
1626 unset($item['parent']);
1627 unset($item['wall']);
1628 unset($item['mention']);
1629 unset($item['origin']);
1630 unset($item['starred']);
1631 unset($item['postopts']);
1632 unset($item['inform']);
1633 unset($item['post-reason']);
1634 $item['contact-id'] = Contact::getIdForURL($item['author-link']);
1636 $public_shadow = self::insert($item, false, true);
1638 Logger::info('Stored public shadow', ['uri-id' => $item['uri-id'], 'id' => $public_shadow]);
1640 // If this was a comment to a Diaspora post we don't get our comment back.
1641 // This means that we have to distribute the comment by ourselves.
1642 if ($origin && Post::exists(['id' => $parent, 'network' => Protocol::DIASPORA])) {
1643 self::distribute($public_shadow);
1648 * Adds a language specification in a "language" element of given $arr.
1649 * Expects "body" element to exist in $arr.
1651 * @param array $item
1652 * @return string detected language
1653 * @throws \Text_LanguageDetect_Exception
1655 private static function getLanguage(array $item)
1657 if (!empty($item['language'])) {
1658 return $item['language'];
1661 if (!in_array($item['gravity'], [GRAVITY_PARENT, GRAVITY_COMMENT]) || empty($item['body'])) {
1665 // Convert attachments to links
1666 $naked_body = BBCode::removeAttachment($item['body']);
1667 if (empty($naked_body)) {
1671 // Remove links and pictures
1672 $naked_body = BBCode::removeLinks($naked_body);
1674 // Convert the title and the body to plain text
1675 $naked_body = trim($item['title'] . "\n" . BBCode::toPlaintext($naked_body));
1677 // Remove possibly remaining links
1678 $naked_body = preg_replace(Strings::autoLinkRegEx(), '', $naked_body);
1680 if (empty($naked_body)) {
1684 $ld = new Language(DI::l10n()->getAvailableLanguages());
1685 $languages = $ld->detect($naked_body)->limit(0, 3)->close();
1686 if (is_array($languages)) {
1687 return json_encode($languages);
1693 public static function getLanguageMessage(array $item)
1695 $iso639 = new \Matriphe\ISO639\ISO639;
1697 $used_languages = '';
1698 foreach (json_decode($item['language'], true) as $language => $reliability) {
1699 $used_languages .= $iso639->languageByCode1($language) . ' (' . $language . "): " . number_format($reliability, 5) . '\n';
1701 $used_languages = DI::l10n()->t('Detected languages in this post:\n%s', $used_languages);
1702 return $used_languages;
1706 * Creates an unique guid out of a given uri
1708 * @param string $uri uri of an item entry
1709 * @param string $host hostname for the GUID prefix
1710 * @return string unique guid
1712 public static function guidFromUri($uri, $host)
1714 // Our regular guid routine is using this kind of prefix as well
1715 // We have to avoid that different routines could accidentally create the same value
1716 $parsed = parse_url($uri);
1718 // We use a hash of the hostname as prefix for the guid
1719 $guid_prefix = hash("crc32", $host);
1721 // Remove the scheme to make sure that "https" and "http" doesn't make a difference
1722 unset($parsed["scheme"]);
1724 // Glue it together to be able to make a hash from it
1725 $host_id = implode("/", $parsed);
1727 // We could use any hash algorithm since it isn't a security issue
1728 $host_hash = hash("ripemd128", $host_id);
1730 return $guid_prefix.$host_hash;
1734 * generate an unique URI
1736 * @param integer $uid User id
1737 * @param string $guid An existing GUID (Otherwise it will be generated)
1740 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1742 public static function newURI($uid, $guid = "")
1745 $guid = System::createUUID();
1748 return DI::baseUrl()->get() . '/objects/' . $guid;
1752 * Set "success_update" and "last-item" to the date of the last time we heard from this contact
1754 * This can be used to filter for inactive contacts.
1755 * Only do this for public postings to avoid privacy problems, since poco data is public.
1756 * Don't set this value if it isn't from the owner (could be an author that we don't know)
1758 * @param array $arr Contains the just posted item record
1759 * @throws \Exception
1761 private static function updateContact($arr)
1763 // Unarchive the author
1764 $contact = DBA::selectFirst('contact', [], ['id' => $arr["author-id"]]);
1765 if (DBA::isResult($contact)) {
1766 Contact::unmarkForArchival($contact);
1769 // Unarchive the contact if it's not our own contact
1770 $contact = DBA::selectFirst('contact', [], ['id' => $arr["contact-id"], 'self' => false]);
1771 if (DBA::isResult($contact)) {
1772 Contact::unmarkForArchival($contact);
1775 /// @todo On private posts we could obfuscate the date
1776 $update = ($arr['private'] != self::PRIVATE) || in_array($arr['network'], Protocol::FEDERATED);
1778 // Is it a forum? Then we don't care about the rules from above
1779 if (!$update && in_array($arr["network"], [Protocol::ACTIVITYPUB, Protocol::DFRN]) && ($arr["parent-uri-id"] === $arr["uri-id"])) {
1780 if (DBA::exists('contact', ['id' => $arr['contact-id'], 'forum' => true])) {
1786 // The "self" contact id is used (for example in the connectors) when the contact is unknown
1787 // So we have to ensure to only update the last item when it had been our own post,
1788 // or it had been done by a "regular" contact.
1789 if (!empty($arr['wall'])) {
1790 $condition = ['id' => $arr['contact-id']];
1792 $condition = ['id' => $arr['contact-id'], 'self' => false];
1794 DBA::update('contact', ['failed' => false, 'success_update' => $arr['received'], 'last-item' => $arr['received']], $condition);
1796 // Now do the same for the system wide contacts with uid=0
1797 if ($arr['private'] != self::PRIVATE) {
1798 DBA::update('contact', ['failed' => false, 'success_update' => $arr['received'], 'last-item' => $arr['received']],
1799 ['id' => $arr['owner-id']]);
1801 if ($arr['owner-id'] != $arr['author-id']) {
1802 DBA::update('contact', ['failed' => false, 'success_update' => $arr['received'], 'last-item' => $arr['received']],
1803 ['id' => $arr['author-id']]);
1808 public static function setHashtags($body)
1810 $body = BBCode::performWithEscapedTags($body, ['noparse', 'pre', 'code', 'img'], function ($body) {
1811 $tags = BBCode::getTags($body);
1814 if (!count($tags)) {
1818 // This sorting is important when there are hashtags that are part of other hashtags
1819 // Otherwise there could be problems with hashtags like #test and #test2
1820 // Because of this we are sorting from the longest to the shortest tag.
1821 usort($tags, function ($a, $b) {
1822 return strlen($b) <=> strlen($a);
1825 $URLSearchString = "^\[\]";
1827 // All hashtags should point to the home server if "local_tags" is activated
1828 if (DI::config()->get('system', 'local_tags')) {
1829 $body = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
1830 "#[url=" . DI::baseUrl() . "/search?tag=$2]$2[/url]", $body);
1833 // mask hashtags inside of url, bookmarks and attachments to avoid urls in urls
1834 $body = preg_replace_callback("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
1836 return ("[url=" . str_replace("#", "#", $match[1]) . "]" . str_replace("#", "#", $match[2]) . "[/url]");
1839 $body = preg_replace_callback("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism",
1841 return ("[bookmark=" . str_replace("#", "#", $match[1]) . "]" . str_replace("#", "#", $match[2]) . "[/bookmark]");
1844 $body = preg_replace_callback("/\[attachment (.*?)\](.*?)\[\/attachment\]/ism",
1846 return ("[attachment " . str_replace("#", "#", $match[1]) . "]" . $match[2] . "[/attachment]");
1849 // Repair recursive urls
1850 $body = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
1853 foreach ($tags as $tag) {
1854 if ((strpos($tag, '#') !== 0) || strpos($tag, '[url=') || strlen($tag) < 2 || $tag[1] == '#') {
1858 $basetag = str_replace('_', ' ', substr($tag, 1));
1859 $newtag = '#[url=' . DI::baseUrl() . '/search?tag=' . $basetag . ']' . $basetag . '[/url]';
1861 $body = str_replace($tag, $newtag, $body);
1864 // Convert back the masked hashtags
1865 $body = str_replace("#", "#", $body);
1874 * look for mention tags and setup a second delivery chain for forum/community posts if appropriate
1877 * @param int $item_id
1878 * @return boolean true if item was deleted, else false
1879 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1880 * @throws \ImagickException
1882 private static function tagDeliver($uid, $item_id)
1886 $user = DBA::selectFirst('user', [], ['uid' => $uid]);
1887 if (!DBA::isResult($user)) {
1891 $community_page = (($user['page-flags'] == User::PAGE_FLAGS_COMMUNITY) ? true : false);
1892 $prvgroup = (($user['page-flags'] == User::PAGE_FLAGS_PRVGROUP) ? true : false);
1894 $item = Post::selectFirst(self::ITEM_FIELDLIST, ['id' => $item_id]);
1895 if (!DBA::isResult($item)) {
1899 $link = Strings::normaliseLink(DI::baseUrl() . '/profile/' . $user['nickname']);
1902 * Diaspora uses their own hardwired link URL in @-tags
1903 * instead of the one we supply with webfinger
1905 $dlink = Strings::normaliseLink(DI::baseUrl() . '/u/' . $user['nickname']);
1907 $cnt = preg_match_all('/[\@\!]\[url\=(.*?)\](.*?)\[\/url\]/ism', $item['body'], $matches, PREG_SET_ORDER);
1909 foreach ($matches as $mtch) {
1910 if (Strings::compareLink($link, $mtch[1]) || Strings::compareLink($dlink, $mtch[1])) {
1912 Logger::log('mention found: ' . $mtch[2]);
1918 $tags = Tag::getByURIId($item['uri-id'], [Tag::MENTION, Tag::EXCLUSIVE_MENTION]);
1919 foreach ($tags as $tag) {
1920 if (Strings::compareLink($link, $tag['url']) || Strings::compareLink($dlink, $tag['url'])) {
1922 DI::logger()->info('mention found in tag.', ['url' => $tag['url']]);
1928 if (($community_page || $prvgroup) &&
1929 !$item['wall'] && !$item['origin'] && ($item['gravity'] == GRAVITY_PARENT)) {
1930 Logger::info('Delete private group/communiy top-level item without mention', ['id' => $item['id'], 'guid'=> $item['guid']]);
1931 Post\User::delete(['uri-id' => $item['uri-id'], 'uid' => $item['uid']]);
1937 $arr = ['item' => $item, 'user' => $user];
1939 Hook::callAll('tagged', $arr);
1941 if (!$community_page && !$prvgroup) {
1946 * tgroup delivery - setup a second delivery chain
1947 * prevent delivery looping - only proceed
1948 * if the message originated elsewhere and is a top-level post
1950 if ($item['wall'] || $item['origin'] || ($item['id'] != $item['parent'])) {
1954 self::performActivity($item['id'], 'announce', $uid);
1957 * All the following lines are only needed for private forums and compatibility to older systems without AP support.
1958 * A possible way would be that the followers list of a forum would always be readable by all followers.
1959 * So this would mean that the comment distribution could be done exactly for the intended audience.
1960 * Or possibly we could store the receivers that had been in the "announce" message above and use this.
1963 // now change this copy of the post to a forum head message and deliver to all the tgroup members
1964 $self = DBA::selectFirst('contact', ['id', 'name', 'url', 'thumb'], ['uid' => $uid, 'self' => true]);
1965 if (!DBA::isResult($self)) {
1969 $owner_id = Contact::getIdForURL($self['url']);
1971 // also reset all the privacy bits to the forum default permissions
1972 if ($user['allow_cid'] || $user['allow_gid'] || $user['deny_cid'] || $user['deny_gid']) {
1973 $private = self::PRIVATE;
1974 } elseif (DI::pConfig()->get($user['uid'], 'system', 'unlisted')) {
1975 $private = self::UNLISTED;
1977 $private = self::PUBLIC;
1980 $psid = PermissionSet::getIdFromACL(
1988 $forum_mode = ($prvgroup ? 2 : 1);
1990 $fields = ['wall' => true, 'origin' => true, 'forum_mode' => $forum_mode, 'contact-id' => $self['id'],
1991 'owner-id' => $owner_id, 'private' => $private, 'psid' => $psid];
1992 self::update($fields, ['id' => $item['id']]);
1994 Worker::add(['priority' => PRIORITY_HIGH, 'dont_fork' => true], 'Notifier', Delivery::POST, (int)$item['uri-id'], (int)$item['uid']);
2000 * Automatically reshare the item if the "remote_self" option is selected
2002 * @param array $item
2005 private static function autoReshare(array $item)
2007 if ($item['gravity'] != GRAVITY_PARENT) {
2011 if (!DBA::exists('contact', ['id' => $item['contact-id'], 'remote_self' => Contact::MIRROR_NATIVE_RESHARE])) {
2015 if (!in_array($item['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN])) {
2019 Logger::info('Automatically reshare item', ['uid' => $item['uid'], 'id' => $item['id'], 'guid' => $item['guid'], 'uri-id' => $item['uri-id']]);
2021 self::performActivity($item['id'], 'announce', $item['uid']);
2024 public static function isRemoteSelf($contact, &$datarray)
2026 if (!$contact['remote_self']) {
2030 // Prevent the forwarding of posts that are forwarded
2031 if (!empty($datarray["extid"]) && ($datarray["extid"] == Protocol::DFRN)) {
2032 Logger::info('Already forwarded');
2036 // Prevent to forward already forwarded posts
2037 if ($datarray["app"] == DI::baseUrl()->getHostname()) {
2038 Logger::info('Already forwarded (second test)');
2042 // Only forward posts
2043 if ($datarray["verb"] != Activity::POST) {
2044 Logger::info('No post');
2048 if (($contact['network'] != Protocol::FEED) && ($datarray['private'] == self::PRIVATE)) {
2049 Logger::info('Not public');
2053 $datarray2 = $datarray;
2054 Logger::info('remote-self start', ['contact' => $contact['url'], 'remote_self'=> $contact['remote_self'], 'item' => $datarray]);
2055 if ($contact['remote_self'] == Contact::MIRROR_OWN_POST) {
2056 $self = DBA::selectFirst('contact', ['id', 'name', 'url', 'thumb'],
2057 ['uid' => $contact['uid'], 'self' => true]);
2058 if (DBA::isResult($self)) {
2059 $datarray['contact-id'] = $self["id"];
2061 $datarray['owner-name'] = $self["name"];
2062 $datarray['owner-link'] = $self["url"];
2063 $datarray['owner-avatar'] = $self["thumb"];
2065 $datarray['author-name'] = $datarray['owner-name'];
2066 $datarray['author-link'] = $datarray['owner-link'];
2067 $datarray['author-avatar'] = $datarray['owner-avatar'];
2069 unset($datarray['edited']);
2071 unset($datarray['network']);
2072 unset($datarray['owner-id']);
2073 unset($datarray['author-id']);
2076 if ($contact['network'] != Protocol::FEED) {
2077 $old_uri_id = $datarray["uri-id"] ?? 0;
2078 $datarray["guid"] = System::createUUID();
2079 unset($datarray["plink"]);
2080 $datarray["uri"] = self::newURI($contact['uid'], $datarray["guid"]);
2081 $datarray["uri-id"] = ItemURI::getIdByURI($datarray["uri"]);
2082 $datarray["extid"] = Protocol::DFRN;
2083 $urlpart = parse_url($datarray2['author-link']);
2084 $datarray["app"] = $urlpart["host"];
2085 if (!empty($old_uri_id)) {
2086 Post\Media::copy($old_uri_id, $datarray["uri-id"]);
2089 unset($datarray["parent-uri"]);
2090 unset($datarray["thr-parent"]);
2092 $datarray['private'] = self::PUBLIC;
2096 if ($contact['network'] != Protocol::FEED) {
2097 // Store the original post
2098 $result = self::insert($datarray2);
2099 Logger::info('remote-self post original item', ['contact' => $contact['url'], 'result'=> $result, 'item' => $datarray2]);
2101 $datarray["app"] = "Feed";
2105 return (bool)$result;
2112 * @param array $item
2115 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2116 * @throws \ImagickException
2118 public static function fixPrivatePhotos($s, $uid, $item = null, $cid = 0)
2120 if (DI::config()->get('system', 'disable_embedded')) {
2124 Logger::info('check for photos');
2125 $site = substr(DI::baseUrl(), strpos(DI::baseUrl(), '://'));
2130 $img_start = strpos($orig_body, '[img');
2131 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
2132 $img_len = ($img_start !== false ? strpos(substr($orig_body, $img_start + $img_st_close + 1), '[/img]') : false);
2134 while (($img_st_close !== false) && ($img_len !== false)) {
2135 $img_st_close++; // make it point to AFTER the closing bracket
2136 $image = substr($orig_body, $img_start + $img_st_close, $img_len);
2138 Logger::info('found photo', ['image' => $image]);
2140 if (stristr($image, $site . '/photo/')) {
2141 // Only embed locally hosted photos
2143 $i = basename($image);
2144 $i = str_replace(['.jpg', '.png', '.gif'], ['', '', ''], $i);
2145 $x = strpos($i, '-');
2148 $res = substr($i, $x + 1);
2149 $i = substr($i, 0, $x);
2150 $photo = Photo::getPhotoForUser($uid, $i, $res);
2151 if (DBA::isResult($photo)) {
2153 * Check to see if we should replace this photo link with an embedded image
2154 * 1. No need to do so if the photo is public
2155 * 2. If there's a contact-id provided, see if they're in the access list
2156 * for the photo. If so, embed it.
2157 * 3. Otherwise, if we have an item, see if the item permissions match the photo
2158 * permissions, regardless of order but first check to see if they're an exact
2159 * match to save some processing overhead.
2161 if (self::hasPermissions($photo)) {
2163 $recips = self::enumeratePermissions($photo);
2164 if (in_array($cid, $recips)) {
2168 if (self::samePermissions($uid, $item, $photo)) {
2174 $photo_img = Photo::getImageForPhoto($photo);
2175 // If a custom width and height were specified, apply before embedding
2176 if (preg_match("/\[img\=([0-9]*)x([0-9]*)\]/is", substr($orig_body, $img_start, $img_st_close), $match)) {
2177 Logger::info('scaling photo');
2179 $width = intval($match[1]);
2180 $height = intval($match[2]);
2182 $photo_img->scaleDown(max($width, $height));
2185 $data = $photo_img->asString();
2186 $type = $photo_img->getType();
2188 Logger::info('replacing photo');
2189 $image = 'data:' . $type . ';base64,' . base64_encode($data);
2190 Logger::debug('replaced', ['image' => $image]);
2196 $new_body = $new_body . substr($orig_body, 0, $img_start + $img_st_close) . $image . '[/img]';
2197 $orig_body = substr($orig_body, $img_start + $img_st_close + $img_len + strlen('[/img]'));
2198 if ($orig_body === false) {
2202 $img_start = strpos($orig_body, '[img');
2203 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
2204 $img_len = ($img_start !== false ? strpos(substr($orig_body, $img_start + $img_st_close + 1), '[/img]') : false);
2207 $new_body = $new_body . $orig_body;
2212 private static function hasPermissions($obj)
2214 return !empty($obj['allow_cid']) || !empty($obj['allow_gid']) ||
2215 !empty($obj['deny_cid']) || !empty($obj['deny_gid']);
2218 private static function samePermissions($uid, $obj1, $obj2)
2220 // first part is easy. Check that these are exactly the same.
2221 if (($obj1['allow_cid'] == $obj2['allow_cid'])
2222 && ($obj1['allow_gid'] == $obj2['allow_gid'])
2223 && ($obj1['deny_cid'] == $obj2['deny_cid'])
2224 && ($obj1['deny_gid'] == $obj2['deny_gid'])) {
2228 // This is harder. Parse all the permissions and compare the resulting set.
2229 $recipients1 = self::enumeratePermissions($obj1);
2230 $recipients2 = self::enumeratePermissions($obj2);
2234 /// @TODO Comparison of arrays, maybe use array_diff_assoc() here?
2235 return ($recipients1 == $recipients2);
2239 * Returns an array of contact-ids that are allowed to see this object
2241 * @param array $obj Item array with at least uid, allow_cid, allow_gid, deny_cid and deny_gid
2242 * @param bool $check_dead Prunes unavailable contacts from the result
2244 * @throws \Exception
2246 public static function enumeratePermissions(array $obj, bool $check_dead = false)
2248 $aclFormater = DI::aclFormatter();
2250 $allow_people = $aclFormater->expand($obj['allow_cid']);
2251 $allow_groups = Group::expand($obj['uid'], $aclFormater->expand($obj['allow_gid']), $check_dead);
2252 $deny_people = $aclFormater->expand($obj['deny_cid']);
2253 $deny_groups = Group::expand($obj['uid'], $aclFormater->expand($obj['deny_gid']), $check_dead);
2254 $recipients = array_unique(array_merge($allow_people, $allow_groups));
2255 $deny = array_unique(array_merge($deny_people, $deny_groups));
2256 $recipients = array_diff($recipients, $deny);
2260 public static function expire(int $uid, int $days, string $network = "", bool $force = false)
2262 if (!$uid || ($days < 1)) {
2266 $condition = ["`uid` = ? AND NOT `deleted` AND `gravity` = ?",
2267 $uid, GRAVITY_PARENT];
2270 * $expire_network_only = save your own wall posts
2271 * and just expire conversations started by others
2273 $expire_network_only = DI::pConfig()->get($uid, 'expire', 'network_only', false);
2275 if ($expire_network_only) {
2276 $condition[0] .= " AND NOT `wall`";
2279 if ($network != "") {
2280 $condition[0] .= " AND `network` = ?";
2281 $condition[] = $network;
2284 $condition[0] .= " AND `received` < UTC_TIMESTAMP() - INTERVAL ? DAY";
2285 $condition[] = $days;
2287 $items = Post::select(['resource-id', 'starred', 'id', 'post-type', 'uid', 'uri-id'], $condition);
2289 if (!DBA::isResult($items)) {
2293 $expire_items = DI::pConfig()->get($uid, 'expire', 'items', true);
2295 // Forcing expiring of items - but not notes and marked items
2297 $expire_items = true;
2300 $expire_notes = DI::pConfig()->get($uid, 'expire', 'notes', true);
2301 $expire_starred = DI::pConfig()->get($uid, 'expire', 'starred', true);
2302 $expire_photos = DI::pConfig()->get($uid, 'expire', 'photos', false);
2306 $priority = DI::config()->get('system', 'expire-notify-priority');
2308 while ($item = Post::fetch($items)) {
2309 // don't expire filed items
2310 if (DBA::exists('post-category', ['uri-id' => $item['uri-id'], 'uid' => $item['uid'], 'type' => Post\Category::FILE])) {
2314 // Only expire posts, not photos and photo comments
2316 if (!$expire_photos && !empty($item['resource-id'])) {
2318 } elseif (!$expire_starred && intval($item['starred'])) {
2320 } elseif (!$expire_notes && ($item['post-type'] == self::PT_PERSONAL_NOTE)) {
2322 } elseif (!$expire_items && ($item['post-type'] != self::PT_PERSONAL_NOTE)) {
2326 self::markForDeletionById($item['id'], $priority);
2331 Logger::log('User ' . $uid . ": expired $expired items; expire items: $expire_items, expire notes: $expire_notes, expire starred: $expire_starred, expire photos: $expire_photos");
2334 public static function firstPostDate($uid, $wall = false)
2336 $user = User::getById($uid, ['register_date']);
2341 $condition = ["`uid` = ? AND `wall` = ? AND NOT `deleted` AND `visible` AND `received` >= ?",
2342 $uid, $wall, $user['register_date']];
2343 $params = ['order' => ['received' => false]];
2344 $thread = Post::selectFirstThread(['received'], $condition, $params);
2345 if (DBA::isResult($thread)) {
2346 $postdate = substr(DateTimeFormat::local($thread['received']), 0, 10);
2353 * add/remove activity to an item
2355 * Toggle activities as like,dislike,attend of an item
2357 * @param int $item_id
2358 * @param string $verb
2359 * Activity verb. One of
2360 * like, unlike, dislike, undislike, attendyes, unattendyes,
2361 * attendno, unattendno, attendmaybe, unattendmaybe,
2362 * announce, unannouce
2364 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2365 * @throws \ImagickException
2366 * @hook 'post_local_end'
2368 * 'post_id' => ID of posted item
2370 public static function performActivity(int $item_id, string $verb, int $uid)
2376 Logger::notice('Start create activity', ['verb' => $verb, 'item' => $item_id, 'user' => $uid]);
2378 $item = Post::selectFirst(self::ITEM_FIELDLIST, ['id' => $item_id]);
2379 if (!DBA::isResult($item)) {
2380 Logger::log('like: unknown item ' . $item_id);
2384 $uri_id = $item['uri-id'];
2386 if (!in_array($item['uid'], [0, $uid])) {
2390 if (!Post::exists(['uri-id' => $item['parent-uri-id'], 'uid' => $uid])) {
2391 $stored = self::storeForUserByUriId($item['parent-uri-id'], $uid);
2392 if (($item['parent-uri-id'] == $item['uri-id']) && !empty($stored)) {
2393 $item = Post::selectFirst(self::ITEM_FIELDLIST, ['id' => $stored]);
2394 if (!DBA::isResult($item)) {
2395 Logger::info('Could not fetch just created item - should not happen', ['stored' => $stored, 'uid' => $uid, 'uri-id' => $uri_id]);
2401 // Retrieves the local post owner
2402 $owner = User::getOwnerDataById($uid);
2403 if (empty($owner)) {
2404 Logger::info('Empty owner for user', ['uid' => $uid]);
2408 // Retrieve the current logged in user's public contact
2409 $author_id = Contact::getIdForURL($owner['url']);
2410 if (empty($author_id)) {
2411 Logger::info('Empty public contact');
2419 $activity = Activity::LIKE;
2423 $activity = Activity::DISLIKE;
2427 $activity = Activity::ATTEND;
2431 $activity = Activity::ATTENDNO;
2434 case 'unattendmaybe':
2435 $activity = Activity::ATTENDMAYBE;
2439 $activity = Activity::FOLLOW;
2443 $activity = Activity::ANNOUNCE;
2446 Logger::notice('unknown verb', ['verb' => $verb, 'item' => $item_id]);
2450 $mode = Strings::startsWith($verb, 'un') ? 'delete' : 'create';
2452 // Enable activity toggling instead of on/off
2453 $event_verb_flag = $activity === Activity::ATTEND || $activity === Activity::ATTENDNO || $activity === Activity::ATTENDMAYBE;
2455 // Look for an existing verb row
2456 // Event participation activities are mutually exclusive, only one of them can exist at all times.
2457 if ($event_verb_flag) {
2458 $verbs = [Activity::ATTEND, Activity::ATTENDNO, Activity::ATTENDMAYBE];
2460 // Translate to the index based activity index
2462 foreach ($verbs as $verb) {
2463 $vids[] = Verb::getID($verb);
2466 $vids = Verb::getID($activity);
2469 $condition = ['vid' => $vids, 'deleted' => false, 'gravity' => GRAVITY_ACTIVITY,
2470 'author-id' => $author_id, 'uid' => $item['uid'], 'thr-parent-id' => $uri_id];
2471 $like_item = Post::selectFirst(['id', 'guid', 'verb'], $condition);
2473 if (DBA::isResult($like_item)) {
2475 * Truth table for existing activities
2477 * | Inputs || Outputs |
2478 * |----------------------------||-------------------|
2479 * | Mode | Event | Same verb || Delete? | Return? |
2480 * |--------|-------|-----------||---------|---------|
2481 * | create | Yes | Yes || No | Yes |
2482 * | create | Yes | No || Yes | No |
2483 * | create | No | Yes || No | Yes |
2484 * | create | No | No || N/A†|
2485 * | delete | Yes | Yes || Yes | N/A‡ |
2486 * | delete | Yes | No || No | N/A‡ |
2487 * | delete | No | Yes || Yes | N/A‡ |
2488 * | delete | No | No || N/A†|
2489 * |--------|-------|-----------||---------|---------|
2490 * | A | B | C || A xor C | !B or C |
2492 * †Can't happen: It's impossible to find an existing non-event activity without
2493 * the same verb because we are only looking for this single verb.
2495 * ‡ The "mode = delete" is returning early whether an existing activity was found or not.
2497 if ($mode == 'create' xor $like_item['verb'] == $activity) {
2498 self::markForDeletionById($like_item['id']);
2501 if (!$event_verb_flag || $like_item['verb'] == $activity) {
2506 // No need to go further if we aren't creating anything
2507 if ($mode == 'delete') {
2511 $objtype = $item['resource-id'] ? Activity\ObjectType::IMAGE : Activity\ObjectType::NOTE;
2514 'guid' => System::createUUID(),
2515 'uri' => self::newURI($item['uid']),
2516 'uid' => $item['uid'],
2517 'contact-id' => $owner['id'],
2518 'wall' => $item['wall'],
2520 'network' => Protocol::DFRN,
2521 'protocol' => Conversation::PARCEL_DIRECT,
2522 'direction' => Conversation::PUSH,
2523 'gravity' => GRAVITY_ACTIVITY,
2524 'parent' => $item['id'],
2525 'thr-parent' => $item['uri'],
2526 'owner-id' => $author_id,
2527 'author-id' => $author_id,
2528 'body' => $activity,
2529 'verb' => $activity,
2530 'object-type' => $objtype,
2531 'allow_cid' => $item['allow_cid'],
2532 'allow_gid' => $item['allow_gid'],
2533 'deny_cid' => $item['deny_cid'],
2534 'deny_gid' => $item['deny_gid'],
2539 $signed = Diaspora::createLikeSignature($uid, $new_item);
2540 if (!empty($signed)) {
2541 $new_item['diaspora_signed_text'] = json_encode($signed);
2544 $new_item_id = self::insert($new_item);
2546 // If the parent item isn't visible then set it to visible
2547 if (!$item['visible']) {
2548 self::update(['visible' => true], ['id' => $item['id']]);
2551 $new_item['id'] = $new_item_id;
2553 Hook::callAll('post_local_end', $new_item);
2559 * Fetch the SQL condition for the given user id
2561 * @param integer $owner_id User ID for which the permissions should be fetched
2562 * @return array condition
2564 public static function getPermissionsConditionArrayByUserId(int $owner_id)
2566 $local_user = local_user();
2567 $remote_user = Session::getRemoteContactID($owner_id);
2569 // default permissions - anonymous user
2570 $condition = ["`private` != ?", self::PRIVATE];
2572 if ($local_user && ($local_user == $owner_id)) {
2573 // Profile owner - everything is visible
2575 } elseif ($remote_user) {
2576 // Authenticated visitor - fetch the matching permissionsets
2577 $set = PermissionSet::get($owner_id, $remote_user);
2579 $condition = ["(`private` != ? OR (`private` = ? AND `wall`
2580 AND `psid` IN (" . implode(', ', array_fill(0, count($set), '?')) . ")))",
2581 self::PRIVATE, self::PRIVATE];
2582 $condition = array_merge($condition, $set);
2590 * Get a permission SQL string for the given user
2592 * @param int $owner_id
2593 * @param string $table
2596 public static function getPermissionsSQLByUserId(int $owner_id, string $table = '')
2598 $local_user = local_user();
2599 $remote_user = Session::getRemoteContactID($owner_id);
2601 if (!empty($table)) {
2602 $table = DBA::quoteIdentifier($table) . '.';
2606 * Construct permissions
2608 * default permissions - anonymous user
2610 $sql = sprintf(" AND " . $table . "`private` != %d", self::PRIVATE);
2612 // Profile owner - everything is visible
2613 if ($local_user && ($local_user == $owner_id)) {
2615 } elseif ($remote_user) {
2617 * Authenticated visitor. Unless pre-verified,
2618 * check that the contact belongs to this $owner_id
2619 * and load the groups the visitor belongs to.
2620 * If pre-verified, the caller is expected to have already
2621 * done this and passed the groups into this function.
2623 $set = PermissionSet::get($owner_id, $remote_user);
2626 $sql_set = sprintf(" OR (" . $table . "`private` = %d AND " . $table . "`wall` AND " . $table . "`psid` IN (", self::PRIVATE) . implode(',', $set) . "))";
2631 $sql = sprintf(" AND (" . $table . "`private` != %d", self::PRIVATE) . $sql_set . ")";
2638 * get translated item type
2640 * @param array $item
2641 * @param \Friendica\Core\L10n $l10n
2644 public static function postType(array $item, \Friendica\Core\L10n $l10n)
2646 if (!empty($item['event-id'])) {
2647 return $l10n->t('event');
2648 } elseif (!empty($item['resource-id'])) {
2649 return $l10n->t('photo');
2650 } elseif ($item['gravity'] == GRAVITY_ACTIVITY) {
2651 return $l10n->t('activity');
2652 } elseif ($item['gravity'] == GRAVITY_COMMENT) {
2653 return $l10n->t('comment');
2656 return $l10n->t('post');
2660 * Sets the "rendered-html" field of the provided item
2662 * Body is preserved to avoid side-effects as we modify it just-in-time for spoilers and private image links
2664 * @param array $item
2666 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2667 * @todo Remove reference, simply return "rendered-html" and "rendered-hash"
2669 public static function putInCache(&$item)
2671 // Save original body to prevent addons to modify it
2672 $body = $item['body'];
2674 $rendered_hash = $item['rendered-hash'] ?? '';
2675 $rendered_html = $item['rendered-html'] ?? '';
2677 if ($rendered_hash == ''
2678 || $rendered_html == ''
2679 || $rendered_hash != hash('md5', BBCode::VERSION . '::' . $body)
2680 || DI::config()->get('system', 'ignore_cache')
2682 self::addRedirToImageTags($item);
2684 $item['rendered-html'] = BBCode::convertForUriId($item['uri-id'], $item['body']);
2685 $item['rendered-hash'] = hash('md5', BBCode::VERSION . '::' . $body);
2687 $hook_data = ['item' => $item, 'rendered-html' => $item['rendered-html'], 'rendered-hash' => $item['rendered-hash']];
2688 Hook::callAll('put_item_in_cache', $hook_data);
2689 $item['rendered-html'] = $hook_data['rendered-html'];
2690 $item['rendered-hash'] = $hook_data['rendered-hash'];
2693 // Update if the generated values differ from the existing ones
2694 if ((($rendered_hash != $item['rendered-hash']) || ($rendered_html != $item['rendered-html'])) && !empty($item['id'])) {
2697 'rendered-html' => $item['rendered-html'],
2698 'rendered-hash' => $item['rendered-hash']
2700 ['id' => $item['id']]
2705 $item['body'] = $body;
2709 * Find any non-embedded images in private items and add redir links to them
2711 * @param array &$item The field array of an item row
2713 private static function addRedirToImageTags(array &$item)
2718 $cnt = preg_match_all('|\[img\](http[^\[]*?/photo/[a-fA-F0-9]+?(-[0-9]\.[\w]+?)?)\[\/img\]|', $item['body'], $matches, PREG_SET_ORDER);
2720 foreach ($matches as $mtch) {
2721 if (strpos($mtch[1], '/redir') !== false) {
2725 if ((local_user() == $item['uid']) && ($item['private'] == self::PRIVATE) && ($item['contact-id'] != $app->contact['id']) && ($item['network'] == Protocol::DFRN)) {
2726 $img_url = 'redir/' . $item['contact-id'] . '?url=' . urlencode($mtch[1]);
2727 $item['body'] = str_replace($mtch[0], '[img]' . $img_url . '[/img]', $item['body']);
2734 * Given an item array, convert the body element from bbcode to html and add smilie icons.
2735 * If attach is true, also add icons for item attachments.
2737 * @param array $item
2738 * @param boolean $attach
2739 * @param boolean $is_preview
2740 * @return string item body html
2741 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2742 * @throws \ImagickException
2743 * @hook prepare_body_init item array before any work
2744 * @hook prepare_body_content_filter ('item'=>item array, 'filter_reasons'=>string array) before first bbcode to html
2745 * @hook prepare_body ('item'=>item array, 'html'=>body string, 'is_preview'=>boolean, 'filter_reasons'=>string array) after first bbcode to html
2746 * @hook prepare_body_final ('item'=>item array, 'html'=>body string) after attach icons and blockquote special case handling (spoiler, author)
2748 public static function prepareBody(array &$item, $attach = false, $is_preview = false)
2751 Hook::callAll('prepare_body_init', $item);
2753 // In order to provide theme developers more possibilities, event items
2754 // are treated differently.
2755 if ($item['object-type'] === Activity\ObjectType::EVENT && isset($item['event-id'])) {
2756 $ev = Event::getItemHTML($item);
2760 $tags = Tag::populateFromItem($item);
2762 $item['tags'] = $tags['tags'];
2763 $item['hashtags'] = $tags['hashtags'];
2764 $item['mentions'] = $tags['mentions'];
2766 // Compile eventual content filter reasons
2767 $filter_reasons = [];
2768 if (!$is_preview && public_contact() != $item['author-id']) {
2769 if (!empty($item['content-warning']) && (!local_user() || !DI::pConfig()->get(local_user(), 'system', 'disable_cw', false))) {
2770 $filter_reasons[] = DI::l10n()->t('Content warning: %s', $item['content-warning']);
2775 'filter_reasons' => $filter_reasons
2777 Hook::callAll('prepare_body_content_filter', $hook_data);
2778 $filter_reasons = $hook_data['filter_reasons'];
2782 $body = $item['body'] ?? '';
2783 $shared = BBCode::fetchShareAttributes($body);
2784 if (!empty($shared['guid'])) {
2785 $shared_item = Post::selectFirst(['uri-id', 'plink'], ['guid' => $shared['guid']]);
2786 $shared_uri_id = $shared_item['uri-id'] ?? 0;
2787 $shared_links = [strtolower($shared_item['plink'] ?? '')];
2788 $shared_attachments = Post\Media::splitAttachments($shared_uri_id, $shared['guid']);
2789 $shared_links = array_merge($shared_links, array_column($shared_attachments['visual'], 'url'));
2790 $shared_links = array_merge($shared_links, array_column($shared_attachments['link'], 'url'));
2791 $shared_links = array_merge($shared_links, array_column($shared_attachments['additional'], 'url'));
2792 $item['body'] = self::replaceVisualAttachments($shared_attachments, $item['body']);
2797 $attachments = Post\Media::splitAttachments($item['uri-id'], $item['guid'] ?? '', $shared_links);
2798 $item['body'] = self::replaceVisualAttachments($attachments, $item['body'] ?? '');
2800 $item['body'] = preg_replace("/\s*\[attachment .*?\].*?\[\/attachment\]\s*/ism", "\n", $item['body']);
2801 self::putInCache($item);
2802 $item['body'] = $body;
2803 $s = $item["rendered-html"];
2808 'preview' => $is_preview,
2809 'filter_reasons' => $filter_reasons
2811 Hook::callAll('prepare_body', $hook_data);
2812 $s = $hook_data['html'];
2816 // Replace the blockquotes with quotes that are used in mails.
2817 $mailquote = '<blockquote type="cite" class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex;">';
2818 $s = str_replace(['<blockquote>', '<blockquote class="spoiler">', '<blockquote class="author">'], [$mailquote, $mailquote, $mailquote], $s);
2822 if (!empty($shared_attachments)) {
2823 $s = self::addVisualAttachments($shared_attachments, $item, $s, true);
2824 $s = self::addLinkAttachment($shared_uri_id ?: $item['uri-id'], $shared_attachments, $body, $s, true, []);
2825 $s = self::addNonVisualAttachments($shared_attachments, $item, $s, true);
2826 $body = preg_replace("/\s*\[share .*?\].*?\[\/share\]\s*/ism", '', $body);
2829 $s = self::addVisualAttachments($attachments, $item, $s, false);
2830 $s = self::addLinkAttachment($item['uri-id'], $attachments, $body, $s, false, $shared_links);
2831 $s = self::addNonVisualAttachments($attachments, $item, $s, false);
2834 if (strpos($s, '<div class="map">') !== false && !empty($item['coord'])) {
2835 $x = Map::byCoordinates(trim($item['coord']));
2837 $s = preg_replace('/\<div class\=\"map\"\>/', '$0' . $x, $s);
2841 // Replace friendica image url size with theme preference.
2842 if (!empty($a->theme_info['item_image_size'])) {
2843 $ps = $a->theme_info['item_image_size'];
2844 $s = preg_replace('|(<img[^>]+src="[^"]+/photo/[0-9a-f]+)-[0-9]|', "$1-" . $ps, $s);
2847 $s = HTML::applyContentFilter($s, $filter_reasons);
2849 $hook_data = ['item' => $item, 'html' => $s];
2850 Hook::callAll('prepare_body_final', $hook_data);
2852 return $hook_data['html'];
2856 * Check if the body contains a link
2858 * @param string $body
2859 * @param string $url
2863 public static function containsLink(string $body, string $url, int $type = 0)
2865 // Make sure that for example site parameters aren't used when testing if the link is contained in the body
2866 $urlparts = parse_url($url);
2867 unset($urlparts['query']);
2868 unset($urlparts['fragment']);
2869 $url = Network::unparseURL($urlparts);
2871 // Remove media links to only search in embedded content
2872 // @todo Check images for image link, audio for audio links, ...
2873 if (in_array($type, [Post\Media::AUDIO, Post\Media::VIDEO, Post\Media::IMAGE])) {
2874 $body = preg_replace("/\[url=[^\[\]]*\](.*)\[\/url\]/Usi", ' $1 ', $body);
2877 if (strpos($body, $url)) {
2880 foreach ([0, 1, 2] as $size) {
2881 if (preg_match('#/photo/.*-' . $size . '\.#ism', $url) &&
2882 strpos(preg_replace('#(/photo/.*)-[012]\.#ism', '$1-' . $size . '.', $body), $url)) {
2890 * Replace visual attachments in the body
2892 * @param array $attachments
2893 * @param string $body
2894 * @return string modified body
2896 private static function replaceVisualAttachments(array $attachments, string $body)
2898 $stamp1 = microtime(true);
2900 foreach ($attachments['visual'] as $attachment) {
2901 if (!empty($attachment['preview'])) {
2902 $body = str_replace($attachment['preview'], Post\Media::getPreviewUrlForId($attachment['id'], Proxy::SIZE_LARGE), $body);
2903 } elseif ($attachment['filetype'] == 'image') {
2904 $body = str_replace($attachment['url'], Post\Media::getUrlForId($attachment['id']), $body);
2907 DI::profiler()->saveTimestamp($stamp1, 'rendering');
2912 * Add visual attachments to the content
2914 * @param array $attachments
2915 * @param array $item
2916 * @param string $content
2917 * @return string modified content
2919 private static function addVisualAttachments(array $attachments, array $item, string $content, bool $shared)
2921 $stamp1 = microtime(true);
2925 // @todo In the future we should make a single for the template engine with all media in it. This allows more flexibilty.
2926 foreach ($attachments['visual'] as $attachment) {
2927 if (self::containsLink($item['body'], $attachment['url'], $attachment['type'])) {
2931 if (!empty($attachment['preview'])) {
2932 $preview_url = Post\Media::getPreviewUrlForId($attachment['id'], Proxy::SIZE_LARGE);
2937 if (($attachment['filetype'] == 'video')) {
2938 /// @todo Move the template to /content as well
2939 $media = Renderer::replaceMacros(Renderer::getMarkupTemplate('video_top.tpl'), [
2941 'id' => $attachment['id'],
2942 'src' => $attachment['url'],
2943 'name' => $attachment['name'] ?: $attachment['url'],
2944 'preview' => $preview_url,
2945 'mime' => $attachment['mimetype'],
2948 if (($item['post-type'] ?? null) == Item::PT_VIDEO) {
2951 $trailing .= $media;
2953 } elseif ($attachment['filetype'] == 'audio') {
2954 $media = Renderer::replaceMacros(Renderer::getMarkupTemplate('content/audio.tpl'), [
2956 'id' => $attachment['id'],
2957 'src' => $attachment['url'],
2958 'name' => $attachment['name'] ?: $attachment['url'],
2959 'mime' => $attachment['mimetype'],
2962 if (($item['post-type'] ?? null) == Item::PT_AUDIO) {
2965 $trailing .= $media;
2967 } elseif ($attachment['filetype'] == 'image') {
2968 $media = Renderer::replaceMacros(Renderer::getMarkupTemplate('content/image.tpl'), [
2970 'src' => Post\Media::getUrlForId($attachment['id']),
2971 'preview' => Post\Media::getPreviewUrlForId($attachment['id'], ($attachment['width'] > $attachment['height']) ? Proxy::SIZE_MEDIUM : Proxy::SIZE_LARGE),
2972 'attachment' => $attachment,
2975 // On Diaspora posts the attached pictures are leading
2976 if ($item['network'] == Protocol::DIASPORA) {
2979 $trailing .= $media;
2985 $content = str_replace(BBCode::TOP_ANCHOR, '<div class="body-attach">' . $leading . '<div class="clear"></div></div>' . BBCode::TOP_ANCHOR, $content);
2986 $content = str_replace(BBCode::BOTTOM_ANCHOR, '<div class="body-attach">' . $trailing . '<div class="clear"></div></div>' . BBCode::BOTTOM_ANCHOR, $content);
2988 if ($leading != '') {
2989 $content = '<div class="body-attach">' . $leading . '<div class="clear"></div></div>' . $content;
2992 if ($trailing != '') {
2993 $content .= '<div class="body-attach">' . $trailing . '<div class="clear"></div></div>';
2997 DI::profiler()->saveTimestamp($stamp1, 'rendering');
3002 * Add link attachment to the content
3004 * @param array $attachments
3005 * @param string $body
3006 * @param string $content
3007 * @param bool $shared
3008 * @param array $ignore_links A list of URLs to ignore
3009 * @return string modified content
3011 private static function addLinkAttachment(int $uriid, array $attachments, string $body, string $content, bool $shared, array $ignore_links)
3013 $stamp1 = microtime(true);
3014 // @ToDo Check only for audio and video
3015 $preview = empty($attachments['visual']);
3017 if (!empty($attachments['link'])) {
3018 foreach ($attachments['link'] as $link) {
3020 foreach ($ignore_links as $ignore_link) {
3021 if (Strings::compareLink($link['url'], $ignore_link)) {
3025 // @todo Judge between the links to use the one with most information
3026 if (!$found && (empty($attachment) || !empty($link['author-name']) ||
3027 (empty($attachment['name']) && !empty($link['name'])) ||
3028 (empty($attachment['description']) && !empty($link['description'])) ||
3029 (empty($attachment['preview']) && !empty($link['preview'])))) {
3030 $attachment = $link;
3035 if (!empty($attachment)) {
3038 'author_name' => $attachment['author-name'] ?? '',
3039 'author_url' => $attachment['author-url'] ?? '',
3040 'description' => $attachment['description'] ?? '',
3043 'provider_name' => $attachment['publisher-name'] ?? '',
3044 'provider_url' => $attachment['publisher-url'] ?? '',
3046 'title' => $attachment['name'] ?? '',
3048 'url' => $attachment['url']];
3050 if ($preview && !empty($attachment['preview'])) {
3051 if ($attachment['preview-width'] >= 500) {
3052 $data['image'] = Post\Media::getPreviewUrlForId($attachment['id'], Proxy::SIZE_MEDIUM);
3054 $data['preview'] = Post\Media::getPreviewUrlForId($attachment['id'], Proxy::SIZE_MEDIUM);
3058 if (!empty($data['description']) && !empty($content)) {
3059 similar_text($data['description'], $content, $percent);
3064 if (!empty($data['description']) && (($data['title'] == $data['description']) || ($percent > 95) || (strpos($content, $data['description']) !== false))) {
3065 $data['description'] = '';
3068 if (($data['author_name'] ?? '') == ($data['provider_name'] ?? '')) {
3069 $data['author_name'] = '';
3072 if (($data['author_url'] ?? '') == ($data['provider_url'] ?? '')) {
3073 $data['author_url'] = '';
3075 } elseif (preg_match("/.*(\[attachment.*?\].*?\[\/attachment\]).*/ism", $body, $match)) {
3076 $data = BBCode::getAttachmentData($match[1]);
3078 DI::profiler()->saveTimestamp($stamp1, 'rendering');
3080 if (isset($data['url']) && !in_array($data['url'], $ignore_links)) {
3081 if (!empty($data['description']) || !empty($data['image']) || !empty($data['preview'])) {
3082 $parts = parse_url($data['url']);
3083 if (!empty($parts['scheme']) && !empty($parts['host'])) {
3084 if (empty($data['provider_name'])) {
3085 $data['provider_name'] = $parts['host'];
3087 if (empty($data['provider_url']) || empty(parse_url($data['provider_url'], PHP_URL_SCHEME))) {
3088 $data['provider_url'] = $parts['scheme'] . '://' . $parts['host'];
3090 if (!empty($parts['port'])) {
3091 $data['provider_url'] .= ':' . $parts['port'];
3096 // @todo Use a template
3097 $rendered = BBCode::convertAttachment('', BBCode::INTERNAL, false, $data, $uriid);
3098 } elseif (!self::containsLink($content, $data['url'], Post\Media::HTML)) {
3099 $rendered = Renderer::replaceMacros(Renderer::getMarkupTemplate('content/link.tpl'), [
3100 '$url' => $data['url'],
3101 '$title' => $data['title'],
3108 return str_replace(BBCode::BOTTOM_ANCHOR, BBCode::BOTTOM_ANCHOR . $rendered, $content);
3110 return $content . $rendered;
3117 * Add non visual attachments to the content
3119 * @param array $attachments
3120 * @param array $item
3121 * @param string $content
3122 * @return string modified content
3124 private static function addNonVisualAttachments(array $attachments, array $item, string $content)
3126 $stamp1 = microtime(true);
3128 foreach ($attachments['additional'] as $attachment) {
3129 if (strpos($item['body'], $attachment['url'])) {
3133 $author = ['uid' => 0, 'id' => $item['author-id'],
3134 'network' => $item['author-network'], 'url' => $item['author-link']];
3135 $the_url = Contact::magicLinkByContact($author, $attachment['url']);
3137 $title = Strings::escapeHtml(trim(($attachment['description'] ?? '') ?: $attachment['url']));
3139 if (!empty($attachment['size'])) {
3140 $title .= ' ' . $attachment['size'] . ' ' . DI::l10n()->t('bytes');
3143 /// @todo Use a template
3144 $icon = '<div class="attachtype icon s22 type-' . $attachment['filetype'] . ' subtype-' . $attachment['subtype'] . '"></div>';
3145 $trailing .= '<a href="' . strip_tags($the_url) . '" title="' . $title . '" class="attachlink" target="_blank" rel="noopener noreferrer" >' . $icon . '</a>';
3148 if ($trailing != '') {
3149 $content .= '<div class="body-attach">' . $trailing . '<div class="clear"></div></div>';
3152 DI::profiler()->saveTimestamp($stamp1, 'rendering');
3157 * get private link for item
3159 * @param array $item
3160 * @return boolean|array False if item has not plink, otherwise array('href'=>plink url, 'title'=>translated title)
3161 * @throws \Exception
3163 public static function getPlink($item)
3167 'href' => "display/" . $item['guid'],
3168 'orig' => "display/" . $item['guid'],
3169 'title' => DI::l10n()->t('View on separate page'),
3170 'orig_title' => DI::l10n()->t('View on separate page'),
3173 if (!empty($item['plink'])) {
3174 $ret['href'] = DI::baseUrl()->remove($item['plink']);
3175 $ret['title'] = DI::l10n()->t('Link to source');
3177 } elseif (!empty($item['plink']) && ($item['private'] != self::PRIVATE)) {
3179 'href' => $item['plink'],
3180 'orig' => $item['plink'],
3181 'title' => DI::l10n()->t('Link to source'),
3182 'orig_title' => DI::l10n()->t('Link to source'),
3192 * Is the given item array a post that is sent as starting post to a forum?
3194 * @param array $item
3195 * @param array $owner
3197 * @return boolean "true" when it is a forum post
3199 public static function isForumPost(array $item, array $owner = [])
3201 if (empty($owner)) {
3202 $owner = User::getOwnerDataById($item['uid']);
3203 if (empty($owner)) {
3208 if (($item['author-id'] == $item['owner-id']) ||
3209 ($owner['id'] == $item['contact-id']) ||
3210 ($item['uri-id'] != $item['parent-uri-id']) ||
3215 return Contact::isForum($item['contact-id']);
3219 * Search item id for given URI or plink
3221 * @param string $uri
3222 * @param integer $uid
3224 * @return integer item id
3226 public static function searchByLink($uri, $uid = 0)
3228 $ssl_uri = str_replace('http://', 'https://', $uri);
3229 $uris = [$uri, $ssl_uri, Strings::normaliseLink($uri)];
3231 $item = Post::selectFirst(['id'], ['uri' => $uris, 'uid' => $uid]);
3232 if (DBA::isResult($item)) {
3236 $item = Post::selectFirst(['id'], ['plink' => $uris, 'uid' => $uid]);
3237 if (DBA::isResult($item)) {
3245 * Return the URI for a link to the post
3247 * @param string $uri URI or link to post
3249 * @return string URI
3251 public static function getURIByLink(string $uri)
3253 $ssl_uri = str_replace('http://', 'https://', $uri);
3254 $uris = [$uri, $ssl_uri, Strings::normaliseLink($uri)];
3256 $item = Post::selectFirst(['uri'], ['uri' => $uris]);
3257 if (DBA::isResult($item)) {
3258 return $item['uri'];
3261 $item = Post::selectFirst(['uri'], ['plink' => $uris]);
3262 if (DBA::isResult($item)) {
3263 return $item['uri'];
3270 * Fetches item for given URI or plink
3272 * @param string $uri
3273 * @param integer $uid
3275 * @return integer item id
3277 public static function fetchByLink(string $uri, int $uid = 0)
3279 Logger::info('Trying to fetch link', ['uid' => $uid, 'uri' => $uri]);
3280 $item_id = self::searchByLink($uri, $uid);
3281 if (!empty($item_id)) {
3282 Logger::info('Link found', ['uid' => $uid, 'uri' => $uri, 'id' => $item_id]);
3286 if ($fetched_uri = ActivityPub\Processor::fetchMissingActivity($uri)) {
3287 $item_id = self::searchByLink($fetched_uri, $uid);
3289 $item_id = Diaspora::fetchByURL($uri);
3292 if (!empty($item_id)) {
3293 Logger::info('Link fetched', ['uid' => $uid, 'uri' => $uri, 'id' => $item_id]);
3297 Logger::info('Link not found', ['uid' => $uid, 'uri' => $uri]);
3302 * Return share data from an item array (if the item is shared item)
3303 * We are providing the complete Item array, because at some time in the future
3304 * we hopefully will define these values not in the body anymore but in some item fields.
3305 * This function is meant to replace all similar functions in the system.
3307 * @param array $item
3309 * @return array with share information
3311 public static function getShareArray($item)
3313 if (!preg_match("/(.*?)\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", $item['body'], $matches)) {
3317 $attribute_string = $matches[2];
3318 $attributes = ['comment' => trim($matches[1]), 'shared' => trim($matches[3])];
3319 foreach (['author', 'profile', 'avatar', 'guid', 'posted', 'link'] as $field) {
3320 if (preg_match("/$field=(['\"])(.+?)\\1/ism", $attribute_string, $matches)) {
3321 $attributes[$field] = trim(html_entity_decode($matches[2] ?? '', ENT_QUOTES, 'UTF-8'));
3328 * Fetch item information for shared items from the original items and adds it.
3330 * @param array $item
3332 * @return array item array with data from the original item
3334 public static function addShareDataFromOriginal(array $item)
3336 $shared = self::getShareArray($item);
3337 if (empty($shared)) {
3341 // Real reshares always have got a GUID.
3342 if (empty($shared['guid'])) {
3346 $uid = $item['uid'] ?? 0;
3348 // first try to fetch the item via the GUID. This will work for all reshares that had been created on this system
3349 $shared_item = Post::selectFirst(['title', 'body'], ['guid' => $shared['guid'], 'uid' => [0, $uid]]);
3350 if (!DBA::isResult($shared_item)) {
3351 if (empty($shared['link'])) {
3355 // Otherwhise try to find (and possibly fetch) the item via the link. This should work for Diaspora and ActivityPub posts
3356 $id = self::fetchByLink($shared['link'] ?? '', $uid);
3358 Logger::info('Original item not found', ['url' => $shared['link'] ?? '', 'callstack' => System::callstack()]);
3362 $shared_item = Post::selectFirst(['title', 'body'], ['id' => $id]);
3363 if (!DBA::isResult($shared_item)) {
3366 Logger::info('Got shared data from url', ['url' => $shared['link'], 'callstack' => System::callstack()]);
3368 Logger::info('Got shared data from guid', ['guid' => $shared['guid'], 'callstack' => System::callstack()]);
3371 if (!empty($shared_item['title'])) {
3372 $body = '[h3]' . $shared_item['title'] . "[/h3]\n" . $shared_item['body'];
3373 unset($shared_item['title']);
3375 $body = $shared_item['body'];
3378 $item['body'] = preg_replace("/\[share ([^\[\]]*)\].*\[\/share\]/ism", '[share $1]' . $body . '[/share]', $item['body']);
3379 unset($shared_item['body']);
3381 return array_merge($item, $shared_item);
3385 * Check a prospective item array against user-level permissions
3387 * @param array $item Expected keys: uri, gravity, and
3388 * author-link if is author-id is set,
3389 * owner-link if is owner-id is set,
3390 * causer-link if is causer-id is set.
3391 * @param int $user_id Local user ID
3393 * @throws \Exception
3395 protected static function isAllowedByUser(array $item, int $user_id)
3397 if (!empty($item['author-id']) && Contact\User::isBlocked($item['author-id'], $user_id)) {
3398 Logger::notice('Author is blocked by user', ['author-link' => $item['author-link'], 'uid' => $user_id, 'item-uri' => $item['uri']]);
3402 if (!empty($item['owner-id']) && Contact\User::isBlocked($item['owner-id'], $user_id)) {
3403 Logger::notice('Owner is blocked by user', ['owner-link' => $item['owner-link'], 'uid' => $user_id, 'item-uri' => $item['uri']]);
3407 // The causer is set during a thread completion, for example because of a reshare. It countains the responsible actor.
3408 if (!empty($item['causer-id']) && Contact\User::isBlocked($item['causer-id'], $user_id)) {
3409 Logger::notice('Causer is blocked by user', ['causer-link' => $item['causer-link'] ?? $item['causer-id'], 'uid' => $user_id, 'item-uri' => $item['uri']]);
3413 if (!empty($item['causer-id']) && ($item['gravity'] === GRAVITY_PARENT) && Contact\User::isIgnored($item['causer-id'], $user_id)) {
3414 Logger::notice('Causer is ignored by user', ['causer-link' => $item['causer-link'] ?? $item['causer-id'], 'uid' => $user_id, 'item-uri' => $item['uri']]);
3422 * Improve the data in shared posts
3424 * @param array $item
3425 * @return string body
3427 public static function improveSharedDataInBody(array $item)
3429 $shared = BBCode::fetchShareAttributes($item['body']);
3430 if (empty($shared['link'])) {
3431 return $item['body'];
3434 $id = self::fetchByLink($shared['link']);
3435 Logger::info('Fetched shared post', ['uri-id' => $item['uri-id'], 'id' => $id, 'author' => $shared['profile'], 'url' => $shared['link'], 'guid' => $shared['guid'], 'callstack' => System::callstack()]);
3437 return $item['body'];
3440 $shared_item = Post::selectFirst(['author-name', 'author-link', 'author-avatar', 'plink', 'created', 'guid', 'title', 'body'], ['id' => $id]);
3441 if (!DBA::isResult($shared_item)) {
3442 return $item['body'];
3445 $shared_content = BBCode::getShareOpeningTag($shared_item['author-name'], $shared_item['author-link'], $shared_item['author-avatar'], $shared_item['plink'], $shared_item['created'], $shared_item['guid']);
3447 if (!empty($shared_item['title'])) {
3448 $shared_content .= '[h3]'.$shared_item['title'].'[/h3]'."\n";
3451 $shared_content .= $shared_item['body'];
3453 $item['body'] = preg_replace("/\[share.*?\](.*)\[\/share\]/ism", $shared_content . '[/share]', $item['body']);
3454 Logger::info('New shared data', ['uri-id' => $item['uri-id'], 'id' => $id, 'shared_item' => $shared_item]);
3455 return $item['body'];