3 * @copyright Copyright (C) 2010-2023, 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]);
388 // Initial header elements
390 'uid' => $importer['uid'],
391 'network' => Protocol::OSTATUS,
394 'gravity' => Item::GRAVITY_COMMENT,
397 if (!is_object($doc->firstChild) || empty($doc->firstChild->tagName)) {
401 $first_child = $doc->firstChild->tagName;
403 if ($first_child == 'feed') {
404 $entries = $xpath->query('/atom:feed/atom:entry');
406 $entries = $xpath->query('/atom:entry');
409 if ($entries->length == 1) {
410 // We reformat the XML to make it better readable
411 $doc2 = new DOMDocument();
412 $doc2->loadXML($xml);
413 $doc2->preserveWhiteSpace = false;
414 $doc2->formatOutput = true;
415 $xml2 = $doc2->saveXML();
417 $header['protocol'] = Conversation::PARCEL_SALMON;
418 $header['source'] = $xml2;
419 $header['direction'] = $direction;
420 } elseif (!$initialize) {
424 // Fetch the first author
425 $authordata = $xpath->query('//author')->item(0);
426 $author = self::fetchAuthor($xpath, $authordata, $importer, $contact, $stored);
428 // Reverse the order of the entries
431 foreach ($entries as $entry) {
432 $entrylist[] = $entry;
435 foreach (array_reverse($entrylist) as $entry) {
437 $authorelement = $xpath->query('/atom:entry/atom:author', $entry);
439 if ($authorelement->length == 0) {
440 $authorelement = $xpath->query('atom:author', $entry);
443 if ($authorelement->length > 0) {
444 $author = self::fetchAuthor($xpath, $entry, $importer, $contact, $stored);
447 $item = array_merge($header, $author);
449 $item['uri'] = XML::getFirstNodeValue($xpath, 'atom:id/text()', $entry);
450 $item['uri-id'] = ItemURI::insert(['uri' => $item['uri']]);
452 $item['verb'] = XML::getFirstNodeValue($xpath, 'activity:verb/text()', $entry);
455 if (in_array($item['verb'], ['qvitter-delete-notice', Activity::DELETE, 'delete'])) {
456 self::deleteNotice($item);
460 if (in_array($item['verb'], [Activity::O_UNFAVOURITE, Activity::UNFAVORITE])) {
461 // Ignore "Unfavorite" message
462 Logger::info('Ignore unfavorite message ', ['item' => $item]);
466 // Deletions come with the same uri, so we check for duplicates after processing deletions
467 if (Post::exists(['uid' => $importer['uid'], 'uri' => $item['uri']])) {
468 Logger::info('Post with URI ' . $item['uri'] . ' already existed for user ' . $importer['uid'] . '.');
471 Logger::info('Processing post with URI ' . $item['uri'] . ' for user ' . $importer['uid'] . '.');
474 if ($item['verb'] == Activity::JOIN) {
475 // ignore "Join" messages
476 Logger::info('Ignore join message ', ['item' => $item]);
480 if ($item['verb'] == 'http://mastodon.social/schema/1.0/block') {
481 // ignore mastodon "block" messages
482 Logger::info('Ignore block message ', ['item' => $item]);
486 if ($item['verb'] == Activity::FOLLOW) {
487 Contact::addRelationship($importer, $contact, $item);
491 if ($item['verb'] == Activity::O_UNFOLLOW) {
493 Contact::removeFollower($contact);
497 if ($item['verb'] == Activity::FAVORITE) {
498 $orig_uri = $xpath->query('activity:object/atom:id', $entry)->item(0)->nodeValue;
499 Logger::notice('Favorite', ['uri' => $orig_uri, 'item' => $item]);
501 $item['body'] = $item['verb'] = Activity::LIKE;
502 $item['thr-parent'] = $orig_uri;
503 $item['gravity'] = Item::GRAVITY_ACTIVITY;
504 $item['object-type'] = Activity\ObjectType::NOTE;
507 // http://activitystrea.ms/schema/1.0/rsvp-yes
508 if (!in_array($item['verb'], [Activity::POST, Activity::LIKE, Activity::SHARE])) {
509 Logger::info('Unhandled verb', ['verb' => $item['verb'], 'item' => $item]);
512 self::processPost($xpath, $entry, $item, $importer);
514 if ($initialize && (count(self::$itemlist) > 0)) {
515 if (self::$itemlist[0]['uri'] == self::$itemlist[0]['thr-parent']) {
516 $uid = self::$itemlist[0]['uid'];
517 // We will import it everytime, when it is started by our contacts
518 $valid = Contact::isSharingByURL(self::$itemlist[0]['author-link'], $uid);
521 // If not, then it depends on this setting
522 $valid = !$uid || DI::pConfig()->get($uid, 'system', 'accept_only_sharer') != Item::COMPLETION_NONE;
525 Logger::info('Item with URI ' . self::$itemlist[0]['uri'] . ' will be imported due to the system settings.');
528 Logger::info('Item with URI ' . self::$itemlist[0]['uri'] . ' belongs to a contact (' . self::$itemlist[0]['contact-id'] . '). It will be imported.');
531 if ($valid && DI::pConfig()->get($uid, 'system', 'accept_only_sharer') != Item::COMPLETION_LIKE) {
532 // Never post a thread when the only interaction by our contact was a like
534 $verbs = [Activity::POST, Activity::SHARE];
535 foreach (self::$itemlist as $item) {
536 if (in_array($item['verb'], $verbs) && Contact::isSharingByURL($item['author-link'], $item['uid'])) {
541 Logger::info('Item with URI ' . self::$itemlist[0]['uri'] . ' will be imported since the thread contains posts or shares.');
549 $default_contact = 0;
550 for ($key = count(self::$itemlist) - 1; $key >= 0; $key--) {
551 if (empty(self::$itemlist[$key]['contact-id'])) {
552 self::$itemlist[$key]['contact-id'] = $default_contact;
554 $default_contact = $item['contact-id'];
557 foreach (self::$itemlist as $item) {
558 $found = Post::exists(['uid' => $importer['uid'], 'uri' => $item['uri']]);
560 Logger::notice('Item with URI ' . $item['uri'] . ' for user ' . $importer['uid'] . ' already exists.');
561 } elseif ($item['contact-id'] < 0) {
562 Logger::notice('Item with URI ' . $item['uri'] . ' is from a blocked contact.');
564 $ret = Item::insert($item);
565 Logger::info('Item with URI ' . $item['uri'] . ' for user ' . $importer['uid'] . ' stored. Return value: ' . $ret);
569 self::$itemlist = [];
571 Logger::info('Processing done for post with URI ' . $item['uri'] . ' for user '.$importer['uid'] . '.');
577 * Removes notice item from database
579 * @param array $item item
583 private static function deleteNotice(array $item)
585 $condition = ['uid' => $item['uid'], 'author-id' => $item['author-id'], 'uri' => $item['uri']];
586 if (!Post::exists($condition)) {
587 Logger::notice('Item from ' . $item['author-link'] . ' with uri ' . $item['uri'] . ' for user ' . $item['uid'] . " wasn't found. We don't delete it.");
591 Item::markForDeletion($condition);
593 Logger::notice('Deleted item with URI ' . $item['uri'] . ' for user ' . $item['uid']);
597 * Processes the XML for a post
599 * @param DOMXPath $xpath The xpath object
600 * @param object $entry The xml entry that is processed
601 * @param array $item The item array
602 * @param array $importer user record of the importing user
604 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
605 * @throws \ImagickException
607 private static function processPost(DOMXPath $xpath, $entry, array &$item, array $importer)
609 $item['body'] = HTML::toBBCode(XML::getFirstNodeValue($xpath, 'atom:content/text()', $entry));
610 $item['object-type'] = XML::getFirstNodeValue($xpath, 'activity:object-type/text()', $entry);
611 if (($item['object-type'] == Activity\ObjectType::BOOKMARK) || ($item['object-type'] == Activity\ObjectType::EVENT)) {
612 $item['title'] = XML::getFirstNodeValue($xpath, 'atom:title/text()', $entry);
613 $item['body'] = XML::getFirstNodeValue($xpath, 'atom:summary/text()', $entry);
614 } elseif ($item['object-type'] == Activity\ObjectType::QUESTION) {
615 $item['title'] = XML::getFirstNodeValue($xpath, 'atom:title/text()', $entry);
618 $item['created'] = XML::getFirstNodeValue($xpath, 'atom:published/text()', $entry);
619 $item['edited'] = XML::getFirstNodeValue($xpath, 'atom:updated/text()', $entry);
620 $item['conversation'] = XML::getFirstNodeValue($xpath, 'ostatus:conversation/text()', $entry);
622 $conv = $xpath->query('ostatus:conversation', $entry);
623 if (is_object($conv->item(0))) {
624 foreach ($conv->item(0)->attributes as $attributes) {
625 if ($attributes->name == 'ref') {
626 $item['conversation'] = $attributes->textContent;
628 if ($attributes->name == 'href') {
629 $item['conversation'] = $attributes->textContent;
636 $inreplyto = $xpath->query('thr:in-reply-to', $entry);
637 if (is_object($inreplyto->item(0))) {
638 foreach ($inreplyto->item(0)->attributes as $attributes) {
639 if ($attributes->name == 'ref') {
640 $item['thr-parent'] = $attributes->textContent;
642 if ($attributes->name == 'href') {
643 $related = $attributes->textContent;
648 $georsspoint = $xpath->query('georss:point', $entry);
649 if (!empty($georsspoint) && ($georsspoint->length > 0)) {
650 $item['coord'] = $georsspoint->item(0)->nodeValue;
653 $categories = $xpath->query('atom:category', $entry);
655 foreach ($categories as $category) {
656 foreach ($category->attributes as $attributes) {
657 if ($attributes->name == 'term') {
659 Tag::store($item['uri-id'], Tag::HASHTAG, $attributes->textContent);
668 $links = $xpath->query('atom:link', $entry);
670 $link_data = self::processLinks($links, $item);
671 $self = $link_data['self'];
672 $add_body = $link_data['add_body'];
677 $notice_info = $xpath->query('statusnet:notice_info', $entry);
678 if ($notice_info && ($notice_info->length > 0)) {
679 foreach ($notice_info->item(0)->attributes as $attributes) {
680 if ($attributes->name == 'source') {
681 $item['app'] = strip_tags($attributes->textContent);
683 if ($attributes->name == 'repeat_of') {
684 $repeat_of = $attributes->textContent;
688 // Is it a repeated post?
689 if (($repeat_of != '') || ($item['verb'] == Activity::SHARE)) {
690 $link_data = self::processRepeatedItem($xpath, $entry, $item, $importer);
691 if (!empty($link_data['add_body'])) {
692 $add_body .= $link_data['add_body'];
696 $item['body'] .= $add_body;
698 Tag::storeFromBody($item['uri-id'], $item['body']);
700 // Mastodon Content Warning
701 if (($item['verb'] == Activity::POST) && $xpath->evaluate('boolean(atom:summary)', $entry)) {
702 $clear_text = XML::getFirstNodeValue($xpath, 'atom:summary/text()', $entry);
703 if (!empty($clear_text)) {
704 $item['content-warning'] = HTML::toBBCode($clear_text);
708 if (isset($item['thr-parent'])) {
709 if (!Post::exists(['uid' => $importer['uid'], 'uri' => $item['thr-parent']])) {
710 if ($related != '') {
711 self::fetchRelated($related, $item['thr-parent'], $importer);
714 Logger::info('Reply with URI ' . $item['uri'] . ' already existed for user ' . $importer['uid'] . '.');
717 $item['thr-parent'] = $item['uri'];
718 $item['gravity'] = Item::GRAVITY_PARENT;
721 self::$itemlist[] = $item;
725 * Fetch related posts and processes them
727 * @param string $related The link to the related item
728 * @param string $related_uri The related item in "uri" format
729 * @param array $importer user record of the importing user
731 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
732 * @throws \ImagickException
734 private static function fetchRelated(string $related, string $related_uri, array $importer)
737 $curlResult = DI::httpClient()->get($related, HttpClientAccept::ATOM_XML);
739 if (!$curlResult->isSuccess() || empty($curlResult->getBody())) {
745 if ($curlResult->inHeader('Content-Type') &&
746 in_array('application/atom+xml', $curlResult->getHeader('Content-Type'))) {
747 Logger::info('Directly fetched XML for URI ' . $related_uri);
748 $xml = $curlResult->getBody();
752 $doc = new DOMDocument();
753 if (!@$doc->loadHTML($curlResult->getBody())) {
756 $xpath = new DOMXPath($doc);
760 $links = $xpath->query('//link');
762 foreach ($links as $link) {
763 $attribute = self::readAttributes($link);
764 if (($attribute['rel'] == 'alternate') && ($attribute['type'] == 'application/atom+xml')) {
765 $atom_file = $attribute['href'];
768 if ($atom_file != '') {
769 $curlResult = DI::httpClient()->get($atom_file, HttpClientAccept::ATOM_XML);
771 if ($curlResult->isSuccess()) {
772 Logger::info('Fetched XML for URI ' . $related_uri);
773 $xml = $curlResult->getBody();
779 // Workaround for older GNU Social servers
780 if (($xml == '') && strstr($related, '/notice/')) {
781 $curlResult = DI::httpClient()->get(str_replace('/notice/', '/api/statuses/show/', $related) . '.atom', HttpClientAccept::ATOM_XML);
783 if ($curlResult->isSuccess()) {
784 Logger::info('GNU Social workaround to fetch XML for URI ' . $related_uri);
785 $xml = $curlResult->getBody();
789 // Even more worse workaround for GNU Social ;-)
791 $related_guess = self::convertHref($related_uri);
792 $curlResult = DI::httpClient()->get(str_replace('/notice/', '/api/statuses/show/', $related_guess) . '.atom', HttpClientAccept::ATOM_XML);
794 if ($curlResult->isSuccess()) {
795 Logger::info('GNU Social workaround 2 to fetch XML for URI ' . $related_uri);
796 $xml = $curlResult->getBody();
802 self::process($xml, $importer, $contact, $hub, $stored, false, Conversation::PULL);
804 Logger::info('XML could not be fetched for URI: ' . $related_uri . ' - href: ' . $related);
810 * Processes the XML for a repeated post
812 * @param DOMXPath $xpath The xpath object
813 * @param object $entry The xml entry that is processed
814 * @param array $item The item array
815 * @param array $importer user record of the importing user
817 * @return array with data from links
818 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
819 * @throws \ImagickException
821 private static function processRepeatedItem(DOMXPath $xpath, $entry, array &$item, array $importer): array
823 $activityobject = $xpath->query('activity:object', $entry)->item(0);
825 if (!is_object($activityobject)) {
831 $orig_uri = XML::getFirstNodeValue($xpath, 'atom:id/text()', $activityobject);
833 $links = $xpath->query('atom:link', $activityobject);
835 $link_data = self::processLinks($links, $item);
838 $orig_body = XML::getFirstNodeValue($xpath, 'atom:content/text()', $activityobject);
839 $orig_created = XML::getFirstNodeValue($xpath, 'atom:published/text()', $activityobject);
840 $orig_edited = XML::getFirstNodeValue($xpath, 'atom:updated/text()', $activityobject);
842 $orig_author = self::fetchAuthor($xpath, $activityobject, $importer, $dummy, false);
844 $item['author-name'] = $orig_author['author-name'];
845 $item['author-link'] = $orig_author['author-link'];
846 $item['author-id'] = $orig_author['author-id'];
848 $item['body'] = HTML::toBBCode($orig_body);
849 $item['created'] = $orig_created;
850 $item['edited'] = $orig_edited;
852 $item['uri'] = $orig_uri;
854 $item['verb'] = XML::getFirstNodeValue($xpath, 'activity:verb/text()', $activityobject);
856 $item['object-type'] = XML::getFirstNodeValue($xpath, 'activity:object-type/text()', $activityobject);
858 // Mastodon Content Warning
859 if (($item['verb'] == Activity::POST) && $xpath->evaluate('boolean(atom:summary)', $activityobject)) {
860 $clear_text = XML::getFirstNodeValue($xpath, 'atom:summary/text()', $activityobject);
861 if (!empty($clear_text)) {
862 $item['content-warning'] = HTML::toBBCode($clear_text);
866 $inreplyto = $xpath->query('thr:in-reply-to', $activityobject);
867 if (is_object($inreplyto->item(0))) {
868 foreach ($inreplyto->item(0)->attributes as $attributes) {
869 if ($attributes->name == 'ref') {
870 $item['thr-parent'] = $attributes->textContent;
879 * Processes links in the XML
881 * @param object $links The xml data that contain links
882 * @param array $item The item array
883 * @return array with data from the links
885 private static function processLinks($links, array &$item): array
887 $link_data = ['add_body' => '', 'self' => ''];
889 foreach ($links as $link) {
890 $attribute = self::readAttributes($link);
892 if (!empty($attribute['rel']) && !empty($attribute['href'])) {
893 switch ($attribute['rel']) {
895 $item['plink'] = $attribute['href'];
896 if (($item['object-type'] == Activity\ObjectType::QUESTION)
897 || ($item['object-type'] == Activity\ObjectType::EVENT)
899 Post\Media::insert(['uri-id' => $item['uri-id'], 'type' => Post\Media::UNKNOWN,
900 'url' => $attribute['href'], 'mimetype' => $attribute['type'] ?? null,
901 'size' => $attribute['length'] ?? null, 'description' => $attribute['title'] ?? null]);
905 case 'ostatus:conversation':
906 $link_data['conversation'] = $attribute['href'];
907 $item['conversation'] = $link_data['conversation'];
911 $filetype = strtolower(substr($attribute['type'], 0, strpos($attribute['type'], '/')));
912 if ($filetype == 'image') {
913 $link_data['add_body'] .= "\n[img]".$attribute['href'].'[/img]';
915 Post\Media::insert(['uri-id' => $item['uri-id'], 'type' => Post\Media::DOCUMENT,
916 'url' => $attribute['href'], 'mimetype' => $attribute['type'],
917 'size' => $attribute['length'] ?? null, 'description' => $attribute['title'] ?? null]);
922 if ($item['object-type'] != Activity\ObjectType::BOOKMARK) {
923 if (!isset($item['thr-parent'])) {
924 $item['thr-parent'] = $attribute['href'];
926 $link_data['related'] = $attribute['href'];
928 Post\Media::insert(['uri-id' => $item['uri-id'], 'type' => Post\Media::UNKNOWN,
929 'url' => $attribute['href'], 'mimetype' => $attribute['type'] ?? null,
930 'size' => $attribute['length'] ?? null, 'description' => $attribute['title'] ?? null]);
935 if (empty($item['plink'])) {
936 $item['plink'] = $attribute['href'];
938 $link_data['self'] = $attribute['href'];
942 Logger::notice('Unsupported rel=' . $attribute['rel'] . ', href=' . $attribute['href'] . ', object-type=' . $item['object-type']);
950 * Create an url out of an uri
952 * @param string $href URI in the format "parameter1:parameter1:..."
953 * @return string URL in the format http(s)://....
955 private static function convertHref(string $href): string
957 $elements = explode(':', $href);
959 if ((count($elements) <= 2) || ($elements[0] != 'tag')) {
963 $server = explode(',', $elements[1]);
964 $conversation = explode('=', $elements[2]);
966 if ((count($elements) == 4) && ($elements[2] == 'post')) {
967 return 'http://' . $server[0] . '/notice/' . $elements[3];
970 if ((count($conversation) != 2) || ($conversation[1] == '')) {
974 if ($elements[3] == 'objectType=thread') {
975 return 'http://' . $server[0] . '/conversation/' . $conversation[1];
977 return 'http://' . $server[0] . '/notice/' . $conversation[1];
982 * Adds the header elements to the XML document
984 * @param DOMDocument $doc XML document
985 * @param array $owner Contact data of the poster
986 * @param string $filter The related feed filter (activity, posts or comments)
988 * @return DOMElement Header root element
989 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
991 private static function addHeader(DOMDocument $doc, array $owner, string $filter): DOMElement
993 $root = $doc->createElementNS(ActivityNamespace::ATOM1, 'feed');
994 $doc->appendChild($root);
996 $root->setAttribute('xmlns:thr', ActivityNamespace::THREAD);
997 $root->setAttribute('xmlns:georss', ActivityNamespace::GEORSS);
998 $root->setAttribute('xmlns:activity', ActivityNamespace::ACTIVITY);
999 $root->setAttribute('xmlns:media', ActivityNamespace::MEDIA);
1000 $root->setAttribute('xmlns:poco', ActivityNamespace::POCO);
1001 $root->setAttribute('xmlns:ostatus', ActivityNamespace::OSTATUS);
1002 $root->setAttribute('xmlns:statusnet', ActivityNamespace::STATUSNET);
1003 $root->setAttribute('xmlns:mastodon', ActivityNamespace::MASTODON);
1006 $selfUri = '/feed/' . $owner['nick'] . '/';
1009 $title = DI::l10n()->t('%s\'s timeline', $owner['name']);
1010 $selfUri .= $filter;
1014 $title = DI::l10n()->t('%s\'s posts', $owner['name']);
1018 $title = DI::l10n()->t('%s\'s comments', $owner['name']);
1019 $selfUri .= $filter;
1023 $selfUri = '/dfrn_poll/' . $owner['nick'];
1026 'uri' => 'https://friendi.ca',
1027 'version' => App::VERSION . '-' . DB_UPDATE_VERSION,
1029 XML::addElement($doc, $root, 'generator', App::PLATFORM, $attributes);
1030 XML::addElement($doc, $root, 'id', DI::baseUrl() . '/profile/' . $owner['nick']);
1031 XML::addElement($doc, $root, 'title', $title);
1032 XML::addElement($doc, $root, 'subtitle', sprintf("Updates from %s on %s", $owner['name'], DI::config()->get('config', 'sitename')));
1033 XML::addElement($doc, $root, 'logo', User::getAvatarUrl($owner, Proxy::SIZE_SMALL));
1034 XML::addElement($doc, $root, 'updated', DateTimeFormat::utcNow(DateTimeFormat::ATOM));
1036 $author = self::addAuthor($doc, $owner, true);
1037 $root->appendChild($author);
1040 'href' => $owner['url'],
1041 'rel' => 'alternate',
1042 'type' => 'text/html',
1044 XML::addElement($doc, $root, 'link', '', $attributes);
1046 /// @TODO We have to find out what this is
1047 /// $attributes = array("href" => DI::baseUrl()."/sup",
1048 /// "rel" => "http://api.friendfeed.com/2008/03#sup",
1049 /// "type" => "application/json");
1050 /// XML::addElement($doc, $root, "link", "", $attributes);
1052 self::addHubLink($doc, $root, $owner['nick']);
1054 $attributes = ['href' => DI::baseUrl() . '/salmon/' . $owner['nick'], 'rel' => 'salmon'];
1055 XML::addElement($doc, $root, 'link', '', $attributes);
1057 $attributes = ['href' => DI::baseUrl() . '/salmon/' . $owner['nick'], 'rel' => 'http://salmon-protocol.org/ns/salmon-replies'];
1058 XML::addElement($doc, $root, 'link', '', $attributes);
1060 $attributes = ['href' => DI::baseUrl() . '/salmon/' . $owner['nick'], 'rel' => 'http://salmon-protocol.org/ns/salmon-mention'];
1061 XML::addElement($doc, $root, 'link', '', $attributes);
1063 $attributes = ['href' => DI::baseUrl() . $selfUri, 'rel' => 'self', 'type' => 'application/atom+xml'];
1064 XML::addElement($doc, $root, 'link', '', $attributes);
1066 if ($owner['contact-type'] == Contact::TYPE_COMMUNITY) {
1067 $members = DBA::count('contact', [
1068 'uid' => $owner['uid'],
1075 XML::addElement($doc, $root, 'statusnet:group_info', '', ['member_count' => $members]);
1082 * Add the link to the push hubs to the XML document
1084 * @param DOMDocument $doc XML document
1085 * @param DOMElement $root XML root element where the hub links are added
1086 * @param string $nick Nickname
1088 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1090 public static function addHubLink(DOMDocument $doc, DOMElement $root, string $nick)
1092 $h = DI::baseUrl() . '/pubsubhubbub/' . $nick;
1093 XML::addElement($doc, $root, 'link', '', ['href' => $h, 'rel' => 'hub']);
1097 * Adds attachment data to the XML document
1099 * @param DOMDocument $doc XML document
1100 * @param DOMElement $root XML root element where the hub links are added
1101 * @param array $item Data of the item that is to be posted
1103 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1105 public static function getAttachment(DOMDocument $doc, DOMElement $root, array $item)
1107 foreach (Post\Media::getByURIId($item['uri-id'], [Post\Media::AUDIO, Post\Media::IMAGE, Post\Media::VIDEO, Post\Media::DOCUMENT, Post\Media::TORRENT]) as $attachment) {
1108 $attributes = ['rel' => 'enclosure',
1109 'href' => $attachment['url'],
1110 'type' => $attachment['mimetype']];
1112 if (!empty($attachment['size'])) {
1113 $attributes['length'] = intval($attachment['size']);
1115 if (!empty($attachment['description'])) {
1116 $attributes['title'] = $attachment['description'];
1119 XML::addElement($doc, $root, 'link', '', $attributes);
1124 * Adds the author element to the XML document
1126 * @param DOMDocument $doc XML document
1127 * @param array $owner Contact data of the poster
1128 * @param bool $show_profile Whether to show profile
1129 * @return DOMElement Author element
1130 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1132 private static function addAuthor(DOMDocument $doc, array $owner, bool $show_profile = true): DOMElement
1134 $profile = DBA::selectFirst('profile', ['homepage', 'publish'], ['uid' => $owner['uid']]);
1135 $author = $doc->createElement('author');
1136 XML::addElement($doc, $author, 'id', $owner['url']);
1137 if ($owner['contact-type'] == Contact::TYPE_COMMUNITY) {
1138 XML::addElement($doc, $author, 'activity:object-type', Activity\ObjectType::GROUP);
1140 XML::addElement($doc, $author, 'activity:object-type', Activity\ObjectType::PERSON);
1143 XML::addElement($doc, $author, 'uri', $owner['url']);
1144 XML::addElement($doc, $author, 'name', $owner['nick']);
1145 XML::addElement($doc, $author, 'email', $owner['addr']);
1146 if ($show_profile) {
1147 XML::addElement($doc, $author, 'summary', BBCode::convertForUriId($owner['uri-id'], $owner['about'], BBCode::OSTATUS));
1151 'rel' => 'alternate',
1152 'type' => 'text/html',
1153 'href' => $owner['url'],
1155 XML::addElement($doc, $author, 'link', '', $attributes);
1159 'type' => 'image/jpeg', // To-Do?
1160 'media:width' => Proxy::PIXEL_SMALL,
1161 'media:height' => Proxy::PIXEL_SMALL,
1162 'href' => User::getAvatarUrl($owner, Proxy::SIZE_SMALL),
1164 XML::addElement($doc, $author, 'link', '', $attributes);
1166 if (isset($owner['thumb'])) {
1169 'type' => 'image/jpeg', // To-Do?
1170 'media:width' => Proxy::PIXEL_THUMB,
1171 'media:height' => Proxy::PIXEL_THUMB,
1172 'href' => User::getAvatarUrl($owner, Proxy::SIZE_THUMB),
1174 XML::addElement($doc, $author, 'link', '', $attributes);
1177 XML::addElement($doc, $author, 'poco:preferredUsername', $owner['nick']);
1178 XML::addElement($doc, $author, 'poco:displayName', $owner['name']);
1179 if ($show_profile) {
1180 XML::addElement($doc, $author, 'poco:note', BBCode::convertForUriId($owner['uri-id'], $owner['about'], BBCode::OSTATUS));
1182 if (trim($owner['location']) != '') {
1183 $element = $doc->createElement('poco:address');
1184 XML::addElement($doc, $element, 'poco:formatted', $owner['location']);
1185 $author->appendChild($element);
1189 if (DBA::isResult($profile) && !$show_profile) {
1190 if (trim($profile['homepage']) != '') {
1191 $urls = $doc->createElement('poco:urls');
1192 XML::addElement($doc, $urls, 'poco:type', 'homepage');
1193 XML::addElement($doc, $urls, 'poco:value', $profile['homepage']);
1194 XML::addElement($doc, $urls, 'poco:primary', 'true');
1195 $author->appendChild($urls);
1198 XML::addElement($doc, $author, 'followers', '', ['url' => DI::baseUrl() . '/profile/' . $owner['nick'] . '/contacts/followers']);
1199 XML::addElement($doc, $author, 'statusnet:profile_info', '', ['local_id' => $owner['uid']]);
1201 if ($profile['publish']) {
1202 XML::addElement($doc, $author, 'mastodon:scope', 'public');
1210 * @TODO Picture attachments should look like this:
1211 * <a href="https://status.pirati.ca/attachment/572819" title="https://status.pirati.ca/file/heluecht-20151202T222602-rd3u49p.gif"
1212 * class="attachment thumbnail" id="attachment-572819" rel="nofollow external">https://status.pirati.ca/attachment/572819</a>
1216 * Returns the given activity if present - otherwise returns the "post" activity
1218 * @param array $item Data of the item that is to be posted
1219 * @return string activity
1221 public static function constructVerb(array $item): string
1223 if (!empty($item['verb'])) {
1224 return $item['verb'];
1227 return Activity::POST;
1231 * Returns the given object type if present - otherwise returns the "note" object type
1233 * @param array $item Data of the item that is to be posted
1234 * @return string Object type
1236 private static function constructObjecttype(array $item): string
1238 if (!empty($item['object-type']) && in_array($item['object-type'], [Activity\ObjectType::NOTE, Activity\ObjectType::COMMENT])) {
1239 return $item['object-type'];
1242 return Activity\ObjectType::NOTE;
1246 * Adds an entry element to the XML document
1248 * @param DOMDocument $doc XML document
1249 * @param array $item Data of the item that is to be posted
1250 * @param array $owner Contact data of the poster
1251 * @param bool $toplevel optional default false
1253 * @return DOMElement Entry element
1254 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1255 * @throws \ImagickException
1257 private static function entry(DOMDocument $doc, array $item, array $owner, bool $toplevel = false): DOMElement
1259 if ($item['verb'] == Activity::LIKE) {
1260 return self::likeEntry($doc, $item, $owner, $toplevel);
1261 } elseif (in_array($item['verb'], [Activity::FOLLOW, Activity::O_UNFOLLOW])) {
1262 return self::followEntry($doc, $item, $owner, $toplevel);
1264 return self::noteEntry($doc, $item, $owner, $toplevel);
1269 * Adds an entry element with a "like"
1271 * @param DOMDocument $doc XML document
1272 * @param array $item Data of the item that is to be posted
1273 * @param array $owner Contact data of the poster
1274 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1275 * @return DOMElement Entry element with "like"
1276 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1277 * @throws \ImagickException
1279 private static function likeEntry(DOMDocument $doc, array $item, array $owner, bool $toplevel): DOMElement
1281 if (($item['gravity'] != Item::GRAVITY_PARENT) && (Strings::normaliseLink($item['author-link']) != Strings::normaliseLink($owner['url']))) {
1282 Logger::info('OStatus entry is from author ' . $owner['url'] . ' - not from ' . $item['author-link'] . '. Quitting.');
1285 $entry = self::entryHeader($doc, $owner, $item, $toplevel);
1287 $verb = ActivityNamespace::ACTIVITY_SCHEMA . 'favorite';
1288 self::entryContent($doc, $entry, $item, $owner, 'Favorite', $verb, false);
1290 $parent = Post::selectFirst([], ['uri' => $item['thr-parent'], 'uid' => $item['uid']]);
1291 if (DBA::isResult($parent)) {
1292 $as_object = $doc->createElement('activity:object');
1294 XML::addElement($doc, $as_object, 'activity:object-type', self::constructObjecttype($parent));
1296 self::entryContent($doc, $as_object, $parent, $owner, 'New entry');
1298 $entry->appendChild($as_object);
1301 self::entryFooter($doc, $entry, $item, $owner);
1307 * Adds the person object element to the XML document
1309 * @param DOMDocument $doc XML document
1310 * @param array $owner Contact data of the poster
1311 * @param array $contact Contact data of the target
1312 * @return DOMElement author element
1314 private static function addPersonObject(DOMDocument $doc, array $owner, array $contact): DOMElement
1316 $object = $doc->createElement('activity:object');
1317 XML::addElement($doc, $object, 'activity:object-type', Activity\ObjectType::PERSON);
1319 if ($contact['network'] == Protocol::PHANTOM) {
1320 XML::addElement($doc, $object, 'id', $contact['url']);
1324 XML::addElement($doc, $object, 'id', $contact['alias']);
1325 XML::addElement($doc, $object, 'title', $contact['nick']);
1327 XML::addElement($doc, $object, 'link', '', [
1328 'rel' => 'alternate',
1329 'type' => 'text/html',
1330 'href' => $contact['url'],
1335 'type' => 'image/jpeg', // To-Do?
1336 'media:width' => 300,
1337 'media:height' => 300,
1338 'href' => $contact['photo'],
1340 XML::addElement($doc, $object, 'link', '', $attributes);
1342 XML::addElement($doc, $object, 'poco:preferredUsername', $contact['nick']);
1343 XML::addElement($doc, $object, 'poco:displayName', $contact['name']);
1345 if (trim($contact['location']) != '') {
1346 $element = $doc->createElement('poco:address');
1347 XML::addElement($doc, $element, 'poco:formatted', $contact['location']);
1348 $object->appendChild($element);
1355 * Adds a follow/unfollow entry element
1357 * @param DOMDocument $doc XML document
1358 * @param array $item Data of the follow/unfollow message
1359 * @param array $owner Contact data of the poster
1360 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1361 * @return DOMElement Entry element
1362 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1363 * @throws \ImagickException
1365 private static function followEntry(DOMDocument $doc, array $item, array $owner, bool $toplevel): DOMElement
1367 $item['id'] = $item['parent'] = 0;
1368 $item['created'] = $item['edited'] = date('c');
1369 $item['private'] = Item::PRIVATE;
1371 $contact = Contact::getByURL($item['follow']);
1372 $item['follow'] = $contact['url'];
1374 if ($contact['alias']) {
1375 $item['follow'] = $contact['alias'];
1377 $contact['alias'] = $contact['url'];
1380 $condition = ['uid' => $owner['uid'], 'nurl' => Strings::normaliseLink($contact['url'])];
1381 $user_contact = DBA::selectFirst('contact', ['id'], $condition);
1383 if (DBA::isResult($user_contact)) {
1384 $connect_id = $user_contact['id'];
1389 if ($item['verb'] == Activity::FOLLOW) {
1390 $message = DI::l10n()->t('%s is now following %s.');
1391 $title = DI::l10n()->t('following');
1392 $action = 'subscription';
1394 $message = DI::l10n()->t('%s stopped following %s.');
1395 $title = DI::l10n()->t('stopped following');
1396 $action = 'unfollow';
1399 $item['uri'] = $item['parent-uri'] = $item['thr-parent']
1400 = 'tag:' . DI::baseUrl()->getHost() .
1401 ','.date('Y-m-d').':'.$action.':'.$owner['uid'].
1402 ':person:'.$connect_id.':'.$item['created'];
1404 $item['body'] = sprintf($message, $owner['nick'], $contact['nick']);
1406 $entry = self::entryHeader($doc, $owner, $item, $toplevel);
1408 self::entryContent($doc, $entry, $item, $owner, $title);
1410 $object = self::addPersonObject($doc, $owner, $contact);
1411 $entry->appendChild($object);
1413 self::entryFooter($doc, $entry, $item, $owner);
1419 * Adds a regular entry element
1421 * @param DOMDocument $doc XML document
1422 * @param array $item Data of the item that is to be posted
1423 * @param array $owner Contact data of the poster
1424 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1425 * @return DOMElement Entry element
1426 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1427 * @throws \ImagickException
1429 private static function noteEntry(DOMDocument $doc, array $item, array $owner, bool $toplevel): DOMElement
1431 if (($item['gravity'] != Item::GRAVITY_PARENT) && (Strings::normaliseLink($item['author-link']) != Strings::normaliseLink($owner['url']))) {
1432 Logger::info('OStatus entry is from author ' . $owner['url'] . ' - not from ' . $item['author-link'] . '. Quitting.');
1436 if (!empty($item['title'])) {
1437 $title = BBCode::convertForUriId($item['uri-id'], $item['title'], BBCode::OSTATUS);
1439 $title = sprintf('New note by %s', $owner['nick']);
1442 $title = sprintf('New comment by %s', $owner['nick']);
1445 $entry = self::entryHeader($doc, $owner, $item, $toplevel);
1447 XML::addElement($doc, $entry, 'activity:object-type', Activity\ObjectType::NOTE);
1449 self::entryContent($doc, $entry, $item, $owner, $title, '', true);
1451 self::entryFooter($doc, $entry, $item, $owner, true);
1457 * Adds a header element to the XML document
1459 * @param DOMDocument $doc XML document
1460 * @param array $owner Contact data of the poster
1461 * @param array $item
1462 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1463 * @return DOMElement The entry element where the elements are added
1464 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1465 * @throws \ImagickException
1467 public static function entryHeader(DOMDocument $doc, array $owner, array $item, bool $toplevel): DOMElement
1470 $entry = $doc->createElement('entry');
1472 if ($owner['contact-type'] == Contact::TYPE_COMMUNITY) {
1473 $entry->setAttribute('xmlns:activity', ActivityNamespace::ACTIVITY);
1475 $contact = Contact::getByURL($item['author-link']) ?: $owner;
1476 $contact['nickname'] = $contact['nickname'] ?? $contact['nick'];
1477 $author = self::addAuthor($doc, $contact, false);
1478 $entry->appendChild($author);
1481 $entry = $doc->createElementNS(ActivityNamespace::ATOM1, 'entry');
1483 $entry->setAttribute('xmlns:thr', ActivityNamespace::THREAD);
1484 $entry->setAttribute('xmlns:georss', ActivityNamespace::GEORSS);
1485 $entry->setAttribute('xmlns:activity', ActivityNamespace::ACTIVITY);
1486 $entry->setAttribute('xmlns:media', ActivityNamespace::MEDIA);
1487 $entry->setAttribute('xmlns:poco', ActivityNamespace::POCO);
1488 $entry->setAttribute('xmlns:ostatus', ActivityNamespace::OSTATUS);
1489 $entry->setAttribute('xmlns:statusnet', ActivityNamespace::STATUSNET);
1490 $entry->setAttribute('xmlns:mastodon', ActivityNamespace::MASTODON);
1492 $author = self::addAuthor($doc, $owner);
1493 $entry->appendChild($author);
1500 * Adds elements to the XML document
1502 * @param DOMDocument $doc XML document
1503 * @param DOMElement $entry Entry element where the content is added
1504 * @param array $item Data of the item that is to be posted
1505 * @param array $owner Contact data of the poster
1506 * @param string $title Title for the post
1507 * @param string $verb The activity verb
1508 * @param bool $complete Add the "status_net" element?
1510 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1512 private static function entryContent(DOMDocument $doc, DOMElement $entry, array $item, array $owner, string $title, string $verb = '', bool $complete = true)
1515 $verb = self::constructVerb($item);
1518 XML::addElement($doc, $entry, 'id', $item['uri']);
1519 XML::addElement($doc, $entry, 'title', html_entity_decode($title, ENT_QUOTES, 'UTF-8'));
1521 $body = Post\Media::addAttachmentsToBody($item['uri-id'], DI::contentItem()->addSharedPost($item));
1522 $body = Post\Media::addHTMLLinkToBody($item['uri-id'], $body);
1524 if (!empty($item['title'])) {
1525 $body = '[b]' . $item['title'] . "[/b]\n\n" . $body;
1528 $body = BBCode::convertForUriId($item['uri-id'], $body, BBCode::OSTATUS);
1530 XML::addElement($doc, $entry, 'content', $body, ['type' => 'html']);
1532 XML::addElement($doc, $entry, 'link', '', [
1533 'rel' => 'alternate',
1534 'type' => 'text/html',
1535 'href' => DI::baseUrl() . '/display/' . $item['guid'],
1538 if ($complete && ($item['id'] > 0)) {
1539 XML::addElement($doc, $entry, 'status_net', '', ['notice_id' => $item['id']]);
1542 XML::addElement($doc, $entry, 'activity:verb', $verb);
1544 XML::addElement($doc, $entry, 'published', DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM));
1545 XML::addElement($doc, $entry, 'updated', DateTimeFormat::utc($item['edited'] . '+00:00', DateTimeFormat::ATOM));
1549 * Adds the elements at the foot of an entry to the XML document
1551 * @param DOMDocument $doc XML document
1552 * @param object $entry The entry element where the elements are added
1553 * @param array $item Data of the item that is to be posted
1554 * @param array $owner Contact data of the poster
1555 * @param bool $complete default true
1557 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1559 private static function entryFooter(DOMDocument $doc, $entry, array $item, array $owner, bool $complete = true)
1563 if ($item['gravity'] != Item::GRAVITY_PARENT) {
1564 $parent = Post::selectFirst(['guid', 'author-link', 'owner-link'], ['id' => $item['parent']]);
1566 $thrparent = Post::selectFirst(['guid', 'author-link', 'owner-link', 'plink'], ['uid' => $owner['uid'], 'uri' => $item['thr-parent']]);
1568 if (DBA::isResult($thrparent)) {
1569 $mentioned[$thrparent['author-link']] = $thrparent['author-link'];
1570 $mentioned[$thrparent['owner-link']] = $thrparent['owner-link'];
1571 $parent_plink = $thrparent['plink'];
1572 } elseif (DBA::isResult($parent)) {
1573 $mentioned[$parent['author-link']] = $parent['author-link'];
1574 $mentioned[$parent['owner-link']] = $parent['owner-link'];
1575 $parent_plink = DI::baseUrl() . '/display/' . $parent['guid'];
1577 DI::logger()->notice('Missing parent and thr-parent for child item', ['item' => $item]);
1580 if (isset($parent_plink)) {
1582 'ref' => $item['thr-parent'],
1583 'href' => $parent_plink];
1584 XML::addElement($doc, $entry, 'thr:in-reply-to', '', $attributes);
1588 'href' => $parent_plink];
1589 XML::addElement($doc, $entry, 'link', '', $attributes);
1593 if (intval($item['parent']) > 0) {
1594 $conversation_href = $conversation_uri = $item['conversation'];
1596 XML::addElement($doc, $entry, 'link', '', ['rel' => 'ostatus:conversation', 'href' => $conversation_href]);
1599 'href' => $conversation_href,
1600 'local_id' => $item['parent'],
1601 'ref' => $conversation_uri,
1604 XML::addElement($doc, $entry, 'ostatus:conversation', $conversation_uri, $attributes);
1607 // uri-id isn't present for follow entry pseudo-items
1608 $tags = Tag::getByURIId($item['uri-id'] ?? 0);
1609 foreach ($tags as $tag) {
1610 $mentioned[$tag['url']] = $tag['url'];
1613 // Make sure that mentions are accepted (GNU Social has problems with mixing HTTP and HTTPS)
1615 foreach ($mentioned as $mention) {
1616 $newmentions[str_replace('http://', 'https://', $mention)] = str_replace('http://', 'https://', $mention);
1617 $newmentions[str_replace('https://', 'http://', $mention)] = str_replace('https://', 'http://', $mention);
1619 $mentioned = $newmentions;
1621 foreach ($mentioned as $mention) {
1622 $contact = Contact::getByURL($mention, false, ['contact-type']);
1623 if (!empty($contact) && ($contact['contact-type'] == Contact::TYPE_COMMUNITY)) {
1624 XML::addElement($doc, $entry, 'link', '', [
1625 'rel' => 'mentioned',
1626 'ostatus:object-type' => Activity\ObjectType::GROUP,
1630 XML::addElement($doc, $entry, 'link', '', [
1631 'rel' => 'mentioned',
1632 'ostatus:object-type' => Activity\ObjectType::PERSON,
1638 if ($owner['contact-type'] == Contact::TYPE_COMMUNITY) {
1639 XML::addElement($doc, $entry, 'link', '', [
1640 'rel' => 'mentioned',
1641 'ostatus:object-type' => 'http://activitystrea.ms/schema/1.0/group',
1642 'href' => $owner['url']
1646 if ($item['private'] != Item::PRIVATE) {
1647 XML::addElement($doc, $entry, 'link', '', ['rel' => 'ostatus:attention',
1648 'href' => 'http://activityschema.org/collection/public']);
1649 XML::addElement($doc, $entry, 'link', '', ['rel' => 'mentioned',
1650 'ostatus:object-type' => 'http://activitystrea.ms/schema/1.0/collection',
1651 'href' => 'http://activityschema.org/collection/public']);
1652 XML::addElement($doc, $entry, 'mastodon:scope', 'public');
1655 foreach ($tags as $tag) {
1656 if ($tag['type'] == Tag::HASHTAG) {
1657 XML::addElement($doc, $entry, 'category', '', ['term' => $tag['name']]);
1661 self::getAttachment($doc, $entry, $item);
1663 if ($complete && ($item['id'] > 0)) {
1664 $app = $item['app'];
1669 $attributes = ['local_id' => $item['id'], 'source' => $app];
1671 if (isset($parent['id'])) {
1672 $attributes['repeat_of'] = $parent['id'];
1675 if ($item['coord'] != '') {
1676 XML::addElement($doc, $entry, 'georss:point', $item['coord']);
1679 XML::addElement($doc, $entry, 'statusnet:notice_info', '', $attributes);
1684 * Creates the XML feed for a given nickname
1686 * Supported filters:
1687 * - activity (default): all the public posts
1688 * - posts: all the public top-level posts
1689 * - comments: all the public replies
1691 * Updates the provided last_update parameter if the result comes from the
1692 * cache or it is empty
1694 * @param string $owner_nick Nickname of the feed owner
1695 * @param string $last_update Date of the last update (in "Y-m-d H:i:s" format)
1696 * @param integer $max_items Number of maximum items to fetch
1697 * @param string $filter Feed items filter (activity, posts or comments)
1698 * @param boolean $nocache Wether to bypass caching
1699 * @return string XML feed or empty string on error
1700 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1701 * @throws \ImagickException
1703 public static function feed(string $owner_nick, string &$last_update, int $max_items = 300, string $filter = 'activity', bool $nocache = false): string
1705 $stamp = microtime(true);
1707 $owner = User::getOwnerDataByNick($owner_nick);
1712 $cachekey = 'ostatus:feed:' . $owner_nick . ':' . $filter . ':' . $last_update;
1714 $previous_created = $last_update;
1716 // Don't cache when the last item was posted less than 15 minutes ago (Cache duration)
1717 if ((time() - strtotime($owner['last-item'])) < 15*60) {
1718 $result = DI::cache()->get($cachekey);
1719 if (!$nocache && !is_null($result)) {
1720 Logger::info('Feed duration: ' . number_format(microtime(true) - $stamp, 3) . ' - ' . $owner_nick . ' - ' . $filter . ' - ' . $previous_created . ' (cached)');
1721 $last_update = $result['last_update'];
1722 return $result['feed'];
1726 if (!strlen($last_update)) {
1727 $last_update = 'now -30 days';
1730 $check_date = DateTimeFormat::utc($last_update);
1731 $authorid = Contact::getIdForURL($owner['url']);
1734 "`uid` = ? AND `received` > ? AND NOT `deleted` AND `private` != ? AND `visible` AND `wall` AND `parent-network` IN (?, ?)",
1742 if ($filter === 'comments') {
1743 $condition[0] .= " AND `object-type` = ? ";
1744 $condition[] = Activity\ObjectType::COMMENT;
1747 if ($owner['contact-type'] != Contact::TYPE_COMMUNITY) {
1748 $condition[0] .= " AND `contact-id` = ? AND `author-id` = ?";
1749 $condition[] = $owner['id'];
1750 $condition[] = $authorid;
1753 $params = ['order' => ['received' => true], 'limit' => $max_items];
1755 if ($filter === 'posts') {
1756 $ret = Post::selectThread([], $condition, $params);
1758 $ret = Post::select([], $condition, $params);
1761 $items = Post::toArray($ret);
1763 $doc = new DOMDocument('1.0', 'utf-8');
1764 $doc->formatOutput = true;
1766 $root = self::addHeader($doc, $owner, $filter);
1768 foreach ($items as $item) {
1769 if (DI::config()->get('system', 'ostatus_debug')) {
1770 $item['body'] .= '🍼';
1773 if (in_array($item['verb'], [Activity::FOLLOW, Activity::O_UNFOLLOW, Activity::LIKE])) {
1777 $entry = self::entry($doc, $item, $owner, false);
1778 $root->appendChild($entry);
1780 if ($last_update < $item['created']) {
1781 $last_update = $item['created'];
1785 $feeddata = trim($doc->saveXML());
1787 $msg = ['feed' => $feeddata, 'last_update' => $last_update];
1788 DI::cache()->set($cachekey, $msg, Duration::QUARTER_HOUR);
1790 Logger::info('Feed duration: ' . number_format(microtime(true) - $stamp, 3) . ' - ' . $owner_nick . ' - ' . $filter . ' - ' . $previous_created);
1796 * Creates the XML for a salmon message
1798 * @param array $item Data of the item that is to be posted
1799 * @param array $owner Contact data of the poster
1801 * @return string XML for the salmon
1802 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1803 * @throws \ImagickException
1805 public static function salmon(array $item, array $owner): string
1807 $doc = new DOMDocument('1.0', 'utf-8');
1808 $doc->formatOutput = true;
1810 if (DI::config()->get('system', 'ostatus_debug')) {
1811 $item['body'] .= '🐟';
1814 $entry = self::entry($doc, $item, $owner, true);
1816 $doc->appendChild($entry);
1818 return trim($doc->saveXML());
1822 * Checks if the given contact url does support OStatus
1824 * @param string $url profile url
1826 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1827 * @throws \ImagickException
1829 public static function isSupportedByContactUrl(string $url): bool
1831 $probe = Probe::uri($url, Protocol::OSTATUS);
1832 return $probe['network'] == Protocol::OSTATUS;