3 * @copyright Copyright (C) 2010-2022, the Friendica project
5 * @license GNU AGPL version 3 or any later version
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU Affero General Public License as
9 * published by the Free Software Foundation, either version 3 of the
10 * License, or (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU Affero General Public License for more details.
17 * You should have received a copy of the GNU Affero General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
22 namespace Friendica\Protocol;
28 use Friendica\Content\Text\BBCode;
29 use Friendica\Content\Text\HTML;
30 use Friendica\Core\Cache\Enum\Duration;
31 use Friendica\Core\Logger;
32 use Friendica\Core\Protocol;
33 use Friendica\Database\DBA;
35 use Friendica\Model\APContact;
36 use Friendica\Model\Contact;
37 use Friendica\Model\Conversation;
38 use Friendica\Model\Item;
39 use Friendica\Model\ItemURI;
40 use Friendica\Model\Post;
41 use Friendica\Model\Tag;
42 use Friendica\Model\User;
43 use Friendica\Network\HTTPClient\Client\HttpClientAccept;
44 use Friendica\Network\Probe;
45 use Friendica\Util\DateTimeFormat;
46 use Friendica\Util\Images;
47 use Friendica\Util\Proxy;
48 use Friendica\Util\Strings;
49 use Friendica\Util\XML;
52 * This class contain functions for the OStatus protocol
56 private static $itemlist;
57 private static $conv_list = [];
62 * @param DOMXPath $xpath The xpath object
63 * @param object $context The xml context of the author details
64 * @param array $importer user record of the importing user
65 * @param array $contact Called by reference, will contain the fetched contact
66 * @param bool $onlyfetch Only fetch the header without updating the contact entries
68 * @return array Array of author related entries for the item
69 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
70 * @throws \ImagickException
72 private static function fetchAuthor(DOMXPath $xpath, $context, array $importer, array &$contact = null, bool $onlyfetch): array
75 $author['author-link'] = XML::getFirstNodeValue($xpath, 'atom:author/atom:uri/text()', $context);
76 $author['author-name'] = XML::getFirstNodeValue($xpath, 'atom:author/atom:name/text()', $context);
77 $addr = XML::getFirstNodeValue($xpath, 'atom:author/atom:email/text()', $context);
79 $aliaslink = $author['author-link'];
81 $alternate_item = $xpath->query("atom:author/atom:link[@rel='alternate']", $context)->item(0);
82 if (is_object($alternate_item)) {
83 foreach ($alternate_item->attributes as $attributes) {
84 if (($attributes->name == 'href') && ($attributes->textContent != '')) {
85 $author['author-link'] = $attributes->textContent;
89 $author['author-id'] = Contact::getIdForURL($author['author-link']);
91 $author['contact-id'] = ($contact['id'] ?? 0) ?: $author['author-id'];
96 This here would be better, but we would get problems with contacts from the statusnet addon
97 This is kept here as a reminder for the future
99 $cid = Contact::getIdForURL($author['author-link'], $importer['uid']);
101 $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
104 if ($aliaslink != '') {
105 $contact = DBA::selectFirst('contact', [], [
106 "`uid` = ? AND `alias` = ? AND `rel` IN (?, ?)",
109 Contact::SHARING, Contact::FRIEND,
113 if (!DBA::isResult($contact) && $author['author-link'] != '') {
114 if ($aliaslink == '') {
115 $aliaslink = $author['author-link'];
118 $contact = DBA::selectFirst('contact', [], [
119 "`uid` = ? AND `nurl` IN (?, ?) AND `rel` IN (?, ?)",
121 Strings::normaliseLink($author['author-link']),
122 Strings::normaliseLink($aliaslink),
128 if (!DBA::isResult($contact) && ($addr != '')) {
129 $contact = DBA::selectFirst('contact', [], [
130 "`uid` = ? AND `addr` = ? AND `rel` IN (?, ?)",
138 if (DBA::isResult($contact)) {
139 if ($contact['blocked']) {
141 } elseif (!empty(APContact::getByURL($contact['url'], false))) {
142 ActivityPub\Receiver::switchContact($contact['id'], $importer['uid'], $contact['url']);
144 $author['contact-id'] = $contact['id'];
148 $avatars = $xpath->query("atom:author/atom:link[@rel='avatar']", $context);
149 foreach ($avatars as $avatar) {
152 foreach ($avatar->attributes as $attributes) {
153 if ($attributes->name == 'href') {
154 $href = $attributes->textContent;
156 if ($attributes->name == 'width') {
157 $width = $attributes->textContent;
161 $avatarlist[$width] = $href;
164 if (count($avatarlist) > 0) {
166 $author['author-avatar'] = Probe::fixAvatar(current($avatarlist), $author['author-link']);
169 $displayname = XML::getFirstNodeValue($xpath, 'atom:author/poco:displayName/text()', $context);
170 if ($displayname != '') {
171 $author['author-name'] = $displayname;
174 $author['owner-id'] = $author['author-id'];
176 // Only update the contacts if it is an OStatus contact
177 if (DBA::isResult($contact) && ($contact['id'] > 0) && !$onlyfetch && ($contact['network'] == Protocol::OSTATUS)) {
179 // Update contact data
181 unset($current['name-date']);
183 // This query doesn't seem to work
184 // $value = $xpath->query("atom:link[@rel='salmon']", $context)->item(0)->nodeValue;
186 // $contact["notify"] = $value;
188 // This query doesn't seem to work as well - I hate these queries
189 // $value = $xpath->query("atom:link[@rel='self' and @type='application/atom+xml']", $context)->item(0)->nodeValue;
191 // $contact["poll"] = $value;
193 $contact['url'] = $author['author-link'];
194 $contact['nurl'] = Strings::normaliseLink($contact['url']);
196 $value = XML::getFirstNodeValue($xpath, 'atom:author/atom:uri/text()', $context);
198 $contact['alias'] = $value;
201 $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:displayName/text()', $context);
203 $contact['name'] = $value;
206 $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:preferredUsername/text()', $context);
208 $contact['nick'] = $value;
211 $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:note/text()', $context);
213 $contact['about'] = HTML::toBBCode($value);
216 $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:address/poco:formatted/text()', $context);
218 $contact['location'] = $value;
221 $contact['name-date'] = DateTimeFormat::utcNow();
223 Contact::update($contact, ['id' => $contact['id']], $current);
225 if (!empty($author['author-avatar']) && ($author['author-avatar'] != $current['avatar'])) {
226 Logger::info('Update profile picture for contact ' . $contact['id']);
227 Contact::updateAvatar($contact['id'], $author['author-avatar']);
230 // Ensure that we are having this contact (with uid=0)
231 $cid = Contact::getIdForURL($aliaslink);
234 $fields = ['url', 'nurl', 'name', 'nick', 'alias', 'about', 'location'];
235 $old_contact = DBA::selectFirst('contact', $fields, ['id' => $cid]);
237 // Update it with the current values
239 'url' => $author['author-link'],
240 'name' => $contact['name'],
241 'nurl' => Strings::normaliseLink($author['author-link']),
242 'nick' => $contact['nick'],
243 'alias' => $contact['alias'],
244 'about' => $contact['about'],
245 'location' => $contact['location'],
246 'success_update' => DateTimeFormat::utcNow(),
247 'last-update' => DateTimeFormat::utcNow(),
250 Contact::update($fields, ['id' => $cid], $old_contact);
253 if (!empty($author['author-avatar'])) {
254 Contact::updateAvatar($cid, $author['author-avatar']);
257 } elseif (empty($contact['network']) || ($contact['network'] != Protocol::DFRN)) {
265 * Fetches author data from a given XML string
267 * @param string $xml The XML
268 * @param array $importer user record of the importing user
270 * @return array Array of author related entries for the item
271 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
272 * @throws \ImagickException
274 public static function salmonAuthor(string $xml, array $importer): array
280 $doc = new DOMDocument();
281 @$doc->loadXML($xml);
283 $xpath = new DOMXPath($doc);
284 $xpath->registerNamespace('atom', ActivityNamespace::ATOM1);
285 $xpath->registerNamespace('thr', ActivityNamespace::THREAD);
286 $xpath->registerNamespace('georss', ActivityNamespace::GEORSS);
287 $xpath->registerNamespace('activity', ActivityNamespace::ACTIVITY);
288 $xpath->registerNamespace('media', ActivityNamespace::MEDIA);
289 $xpath->registerNamespace('poco', ActivityNamespace::POCO);
290 $xpath->registerNamespace('ostatus', ActivityNamespace::OSTATUS);
291 $xpath->registerNamespace('statusnet', ActivityNamespace::STATUSNET);
293 $contact = ['id' => 0];
295 // Fetch the first author
296 $authordata = $xpath->query('//author')->item(0);
297 $author = self::fetchAuthor($xpath, $authordata, $importer, $contact, true);
302 * Read attributes from element
304 * @param object $element Element object
305 * @return array attributes
307 private static function readAttributes($element): array
311 foreach ($element->attributes as $attributes) {
312 $attribute[$attributes->name] = $attributes->textContent;
319 * Imports an XML string containing OStatus elements
321 * @param string $xml The XML
322 * @param array $importer user record of the importing user
323 * @param array $contact contact
324 * @param string $hub Called by reference, returns the fetched hub data
326 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
327 * @throws \ImagickException
329 public static function import($xml, array $importer, array &$contact, &$hub)
331 self::process($xml, $importer, $contact, $hub, false, true, Conversation::PUSH);
335 * Internal feed processing
337 * @param string $xml The XML
338 * @param array $importer user record of the importing user
339 * @param array $contact contact
340 * @param string $hub Called by reference, returns the fetched hub data
341 * @param boolean $stored Is the post fresh imported or from the database?
342 * @param boolean $initialize Is it the leading post so that data has to be initialized?
343 * @param integer $direction Direction, default UNKNOWN(0)
344 * @return boolean Could the XML be processed?
345 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
346 * @throws \ImagickException
348 private static function process(string $xml, array $importer, array &$contact = null, string &$hub, bool $stored = false, bool $initialize = true, int $direction = Conversation::UNKNOWN)
351 self::$itemlist = [];
352 self::$conv_list = [];
355 Logger::info('Import OStatus message for user ' . $importer['uid']);
361 $doc = new DOMDocument();
362 @$doc->loadXML($xml);
364 $xpath = new DOMXPath($doc);
365 $xpath->registerNamespace('atom', ActivityNamespace::ATOM1);
366 $xpath->registerNamespace('thr', ActivityNamespace::THREAD);
367 $xpath->registerNamespace('georss', ActivityNamespace::GEORSS);
368 $xpath->registerNamespace('activity', ActivityNamespace::ACTIVITY);
369 $xpath->registerNamespace('media', ActivityNamespace::MEDIA);
370 $xpath->registerNamespace('poco', ActivityNamespace::POCO);
371 $xpath->registerNamespace('ostatus', ActivityNamespace::OSTATUS);
372 $xpath->registerNamespace('statusnet', ActivityNamespace::STATUSNET);
375 $hub_items = $xpath->query("/atom:feed/atom:link[@rel='hub']")->item(0);
376 if (is_object($hub_items)) {
377 $hub_attributes = $hub_items->attributes;
378 if (is_object($hub_attributes)) {
379 foreach ($hub_attributes as $hub_attribute) {
380 if ($hub_attribute->name == 'href') {
381 $hub = $hub_attribute->textContent;
382 Logger::info('Found hub ', ['hub' => $hub]);
389 $header['uid'] = $importer['uid'];
390 $header['network'] = Protocol::OSTATUS;
392 $header['origin'] = 0;
393 $header['gravity'] = Item::GRAVITY_COMMENT;
395 if (!is_object($doc->firstChild) || empty($doc->firstChild->tagName)) {
399 $first_child = $doc->firstChild->tagName;
401 if ($first_child == 'feed') {
402 $entries = $xpath->query('/atom:feed/atom:entry');
404 $entries = $xpath->query('/atom:entry');
407 if ($entries->length == 1) {
408 // We reformat the XML to make it better readable
409 $doc2 = new DOMDocument();
410 $doc2->loadXML($xml);
411 $doc2->preserveWhiteSpace = false;
412 $doc2->formatOutput = true;
413 $xml2 = $doc2->saveXML();
415 $header['protocol'] = Conversation::PARCEL_SALMON;
416 $header['source'] = $xml2;
417 $header['direction'] = $direction;
418 } elseif (!$initialize) {
422 // Fetch the first author
423 $authordata = $xpath->query('//author')->item(0);
424 $author = self::fetchAuthor($xpath, $authordata, $importer, $contact, $stored);
426 // Reverse the order of the entries
429 foreach ($entries as $entry) {
430 $entrylist[] = $entry;
433 foreach (array_reverse($entrylist) as $entry) {
435 $authorelement = $xpath->query('/atom:entry/atom:author', $entry);
437 if ($authorelement->length == 0) {
438 $authorelement = $xpath->query('atom:author', $entry);
441 if ($authorelement->length > 0) {
442 $author = self::fetchAuthor($xpath, $entry, $importer, $contact, $stored);
445 $item = array_merge($header, $author);
447 $item['uri'] = XML::getFirstNodeValue($xpath, 'atom:id/text()', $entry);
448 $item['uri-id'] = ItemURI::insert(['uri' => $item['uri']]);
450 $item['verb'] = XML::getFirstNodeValue($xpath, 'activity:verb/text()', $entry);
453 if (in_array($item['verb'], ['qvitter-delete-notice', Activity::DELETE, 'delete'])) {
454 self::deleteNotice($item);
458 if (in_array($item['verb'], [Activity::O_UNFAVOURITE, Activity::UNFAVORITE])) {
459 // Ignore "Unfavorite" message
460 Logger::info('Ignore unfavorite message ', ['item' => $item]);
464 // Deletions come with the same uri, so we check for duplicates after processing deletions
465 if (Post::exists(['uid' => $importer['uid'], 'uri' => $item['uri']])) {
466 Logger::info('Post with URI ' . $item['uri'] . ' already existed for user ' . $importer['uid'] . '.');
469 Logger::info('Processing post with URI ' . $item['uri'] . ' for user ' . $importer['uid'] . '.');
472 if ($item['verb'] == Activity::JOIN) {
473 // ignore "Join" messages
474 Logger::info('Ignore join message ', ['item' => $item]);
478 if ($item['verb'] == 'http://mastodon.social/schema/1.0/block') {
479 // ignore mastodon "block" messages
480 Logger::info('Ignore block message ', ['item' => $item]);
484 if ($item['verb'] == Activity::FOLLOW) {
485 Contact::addRelationship($importer, $contact, $item);
489 if ($item['verb'] == Activity::O_UNFOLLOW) {
491 Contact::removeFollower($contact);
495 if ($item['verb'] == Activity::FAVORITE) {
496 $orig_uri = $xpath->query('activity:object/atom:id', $entry)->item(0)->nodeValue;
497 Logger::notice('Favorite', ['uri' => $orig_uri, 'item' => $item]);
499 $item['verb'] = Activity::LIKE;
500 $item['thr-parent'] = $orig_uri;
501 $item['gravity'] = Item::GRAVITY_ACTIVITY;
502 $item['object-type'] = Activity\ObjectType::NOTE;
505 // http://activitystrea.ms/schema/1.0/rsvp-yes
506 if (!in_array($item['verb'], [Activity::POST, Activity::LIKE, Activity::SHARE])) {
507 Logger::info('Unhandled verb', ['verb' => $item['verb'], 'item' => $item]);
510 self::processPost($xpath, $entry, $item, $importer);
512 if ($initialize && (count(self::$itemlist) > 0)) {
513 if (self::$itemlist[0]['uri'] == self::$itemlist[0]['thr-parent']) {
514 $uid = self::$itemlist[0]['uid'];
515 // We will import it everytime, when it is started by our contacts
516 $valid = Contact::isSharingByURL(self::$itemlist[0]['author-link'], $uid);
519 // If not, then it depends on this setting
520 $valid = !$uid || DI::pConfig()->get($uid, 'system', 'accept_only_sharer') != Item::COMPLETION_NONE;
523 Logger::info('Item with URI ' . self::$itemlist[0]['uri'] . ' will be imported due to the system settings.');
526 Logger::info('Item with URI ' . self::$itemlist[0]['uri'] . ' belongs to a contact (' . self::$itemlist[0]['contact-id'] . '). It will be imported.');
529 if ($valid && DI::pConfig()->get($uid, 'system', 'accept_only_sharer') != Item::COMPLETION_LIKE) {
530 // Never post a thread when the only interaction by our contact was a like
532 $verbs = [Activity::POST, Activity::SHARE];
533 foreach (self::$itemlist as $item) {
534 if (in_array($item['verb'], $verbs) && Contact::isSharingByURL($item['author-link'], $item['uid'])) {
539 Logger::info('Item with URI ' . self::$itemlist[0]['uri'] . ' will be imported since the thread contains posts or shares.');
547 $default_contact = 0;
548 for ($key = count(self::$itemlist) - 1; $key >= 0; $key--) {
549 if (empty(self::$itemlist[$key]['contact-id'])) {
550 self::$itemlist[$key]['contact-id'] = $default_contact;
552 $default_contact = $item['contact-id'];
555 foreach (self::$itemlist as $item) {
556 $found = Post::exists(['uid' => $importer['uid'], 'uri' => $item['uri']]);
558 Logger::notice('Item with URI ' . $item['uri'] . ' for user ' . $importer['uid'] . ' already exists.');
559 } elseif ($item['contact-id'] < 0) {
560 Logger::notice('Item with URI ' . $item['uri'] . ' is from a blocked contact.');
562 $ret = Item::insert($item);
563 Logger::info('Item with URI ' . $item['uri'] . ' for user ' . $importer['uid'] . ' stored. Return value: ' . $ret);
567 self::$itemlist = [];
569 Logger::info('Processing done for post with URI ' . $item['uri'] . ' for user '.$importer['uid'] . '.');
575 * Removes notice item from database
577 * @param array $item item
581 private static function deleteNotice(array $item)
583 $condition = ['uid' => $item['uid'], 'author-id' => $item['author-id'], 'uri' => $item['uri']];
584 if (!Post::exists($condition)) {
585 Logger::notice('Item from ' . $item['author-link'] . ' with uri ' . $item['uri'] . ' for user ' . $item['uid'] . " wasn't found. We don't delete it.");
589 Item::markForDeletion($condition);
591 Logger::notice('Deleted item with URI ' . $item['uri'] . ' for user ' . $item['uid']);
595 * Processes the XML for a post
597 * @param DOMXPath $xpath The xpath object
598 * @param object $entry The xml entry that is processed
599 * @param array $item The item array
600 * @param array $importer user record of the importing user
602 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
603 * @throws \ImagickException
605 private static function processPost(DOMXPath $xpath, $entry, array &$item, array $importer)
607 $item['body'] = HTML::toBBCode(XML::getFirstNodeValue($xpath, 'atom:content/text()', $entry));
608 $item['object-type'] = XML::getFirstNodeValue($xpath, 'activity:object-type/text()', $entry);
609 if (($item['object-type'] == Activity\ObjectType::BOOKMARK) || ($item['object-type'] == Activity\ObjectType::EVENT)) {
610 $item['title'] = XML::getFirstNodeValue($xpath, 'atom:title/text()', $entry);
611 $item['body'] = XML::getFirstNodeValue($xpath, 'atom:summary/text()', $entry);
612 } elseif ($item['object-type'] == Activity\ObjectType::QUESTION) {
613 $item['title'] = XML::getFirstNodeValue($xpath, 'atom:title/text()', $entry);
616 $item['created'] = XML::getFirstNodeValue($xpath, 'atom:published/text()', $entry);
617 $item['edited'] = XML::getFirstNodeValue($xpath, 'atom:updated/text()', $entry);
618 $item['conversation'] = XML::getFirstNodeValue($xpath, 'ostatus:conversation/text()', $entry);
620 $conv = $xpath->query('ostatus:conversation', $entry);
621 if (is_object($conv->item(0))) {
622 foreach ($conv->item(0)->attributes as $attributes) {
623 if ($attributes->name == 'ref') {
624 $item['conversation'] = $attributes->textContent;
626 if ($attributes->name == 'href') {
627 $item['conversation'] = $attributes->textContent;
634 $inreplyto = $xpath->query('thr:in-reply-to', $entry);
635 if (is_object($inreplyto->item(0))) {
636 foreach ($inreplyto->item(0)->attributes as $attributes) {
637 if ($attributes->name == 'ref') {
638 $item['thr-parent'] = $attributes->textContent;
640 if ($attributes->name == 'href') {
641 $related = $attributes->textContent;
646 $georsspoint = $xpath->query('georss:point', $entry);
647 if (!empty($georsspoint) && ($georsspoint->length > 0)) {
648 $item['coord'] = $georsspoint->item(0)->nodeValue;
651 $categories = $xpath->query('atom:category', $entry);
653 foreach ($categories as $category) {
654 foreach ($category->attributes as $attributes) {
655 if ($attributes->name == 'term') {
657 Tag::store($item['uri-id'], Tag::HASHTAG, $attributes->textContent);
666 $links = $xpath->query('atom:link', $entry);
668 $link_data = self::processLinks($links, $item);
669 $self = $link_data['self'];
670 $add_body = $link_data['add_body'];
675 $notice_info = $xpath->query('statusnet:notice_info', $entry);
676 if ($notice_info && ($notice_info->length > 0)) {
677 foreach ($notice_info->item(0)->attributes as $attributes) {
678 if ($attributes->name == 'source') {
679 $item['app'] = strip_tags($attributes->textContent);
681 if ($attributes->name == 'repeat_of') {
682 $repeat_of = $attributes->textContent;
686 // Is it a repeated post?
687 if (($repeat_of != '') || ($item['verb'] == Activity::SHARE)) {
688 $link_data = self::processRepeatedItem($xpath, $entry, $item, $importer);
689 if (!empty($link_data['add_body'])) {
690 $add_body .= $link_data['add_body'];
694 $item['body'] .= $add_body;
696 Tag::storeFromBody($item['uri-id'], $item['body']);
698 // Mastodon Content Warning
699 if (($item['verb'] == Activity::POST) && $xpath->evaluate('boolean(atom:summary)', $entry)) {
700 $clear_text = XML::getFirstNodeValue($xpath, 'atom:summary/text()', $entry);
701 if (!empty($clear_text)) {
702 $item['content-warning'] = HTML::toBBCode($clear_text);
706 if (isset($item['thr-parent'])) {
707 if (!Post::exists(['uid' => $importer['uid'], 'uri' => $item['thr-parent']])) {
708 if ($related != '') {
709 self::fetchRelated($related, $item['thr-parent'], $importer);
712 Logger::info('Reply with URI ' . $item['uri'] . ' already existed for user ' . $importer['uid'] . '.');
715 $item['thr-parent'] = $item['uri'];
716 $item['gravity'] = Item::GRAVITY_PARENT;
719 self::$itemlist[] = $item;
723 * Fetch related posts and processes them
725 * @param string $related The link to the related item
726 * @param string $related_uri The related item in "uri" format
727 * @param array $importer user record of the importing user
729 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
730 * @throws \ImagickException
732 private static function fetchRelated(string $related, string $related_uri, array $importer)
735 $curlResult = DI::httpClient()->get($related, HttpClientAccept::ATOM_XML);
737 if (!$curlResult->isSuccess() || empty($curlResult->getBody())) {
743 if ($curlResult->inHeader('Content-Type') &&
744 in_array('application/atom+xml', $curlResult->getHeader('Content-Type'))) {
745 Logger::info('Directly fetched XML for URI ' . $related_uri);
746 $xml = $curlResult->getBody();
750 $doc = new DOMDocument();
751 if (!@$doc->loadHTML($curlResult->getBody())) {
754 $xpath = new DOMXPath($doc);
758 $links = $xpath->query('//link');
760 foreach ($links as $link) {
761 $attribute = self::readAttributes($link);
762 if (($attribute['rel'] == 'alternate') && ($attribute['type'] == 'application/atom+xml')) {
763 $atom_file = $attribute['href'];
766 if ($atom_file != '') {
767 $curlResult = DI::httpClient()->get($atom_file, HttpClientAccept::ATOM_XML);
769 if ($curlResult->isSuccess()) {
770 Logger::info('Fetched XML for URI ' . $related_uri);
771 $xml = $curlResult->getBody();
777 // Workaround for older GNU Social servers
778 if (($xml == '') && strstr($related, '/notice/')) {
779 $curlResult = DI::httpClient()->get(str_replace('/notice/', '/api/statuses/show/', $related) . '.atom', HttpClientAccept::ATOM_XML);
781 if ($curlResult->isSuccess()) {
782 Logger::info('GNU Social workaround to fetch XML for URI ' . $related_uri);
783 $xml = $curlResult->getBody();
787 // Even more worse workaround for GNU Social ;-)
789 $related_guess = self::convertHref($related_uri);
790 $curlResult = DI::httpClient()->get(str_replace('/notice/', '/api/statuses/show/', $related_guess) . '.atom', HttpClientAccept::ATOM_XML);
792 if ($curlResult->isSuccess()) {
793 Logger::info('GNU Social workaround 2 to fetch XML for URI ' . $related_uri);
794 $xml = $curlResult->getBody();
800 self::process($xml, $importer, $contact, $hub, $stored, false, Conversation::PULL);
802 Logger::info('XML could not be fetched for URI: ' . $related_uri . ' - href: ' . $related);
808 * Processes the XML for a repeated post
810 * @param DOMXPath $xpath The xpath object
811 * @param object $entry The xml entry that is processed
812 * @param array $item The item array
813 * @param array $importer user record of the importing user
815 * @return array with data from links
816 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
817 * @throws \ImagickException
819 private static function processRepeatedItem(DOMXPath $xpath, $entry, array &$item, array $importer): array
821 $activityobject = $xpath->query('activity:object', $entry)->item(0);
823 if (!is_object($activityobject)) {
829 $orig_uri = XML::getFirstNodeValue($xpath, 'atom:id/text()', $activityobject);
831 $links = $xpath->query('atom:link', $activityobject);
833 $link_data = self::processLinks($links, $item);
836 $orig_body = XML::getFirstNodeValue($xpath, 'atom:content/text()', $activityobject);
837 $orig_created = XML::getFirstNodeValue($xpath, 'atom:published/text()', $activityobject);
838 $orig_edited = XML::getFirstNodeValue($xpath, 'atom:updated/text()', $activityobject);
840 $orig_author = self::fetchAuthor($xpath, $activityobject, $importer, $dummy, false);
842 $item['author-name'] = $orig_author['author-name'];
843 $item['author-link'] = $orig_author['author-link'];
844 $item['author-id'] = $orig_author['author-id'];
846 $item['body'] = HTML::toBBCode($orig_body);
847 $item['created'] = $orig_created;
848 $item['edited'] = $orig_edited;
850 $item['uri'] = $orig_uri;
852 $item['verb'] = XML::getFirstNodeValue($xpath, 'activity:verb/text()', $activityobject);
854 $item['object-type'] = XML::getFirstNodeValue($xpath, 'activity:object-type/text()', $activityobject);
856 // Mastodon Content Warning
857 if (($item['verb'] == Activity::POST) && $xpath->evaluate('boolean(atom:summary)', $activityobject)) {
858 $clear_text = XML::getFirstNodeValue($xpath, 'atom:summary/text()', $activityobject);
859 if (!empty($clear_text)) {
860 $item['content-warning'] = HTML::toBBCode($clear_text);
864 $inreplyto = $xpath->query('thr:in-reply-to', $activityobject);
865 if (is_object($inreplyto->item(0))) {
866 foreach ($inreplyto->item(0)->attributes as $attributes) {
867 if ($attributes->name == 'ref') {
868 $item['thr-parent'] = $attributes->textContent;
877 * Processes links in the XML
879 * @param object $links The xml data that contain links
880 * @param array $item The item array
881 * @return array with data from the links
883 private static function processLinks($links, array &$item): array
885 $link_data = ['add_body' => '', 'self' => ''];
887 foreach ($links as $link) {
888 $attribute = self::readAttributes($link);
890 if (!empty($attribute['rel']) && !empty($attribute['href'])) {
891 switch ($attribute['rel']) {
893 $item['plink'] = $attribute['href'];
894 if (($item['object-type'] == Activity\ObjectType::QUESTION)
895 || ($item['object-type'] == Activity\ObjectType::EVENT)
897 Post\Media::insert(['uri-id' => $item['uri-id'], 'type' => Post\Media::UNKNOWN,
898 'url' => $attribute['href'], 'mimetype' => $attribute['type'] ?? null,
899 'size' => $attribute['length'] ?? null, 'description' => $attribute['title'] ?? null]);
903 case 'ostatus:conversation':
904 $link_data['conversation'] = $attribute['href'];
905 $item['conversation'] = $link_data['conversation'];
909 $filetype = strtolower(substr($attribute['type'], 0, strpos($attribute['type'], '/')));
910 if ($filetype == 'image') {
911 $link_data['add_body'] .= "\n[img]".$attribute['href'].'[/img]';
913 Post\Media::insert(['uri-id' => $item['uri-id'], 'type' => Post\Media::DOCUMENT,
914 'url' => $attribute['href'], 'mimetype' => $attribute['type'],
915 'size' => $attribute['length'] ?? null, 'description' => $attribute['title'] ?? null]);
920 if ($item['object-type'] != Activity\ObjectType::BOOKMARK) {
921 if (!isset($item['thr-parent'])) {
922 $item['thr-parent'] = $attribute['href'];
924 $link_data['related'] = $attribute['href'];
926 Post\Media::insert(['uri-id' => $item['uri-id'], 'type' => Post\Media::UNKNOWN,
927 'url' => $attribute['href'], 'mimetype' => $attribute['type'] ?? null,
928 'size' => $attribute['length'] ?? null, 'description' => $attribute['title'] ?? null]);
933 if (empty($item['plink'])) {
934 $item['plink'] = $attribute['href'];
936 $link_data['self'] = $attribute['href'];
940 Logger::notice('Unsupported rel=' . $attribute['rel'] . ', href=' . $attribute['href'] . ', object-type=' . $item['object-type']);
948 * Create an url out of an uri
950 * @param string $href URI in the format "parameter1:parameter1:..."
951 * @return string URL in the format http(s)://....
953 private static function convertHref(string $href): string
955 $elements = explode(':', $href);
957 if ((count($elements) <= 2) || ($elements[0] != 'tag')) {
961 $server = explode(',', $elements[1]);
962 $conversation = explode('=', $elements[2]);
964 if ((count($elements) == 4) && ($elements[2] == 'post')) {
965 return 'http://' . $server[0] . '/notice/' . $elements[3];
968 if ((count($conversation) != 2) || ($conversation[1] == '')) {
972 if ($elements[3] == 'objectType=thread') {
973 return 'http://' . $server[0] . '/conversation/' . $conversation[1];
975 return 'http://' . $server[0] . '/notice/' . $conversation[1];
980 * Cleans the body of a post if it contains picture links
982 * @param string $body The body
983 * @param integer $uriId
984 * @return string The cleaned body
985 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
987 public static function formatPicturePost(string $body, int $uriid): string
989 $siteinfo = BBCode::getAttachedData($body);
991 if (($siteinfo['type'] == 'photo') && (!empty($siteinfo['preview']) || !empty($siteinfo['image']))) {
992 if (isset($siteinfo['preview'])) {
993 $preview = $siteinfo['preview'];
995 $preview = $siteinfo['image'];
998 // Is it a remote picture? Then make a smaller preview here
999 $preview = Post\Link::getByLink($uriid, $preview, Proxy::SIZE_SMALL);
1001 // Is it a local picture? Then make it smaller here
1002 $preview = str_replace(['-0.jpg', '-0.png'], ['-2.jpg', '-2.png'], $preview);
1003 $preview = str_replace(['-1.jpg', '-1.png'], ['-2.jpg', '-2.png'], $preview);
1005 if (isset($siteinfo['url'])) {
1006 $url = $siteinfo['url'];
1008 $url = $siteinfo['image'];
1011 $body = trim($siteinfo['text']) . ' [url]' . $url . "[/url]\n[img]" . $preview . '[/img]';
1018 * Adds the header elements to the XML document
1020 * @param DOMDocument $doc XML document
1021 * @param array $owner Contact data of the poster
1022 * @param string $filter The related feed filter (activity, posts or comments)
1024 * @return DOMElement Header root element
1025 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1027 private static function addHeader(DOMDocument $doc, array $owner, string $filter): DOMElement
1029 $root = $doc->createElementNS(ActivityNamespace::ATOM1, 'feed');
1030 $doc->appendChild($root);
1032 $root->setAttribute('xmlns:thr', ActivityNamespace::THREAD);
1033 $root->setAttribute('xmlns:georss', ActivityNamespace::GEORSS);
1034 $root->setAttribute('xmlns:activity', ActivityNamespace::ACTIVITY);
1035 $root->setAttribute('xmlns:media', ActivityNamespace::MEDIA);
1036 $root->setAttribute('xmlns:poco', ActivityNamespace::POCO);
1037 $root->setAttribute('xmlns:ostatus', ActivityNamespace::OSTATUS);
1038 $root->setAttribute('xmlns:statusnet', ActivityNamespace::STATUSNET);
1039 $root->setAttribute('xmlns:mastodon', ActivityNamespace::MASTODON);
1042 $selfUri = '/feed/' . $owner['nick'] . '/';
1045 $title = DI::l10n()->t('%s\'s timeline', $owner['name']);
1046 $selfUri .= $filter;
1050 $title = DI::l10n()->t('%s\'s posts', $owner['name']);
1054 $title = DI::l10n()->t('%s\'s comments', $owner['name']);
1055 $selfUri .= $filter;
1059 $selfUri = '/dfrn_poll/' . $owner['nick'];
1062 'uri' => 'https://friendi.ca',
1063 'version' => App::VERSION . '-' . DB_UPDATE_VERSION,
1065 XML::addElement($doc, $root, 'generator', App::PLATFORM, $attributes);
1066 XML::addElement($doc, $root, 'id', DI::baseUrl() . '/profile/' . $owner['nick']);
1067 XML::addElement($doc, $root, 'title', $title);
1068 XML::addElement($doc, $root, 'subtitle', sprintf("Updates from %s on %s", $owner['name'], DI::config()->get('config', 'sitename')));
1069 XML::addElement($doc, $root, 'logo', User::getAvatarUrl($owner, Proxy::SIZE_SMALL));
1070 XML::addElement($doc, $root, 'updated', DateTimeFormat::utcNow(DateTimeFormat::ATOM));
1072 $author = self::addAuthor($doc, $owner, true);
1073 $root->appendChild($author);
1076 'href' => $owner['url'],
1077 'rel' => 'alternate',
1078 'type' => 'text/html',
1080 XML::addElement($doc, $root, 'link', '', $attributes);
1082 /// @TODO We have to find out what this is
1083 /// $attributes = array("href" => DI::baseUrl()."/sup",
1084 /// "rel" => "http://api.friendfeed.com/2008/03#sup",
1085 /// "type" => "application/json");
1086 /// XML::addElement($doc, $root, "link", "", $attributes);
1088 self::addHubLink($doc, $root, $owner['nick']);
1090 $attributes = ['href' => DI::baseUrl() . '/salmon/' . $owner['nick'], 'rel' => 'salmon'];
1091 XML::addElement($doc, $root, 'link', '', $attributes);
1093 $attributes = ['href' => DI::baseUrl() . '/salmon/' . $owner['nick'], 'rel' => 'http://salmon-protocol.org/ns/salmon-replies'];
1094 XML::addElement($doc, $root, 'link', '', $attributes);
1096 $attributes = ['href' => DI::baseUrl() . '/salmon/' . $owner['nick'], 'rel' => 'http://salmon-protocol.org/ns/salmon-mention'];
1097 XML::addElement($doc, $root, 'link', '', $attributes);
1099 $attributes = ['href' => DI::baseUrl() . $selfUri, 'rel' => 'self', 'type' => 'application/atom+xml'];
1100 XML::addElement($doc, $root, 'link', '', $attributes);
1102 if ($owner['contact-type'] == Contact::TYPE_COMMUNITY) {
1103 $members = DBA::count('contact', [
1104 'uid' => $owner['uid'],
1111 XML::addElement($doc, $root, 'statusnet:group_info', '', ['member_count' => $members]);
1118 * Add the link to the push hubs to the XML document
1120 * @param DOMDocument $doc XML document
1121 * @param DOMElement $root XML root element where the hub links are added
1122 * @param string $nick Nickname
1124 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1126 public static function addHubLink(DOMDocument $doc, DOMElement $root, string $nick)
1128 $h = DI::baseUrl() . '/pubsubhubbub/' . $nick;
1129 XML::addElement($doc, $root, 'link', '', ['href' => $h, 'rel' => 'hub']);
1133 * Adds attachment data to the XML document
1135 * @param DOMDocument $doc XML document
1136 * @param DOMElement $root XML root element where the hub links are added
1137 * @param array $item Data of the item that is to be posted
1139 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1141 public static function getAttachment(DOMDocument $doc, DOMElement $root, array $item)
1143 $siteinfo = BBCode::getAttachedData($item['body']);
1145 switch ($siteinfo['type']) {
1147 if (!empty($siteinfo['image'])) {
1148 $imgdata = Images::getInfoFromURLCached($siteinfo['image']);
1151 'rel' => 'enclosure',
1152 'href' => $siteinfo['image'],
1153 'type' => $imgdata['mime'],
1154 'length' => intval($imgdata['size']),
1156 XML::addElement($doc, $root, 'link', '', $attributes);
1163 'rel' => 'enclosure',
1164 'href' => $siteinfo['url'],
1165 'type' => 'text/html; charset=UTF-8',
1167 'title' => ($siteinfo['title'] ?? '') ?: $siteinfo['url'],
1169 XML::addElement($doc, $root, 'link', '', $attributes);
1173 if (!DI::config()->get('system', 'ostatus_not_attach_preview') && ($siteinfo['type'] != 'photo') && isset($siteinfo['image'])) {
1174 $imgdata = Images::getInfoFromURLCached($siteinfo['image']);
1177 'rel' => 'enclosure',
1178 'href' => $siteinfo['image'],
1179 'type' => $imgdata['mime'],
1180 'length' => intval($imgdata['size']),
1183 XML::addElement($doc, $root, 'link', '', $attributes);
1187 foreach (Post\Media::getByURIId($item['uri-id'], [Post\Media::DOCUMENT, Post\Media::TORRENT]) as $attachment) {
1188 $attributes = ['rel' => 'enclosure',
1189 'href' => $attachment['url'],
1190 'type' => $attachment['mimetype']];
1192 if (!empty($attachment['size'])) {
1193 $attributes['length'] = intval($attachment['size']);
1195 if (!empty($attachment['description'])) {
1196 $attributes['title'] = $attachment['description'];
1199 XML::addElement($doc, $root, 'link', '', $attributes);
1204 * Adds the author element to the XML document
1206 * @param DOMDocument $doc XML document
1207 * @param array $owner Contact data of the poster
1208 * @param bool $show_profile Whether to show profile
1209 * @return DOMElement Author element
1210 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1212 private static function addAuthor(DOMDocument $doc, array $owner, bool $show_profile = true): DOMElement
1214 $profile = DBA::selectFirst('profile', ['homepage', 'publish'], ['uid' => $owner['uid']]);
1215 $author = $doc->createElement('author');
1216 XML::addElement($doc, $author, 'id', $owner['url']);
1217 if ($owner['contact-type'] == Contact::TYPE_COMMUNITY) {
1218 XML::addElement($doc, $author, 'activity:object-type', Activity\ObjectType::GROUP);
1220 XML::addElement($doc, $author, 'activity:object-type', Activity\ObjectType::PERSON);
1223 XML::addElement($doc, $author, 'uri', $owner['url']);
1224 XML::addElement($doc, $author, 'name', $owner['nick']);
1225 XML::addElement($doc, $author, 'email', $owner['addr']);
1226 if ($show_profile) {
1227 XML::addElement($doc, $author, 'summary', BBCode::convertForUriId($owner['uri-id'], $owner['about'], BBCode::OSTATUS));
1231 'rel' => 'alternate',
1232 'type' => 'text/html',
1233 'href' => $owner['url'],
1235 XML::addElement($doc, $author, 'link', '', $attributes);
1239 'type' => 'image/jpeg', // To-Do?
1240 'media:width' => Proxy::PIXEL_SMALL,
1241 'media:height' => Proxy::PIXEL_SMALL,
1242 'href' => User::getAvatarUrl($owner, Proxy::SIZE_SMALL),
1244 XML::addElement($doc, $author, 'link', '', $attributes);
1246 if (isset($owner['thumb'])) {
1249 'type' => 'image/jpeg', // To-Do?
1250 'media:width' => Proxy::PIXEL_THUMB,
1251 'media:height' => Proxy::PIXEL_THUMB,
1252 'href' => User::getAvatarUrl($owner, Proxy::SIZE_THUMB),
1254 XML::addElement($doc, $author, 'link', '', $attributes);
1257 XML::addElement($doc, $author, 'poco:preferredUsername', $owner['nick']);
1258 XML::addElement($doc, $author, 'poco:displayName', $owner['name']);
1259 if ($show_profile) {
1260 XML::addElement($doc, $author, 'poco:note', BBCode::convertForUriId($owner['uri-id'], $owner['about'], BBCode::OSTATUS));
1262 if (trim($owner['location']) != '') {
1263 $element = $doc->createElement('poco:address');
1264 XML::addElement($doc, $element, 'poco:formatted', $owner['location']);
1265 $author->appendChild($element);
1269 if (DBA::isResult($profile) && !$show_profile) {
1270 if (trim($profile['homepage']) != '') {
1271 $urls = $doc->createElement('poco:urls');
1272 XML::addElement($doc, $urls, 'poco:type', 'homepage');
1273 XML::addElement($doc, $urls, 'poco:value', $profile['homepage']);
1274 XML::addElement($doc, $urls, 'poco:primary', 'true');
1275 $author->appendChild($urls);
1278 XML::addElement($doc, $author, 'followers', '', ['url' => DI::baseUrl() . '/profile/' . $owner['nick'] . '/contacts/followers']);
1279 XML::addElement($doc, $author, 'statusnet:profile_info', '', ['local_id' => $owner['uid']]);
1281 if ($profile['publish']) {
1282 XML::addElement($doc, $author, 'mastodon:scope', 'public');
1290 * @TODO Picture attachments should look like this:
1291 * <a href="https://status.pirati.ca/attachment/572819" title="https://status.pirati.ca/file/heluecht-20151202T222602-rd3u49p.gif"
1292 * class="attachment thumbnail" id="attachment-572819" rel="nofollow external">https://status.pirati.ca/attachment/572819</a>
1296 * Returns the given activity if present - otherwise returns the "post" activity
1298 * @param array $item Data of the item that is to be posted
1299 * @return string activity
1301 public static function constructVerb(array $item): string
1303 if (!empty($item['verb'])) {
1304 return $item['verb'];
1307 return Activity::POST;
1311 * Returns the given object type if present - otherwise returns the "note" object type
1313 * @param array $item Data of the item that is to be posted
1314 * @return string Object type
1316 private static function constructObjecttype(array $item): string
1318 if (!empty($item['object-type']) && in_array($item['object-type'], [Activity\ObjectType::NOTE, Activity\ObjectType::COMMENT])) {
1319 return $item['object-type'];
1322 return Activity\ObjectType::NOTE;
1326 * Adds an entry element to the XML document
1328 * @param DOMDocument $doc XML document
1329 * @param array $item Data of the item that is to be posted
1330 * @param array $owner Contact data of the poster
1331 * @param bool $toplevel optional default false
1333 * @return DOMElement Entry element
1334 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1335 * @throws \ImagickException
1337 private static function entry(DOMDocument $doc, array $item, array $owner, bool $toplevel = false): DOMElement
1339 if ($item['verb'] == Activity::LIKE) {
1340 return self::likeEntry($doc, $item, $owner, $toplevel);
1341 } elseif (in_array($item['verb'], [Activity::FOLLOW, Activity::O_UNFOLLOW])) {
1342 return self::followEntry($doc, $item, $owner, $toplevel);
1344 return self::noteEntry($doc, $item, $owner, $toplevel);
1349 * Adds an entry element with a "like"
1351 * @param DOMDocument $doc XML document
1352 * @param array $item Data of the item that is to be posted
1353 * @param array $owner Contact data of the poster
1354 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1355 * @return DOMElement Entry element with "like"
1356 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1357 * @throws \ImagickException
1359 private static function likeEntry(DOMDocument $doc, array $item, array $owner, bool $toplevel): DOMElement
1361 if (($item['gravity'] != Item::GRAVITY_PARENT) && (Strings::normaliseLink($item['author-link']) != Strings::normaliseLink($owner['url']))) {
1362 Logger::info('OStatus entry is from author ' . $owner['url'] . ' - not from ' . $item['author-link'] . '. Quitting.');
1365 $entry = self::entryHeader($doc, $owner, $item, $toplevel);
1367 $verb = ActivityNamespace::ACTIVITY_SCHEMA . 'favorite';
1368 self::entryContent($doc, $entry, $item, $owner, 'Favorite', $verb, false);
1370 $parent = Post::selectFirst([], ['uri' => $item['thr-parent'], 'uid' => $item['uid']]);
1371 if (DBA::isResult($parent)) {
1372 $as_object = $doc->createElement('activity:object');
1374 XML::addElement($doc, $as_object, 'activity:object-type', self::constructObjecttype($parent));
1376 self::entryContent($doc, $as_object, $parent, $owner, 'New entry');
1378 $entry->appendChild($as_object);
1381 self::entryFooter($doc, $entry, $item, $owner);
1387 * Adds the person object element to the XML document
1389 * @param DOMDocument $doc XML document
1390 * @param array $owner Contact data of the poster
1391 * @param array $contact Contact data of the target
1392 * @return DOMElement author element
1394 private static function addPersonObject(DOMDocument $doc, array $owner, array $contact): DOMElement
1396 $object = $doc->createElement('activity:object');
1397 XML::addElement($doc, $object, 'activity:object-type', Activity\ObjectType::PERSON);
1399 if ($contact['network'] == Protocol::PHANTOM) {
1400 XML::addElement($doc, $object, 'id', $contact['url']);
1404 XML::addElement($doc, $object, 'id', $contact['alias']);
1405 XML::addElement($doc, $object, 'title', $contact['nick']);
1407 XML::addElement($doc, $object, 'link', '', [
1408 'rel' => 'alternate',
1409 'type' => 'text/html',
1410 'href' => $contact['url'],
1415 'type' => 'image/jpeg', // To-Do?
1416 'media:width' => 300,
1417 'media:height' => 300,
1418 'href' => $contact['photo'],
1420 XML::addElement($doc, $object, 'link', '', $attributes);
1422 XML::addElement($doc, $object, 'poco:preferredUsername', $contact['nick']);
1423 XML::addElement($doc, $object, 'poco:displayName', $contact['name']);
1425 if (trim($contact['location']) != '') {
1426 $element = $doc->createElement('poco:address');
1427 XML::addElement($doc, $element, 'poco:formatted', $contact['location']);
1428 $object->appendChild($element);
1435 * Adds a follow/unfollow entry element
1437 * @param DOMDocument $doc XML document
1438 * @param array $item Data of the follow/unfollow message
1439 * @param array $owner Contact data of the poster
1440 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1441 * @return DOMElement Entry element
1442 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1443 * @throws \ImagickException
1445 private static function followEntry(DOMDocument $doc, array $item, array $owner, bool $toplevel): DOMElement
1447 $item['id'] = $item['parent'] = 0;
1448 $item['created'] = $item['edited'] = date('c');
1449 $item['private'] = Item::PRIVATE;
1451 $contact = Contact::getByURL($item['follow']);
1452 $item['follow'] = $contact['url'];
1454 if ($contact['alias']) {
1455 $item['follow'] = $contact['alias'];
1457 $contact['alias'] = $contact['url'];
1460 $condition = ['uid' => $owner['uid'], 'nurl' => Strings::normaliseLink($contact['url'])];
1461 $user_contact = DBA::selectFirst('contact', ['id'], $condition);
1463 if (DBA::isResult($user_contact)) {
1464 $connect_id = $user_contact['id'];
1469 if ($item['verb'] == Activity::FOLLOW) {
1470 $message = DI::l10n()->t('%s is now following %s.');
1471 $title = DI::l10n()->t('following');
1472 $action = 'subscription';
1474 $message = DI::l10n()->t('%s stopped following %s.');
1475 $title = DI::l10n()->t('stopped following');
1476 $action = 'unfollow';
1479 $item['uri'] = $item['parent-uri'] = $item['thr-parent']
1480 = 'tag:' . DI::baseUrl()->getHostname().
1481 ','.date('Y-m-d').':'.$action.':'.$owner['uid'].
1482 ':person:'.$connect_id.':'.$item['created'];
1484 $item['body'] = sprintf($message, $owner['nick'], $contact['nick']);
1486 $entry = self::entryHeader($doc, $owner, $item, $toplevel);
1488 self::entryContent($doc, $entry, $item, $owner, $title);
1490 $object = self::addPersonObject($doc, $owner, $contact);
1491 $entry->appendChild($object);
1493 self::entryFooter($doc, $entry, $item, $owner);
1499 * Adds a regular entry element
1501 * @param DOMDocument $doc XML document
1502 * @param array $item Data of the item that is to be posted
1503 * @param array $owner Contact data of the poster
1504 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1505 * @return DOMElement Entry element
1506 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1507 * @throws \ImagickException
1509 private static function noteEntry(DOMDocument $doc, array $item, array $owner, bool $toplevel): DOMElement
1511 if (($item['gravity'] != Item::GRAVITY_PARENT) && (Strings::normaliseLink($item['author-link']) != Strings::normaliseLink($owner['url']))) {
1512 Logger::info('OStatus entry is from author ' . $owner['url'] . ' - not from ' . $item['author-link'] . '. Quitting.');
1516 if (!empty($item['title'])) {
1517 $title = BBCode::convertForUriId($item['uri-id'], $item['title'], BBCode::OSTATUS);
1519 $title = sprintf('New note by %s', $owner['nick']);
1522 $title = sprintf('New comment by %s', $owner['nick']);
1525 $entry = self::entryHeader($doc, $owner, $item, $toplevel);
1527 XML::addElement($doc, $entry, 'activity:object-type', Activity\ObjectType::NOTE);
1529 self::entryContent($doc, $entry, $item, $owner, $title, '', true);
1531 self::entryFooter($doc, $entry, $item, $owner, true);
1537 * Adds a header element to the XML document
1539 * @param DOMDocument $doc XML document
1540 * @param array $owner Contact data of the poster
1541 * @param array $item
1542 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1543 * @return DOMElement The entry element where the elements are added
1544 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1545 * @throws \ImagickException
1547 public static function entryHeader(DOMDocument $doc, array $owner, array $item, bool $toplevel): DOMElement
1550 $entry = $doc->createElement('entry');
1552 if ($owner['contact-type'] == Contact::TYPE_COMMUNITY) {
1553 $contact = Contact::getByURL($item['author-link']) ?: $owner;
1554 $contact['nickname'] = $contact['nickname'] ?? $contact['nick'];
1555 $author = self::addAuthor($doc, $contact, false);
1556 $entry->appendChild($author);
1559 $entry = $doc->createElementNS(ActivityNamespace::ATOM1, 'entry');
1561 $entry->setAttribute('xmlns:thr', ActivityNamespace::THREAD);
1562 $entry->setAttribute('xmlns:georss', ActivityNamespace::GEORSS);
1563 $entry->setAttribute('xmlns:activity', ActivityNamespace::ACTIVITY);
1564 $entry->setAttribute('xmlns:media', ActivityNamespace::MEDIA);
1565 $entry->setAttribute('xmlns:poco', ActivityNamespace::POCO);
1566 $entry->setAttribute('xmlns:ostatus', ActivityNamespace::OSTATUS);
1567 $entry->setAttribute('xmlns:statusnet', ActivityNamespace::STATUSNET);
1568 $entry->setAttribute('xmlns:mastodon', ActivityNamespace::MASTODON);
1570 $author = self::addAuthor($doc, $owner);
1571 $entry->appendChild($author);
1578 * Adds elements to the XML document
1580 * @param DOMDocument $doc XML document
1581 * @param DOMElement $entry Entry element where the content is added
1582 * @param array $item Data of the item that is to be posted
1583 * @param array $owner Contact data of the poster
1584 * @param string $title Title for the post
1585 * @param string $verb The activity verb
1586 * @param bool $complete Add the "status_net" element?
1588 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1590 private static function entryContent(DOMDocument $doc, DOMElement $entry, array $item, array $owner, string $title, string $verb = '', bool $complete = true)
1593 $verb = self::constructVerb($item);
1596 XML::addElement($doc, $entry, 'id', $item['uri']);
1597 XML::addElement($doc, $entry, 'title', html_entity_decode($title, ENT_QUOTES, 'UTF-8'));
1599 $body = Post\Media::addAttachmentsToBody($item['uri-id'], DI::contentItem()->addSharedPost($item));
1600 $body = self::formatPicturePost($body, $item['uri-id']);
1602 if (!empty($item['title'])) {
1603 $body = '[b]' . $item['title'] . "[/b]\n\n" . $body;
1606 $body = BBCode::convertForUriId($item['uri-id'], $body, BBCode::OSTATUS);
1608 XML::addElement($doc, $entry, 'content', $body, ['type' => 'html']);
1610 XML::addElement($doc, $entry, 'link', '', [
1611 'rel' => 'alternate',
1612 'type' => 'text/html',
1613 'href' => DI::baseUrl() . '/display/' . $item['guid'],
1616 if ($complete && ($item['id'] > 0)) {
1617 XML::addElement($doc, $entry, 'status_net', '', ['notice_id' => $item['id']]);
1620 XML::addElement($doc, $entry, 'activity:verb', $verb);
1622 XML::addElement($doc, $entry, 'published', DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM));
1623 XML::addElement($doc, $entry, 'updated', DateTimeFormat::utc($item['edited'] . '+00:00', DateTimeFormat::ATOM));
1627 * Adds the elements at the foot of an entry to the XML document
1629 * @param DOMDocument $doc XML document
1630 * @param object $entry The entry element where the elements are added
1631 * @param array $item Data of the item that is to be posted
1632 * @param array $owner Contact data of the poster
1633 * @param bool $complete default true
1635 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1637 private static function entryFooter(DOMDocument $doc, $entry, array $item, array $owner, bool $complete = true)
1641 if ($item['gravity'] != Item::GRAVITY_PARENT) {
1642 $parent = Post::selectFirst(['guid', 'author-link', 'owner-link'], ['id' => $item['parent']]);
1644 $thrparent = Post::selectFirst(['guid', 'author-link', 'owner-link', 'plink'], ['uid' => $owner['uid'], 'uri' => $item['thr-parent']]);
1646 if (DBA::isResult($thrparent)) {
1647 $mentioned[$thrparent['author-link']] = $thrparent['author-link'];
1648 $mentioned[$thrparent['owner-link']] = $thrparent['owner-link'];
1649 $parent_plink = $thrparent['plink'];
1650 } elseif (DBA::isResult($parent)) {
1651 $mentioned[$parent['author-link']] = $parent['author-link'];
1652 $mentioned[$parent['owner-link']] = $parent['owner-link'];
1653 $parent_plink = DI::baseUrl() . '/display/' . $parent['guid'];
1655 DI::logger()->notice('Missing parent and thr-parent for child item', ['item' => $item]);
1658 if (isset($parent_plink)) {
1660 'ref' => $item['thr-parent'],
1661 'href' => $parent_plink];
1662 XML::addElement($doc, $entry, 'thr:in-reply-to', '', $attributes);
1666 'href' => $parent_plink];
1667 XML::addElement($doc, $entry, 'link', '', $attributes);
1671 if (intval($item['parent']) > 0) {
1672 $conversation_href = $conversation_uri = $item['conversation'];
1674 XML::addElement($doc, $entry, 'link', '', ['rel' => 'ostatus:conversation', 'href' => $conversation_href]);
1677 'href' => $conversation_href,
1678 'local_id' => $item['parent'],
1679 'ref' => $conversation_uri,
1682 XML::addElement($doc, $entry, 'ostatus:conversation', $conversation_uri, $attributes);
1685 // uri-id isn't present for follow entry pseudo-items
1686 $tags = Tag::getByURIId($item['uri-id'] ?? 0);
1687 foreach ($tags as $tag) {
1688 $mentioned[$tag['url']] = $tag['url'];
1691 // Make sure that mentions are accepted (GNU Social has problems with mixing HTTP and HTTPS)
1693 foreach ($mentioned as $mention) {
1694 $newmentions[str_replace('http://', 'https://', $mention)] = str_replace('http://', 'https://', $mention);
1695 $newmentions[str_replace('https://', 'http://', $mention)] = str_replace('https://', 'http://', $mention);
1697 $mentioned = $newmentions;
1699 foreach ($mentioned as $mention) {
1700 $contact = Contact::getByURL($mention, false, ['contact-type']);
1701 if (!empty($contact) && ($contact['contact-type'] == Contact::TYPE_COMMUNITY)) {
1702 XML::addElement($doc, $entry, 'link', '', [
1703 'rel' => 'mentioned',
1704 'ostatus:object-type' => Activity\ObjectType::GROUP,
1708 XML::addElement($doc, $entry, 'link', '', [
1709 'rel' => 'mentioned',
1710 'ostatus:object-type' => Activity\ObjectType::PERSON,
1716 if ($owner['contact-type'] == Contact::TYPE_COMMUNITY) {
1717 XML::addElement($doc, $entry, 'link', '', [
1718 'rel' => 'mentioned',
1719 'ostatus:object-type' => 'http://activitystrea.ms/schema/1.0/group',
1720 'href' => $owner['url']
1724 if ($item['private'] != Item::PRIVATE) {
1725 XML::addElement($doc, $entry, 'link', '', ['rel' => 'ostatus:attention',
1726 'href' => 'http://activityschema.org/collection/public']);
1727 XML::addElement($doc, $entry, 'link', '', ['rel' => 'mentioned',
1728 'ostatus:object-type' => 'http://activitystrea.ms/schema/1.0/collection',
1729 'href' => 'http://activityschema.org/collection/public']);
1730 XML::addElement($doc, $entry, 'mastodon:scope', 'public');
1733 foreach ($tags as $tag) {
1734 if ($tag['type'] == Tag::HASHTAG) {
1735 XML::addElement($doc, $entry, 'category', '', ['term' => $tag['name']]);
1739 self::getAttachment($doc, $entry, $item);
1741 if ($complete && ($item['id'] > 0)) {
1742 $app = $item['app'];
1747 $attributes = ['local_id' => $item['id'], 'source' => $app];
1749 if (isset($parent['id'])) {
1750 $attributes['repeat_of'] = $parent['id'];
1753 if ($item['coord'] != '') {
1754 XML::addElement($doc, $entry, 'georss:point', $item['coord']);
1757 XML::addElement($doc, $entry, 'statusnet:notice_info', '', $attributes);
1762 * Creates the XML feed for a given nickname
1764 * Supported filters:
1765 * - activity (default): all the public posts
1766 * - posts: all the public top-level posts
1767 * - comments: all the public replies
1769 * Updates the provided last_update parameter if the result comes from the
1770 * cache or it is empty
1772 * @param string $owner_nick Nickname of the feed owner
1773 * @param string $last_update Date of the last update (in "Y-m-d H:i:s" format)
1774 * @param integer $max_items Number of maximum items to fetch
1775 * @param string $filter Feed items filter (activity, posts or comments)
1776 * @param boolean $nocache Wether to bypass caching
1777 * @return string XML feed or empty string on error
1778 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1779 * @throws \ImagickException
1781 public static function feed(string $owner_nick, string &$last_update, int $max_items = 300, string $filter = 'activity', bool $nocache = false): string
1783 $stamp = microtime(true);
1785 $owner = User::getOwnerDataByNick($owner_nick);
1790 $cachekey = 'ostatus:feed:' . $owner_nick . ':' . $filter . ':' . $last_update;
1792 $previous_created = $last_update;
1794 // Don't cache when the last item was posted less then 15 minutes ago (Cache duration)
1795 if ((time() - strtotime($owner['last-item'])) < 15*60) {
1796 $result = DI::cache()->get($cachekey);
1797 if (!$nocache && !is_null($result)) {
1798 Logger::info('Feed duration: ' . number_format(microtime(true) - $stamp, 3) . ' - ' . $owner_nick . ' - ' . $filter . ' - ' . $previous_created . ' (cached)');
1799 $last_update = $result['last_update'];
1800 return $result['feed'];
1804 if (!strlen($last_update)) {
1805 $last_update = 'now -30 days';
1808 $check_date = DateTimeFormat::utc($last_update);
1809 $authorid = Contact::getIdForURL($owner['url']);
1812 "`uid` = ? AND `received` > ? AND NOT `deleted` AND `private` != ? AND `visible` AND `wall` AND `parent-network` IN (?, ?)",
1820 if ($filter === 'comments') {
1821 $condition[0] .= " AND `object-type` = ? ";
1822 $condition[] = Activity\ObjectType::COMMENT;
1825 if ($owner['contact-type'] != Contact::TYPE_COMMUNITY) {
1826 $condition[0] .= " AND `contact-id` = ? AND `author-id` = ?";
1827 $condition[] = $owner['id'];
1828 $condition[] = $authorid;
1831 $params = ['order' => ['received' => true], 'limit' => $max_items];
1833 if ($filter === 'posts') {
1834 $ret = Post::selectThread([], $condition, $params);
1836 $ret = Post::select([], $condition, $params);
1839 $items = Post::toArray($ret);
1841 $doc = new DOMDocument('1.0', 'utf-8');
1842 $doc->formatOutput = true;
1844 $root = self::addHeader($doc, $owner, $filter);
1846 foreach ($items as $item) {
1847 if (DI::config()->get('system', 'ostatus_debug')) {
1848 $item['body'] .= '🍼';
1851 if (in_array($item['verb'], [Activity::FOLLOW, Activity::O_UNFOLLOW, Activity::LIKE])) {
1855 $entry = self::entry($doc, $item, $owner, false);
1856 $root->appendChild($entry);
1858 if ($last_update < $item['created']) {
1859 $last_update = $item['created'];
1863 $feeddata = trim($doc->saveXML());
1865 $msg = ['feed' => $feeddata, 'last_update' => $last_update];
1866 DI::cache()->set($cachekey, $msg, Duration::QUARTER_HOUR);
1868 Logger::info('Feed duration: ' . number_format(microtime(true) - $stamp, 3) . ' - ' . $owner_nick . ' - ' . $filter . ' - ' . $previous_created);
1874 * Creates the XML for a salmon message
1876 * @param array $item Data of the item that is to be posted
1877 * @param array $owner Contact data of the poster
1879 * @return string XML for the salmon
1880 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1881 * @throws \ImagickException
1883 public static function salmon(array $item, array $owner): string
1885 $doc = new DOMDocument('1.0', 'utf-8');
1886 $doc->formatOutput = true;
1888 if (DI::config()->get('system', 'ostatus_debug')) {
1889 $item['body'] .= '🐟';
1892 $entry = self::entry($doc, $item, $owner, true);
1894 $doc->appendChild($entry);
1896 return trim($doc->saveXML());
1900 * Checks if the given contact url does support OStatus
1902 * @param string $url profile url
1904 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1905 * @throws \ImagickException
1907 public static function isSupportedByContactUrl(string $url): bool
1909 $probe = Probe::uri($url, Protocol::OSTATUS);
1910 return $probe['network'] == Protocol::OSTATUS;