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;
26 use Friendica\Content\Text\BBCode;
27 use Friendica\Content\Text\HTML;
28 use Friendica\Core\Cache\Enum\Duration;
29 use Friendica\Core\Logger;
30 use Friendica\Core\Protocol;
31 use Friendica\Database\DBA;
33 use Friendica\Model\APContact;
34 use Friendica\Model\Contact;
35 use Friendica\Model\Conversation;
36 use Friendica\Model\Item;
37 use Friendica\Model\ItemURI;
38 use Friendica\Model\Post;
39 use Friendica\Model\Tag;
40 use Friendica\Model\User;
41 use Friendica\Network\HTTPClient\Client\HttpClientAccept;
42 use Friendica\Network\HTTPClient\Client\HttpClientOptions;
43 use Friendica\Network\Probe;
44 use Friendica\Util\DateTimeFormat;
45 use Friendica\Util\Images;
46 use Friendica\Util\Proxy;
47 use Friendica\Util\Strings;
48 use Friendica\Util\XML;
51 * This class contain functions for the OStatus protocol
55 private static $itemlist;
56 private static $conv_list = [];
61 * @param DOMXPath $xpath The xpath object
62 * @param object $context The xml context of the author details
63 * @param array $importer user record of the importing user
64 * @param array $contact Called by reference, will contain the fetched contact
65 * @param bool $onlyfetch Only fetch the header without updating the contact entries
67 * @return array Array of author related entries for the item
68 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
69 * @throws \ImagickException
71 private static function fetchAuthor(DOMXPath $xpath, $context, array $importer, array &$contact = null, $onlyfetch)
74 $author["author-link"] = XML::getFirstNodeValue($xpath, 'atom:author/atom:uri/text()', $context);
75 $author["author-name"] = XML::getFirstNodeValue($xpath, 'atom:author/atom:name/text()', $context);
76 $addr = XML::getFirstNodeValue($xpath, 'atom:author/atom:email/text()', $context);
78 $aliaslink = $author["author-link"];
80 $alternate_item = $xpath->query("atom:author/atom:link[@rel='alternate']", $context)->item(0);
81 if (is_object($alternate_item)) {
82 foreach ($alternate_item->attributes as $attributes) {
83 if (($attributes->name == "href") && ($attributes->textContent != "")) {
84 $author["author-link"] = $attributes->textContent;
88 $author["author-id"] = Contact::getIdForURL($author["author-link"]);
90 $author['contact-id'] = ($contact['id'] ?? 0) ?: $author['author-id'];
95 This here would be better, but we would get problems with contacts from the statusnet addon
96 This is kept here as a reminder for the future
98 $cid = Contact::getIdForURL($author["author-link"], $importer["uid"]);
100 $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
103 if ($aliaslink != '') {
104 $condition = ["`uid` = ? AND `alias` = ? AND `network` != ? AND `rel` IN (?, ?)",
105 $importer["uid"], $aliaslink, Protocol::STATUSNET,
106 Contact::SHARING, Contact::FRIEND];
107 $contact = DBA::selectFirst('contact', [], $condition);
110 if (!DBA::isResult($contact) && $author["author-link"] != '') {
111 if ($aliaslink == "") {
112 $aliaslink = $author["author-link"];
115 $condition = ["`uid` = ? AND `nurl` IN (?, ?) AND `network` != ? AND `rel` IN (?, ?)",
116 $importer["uid"], Strings::normaliseLink($author["author-link"]), Strings::normaliseLink($aliaslink),
117 Protocol::STATUSNET, Contact::SHARING, Contact::FRIEND];
118 $contact = DBA::selectFirst('contact', [], $condition);
121 if (!DBA::isResult($contact) && ($addr != '')) {
122 $condition = ["`uid` = ? AND `addr` = ? AND `network` != ? AND `rel` IN (?, ?)",
123 $importer["uid"], $addr, Protocol::STATUSNET,
124 Contact::SHARING, Contact::FRIEND];
125 $contact = DBA::selectFirst('contact', [], $condition);
128 if (DBA::isResult($contact)) {
129 if ($contact['blocked']) {
131 } elseif (!empty(APContact::getByURL($contact['url'], false))) {
132 ActivityPub\Receiver::switchContact($contact['id'], $importer['uid'], $contact['url']);
134 $author["contact-id"] = $contact["id"];
138 $avatars = $xpath->query("atom:author/atom:link[@rel='avatar']", $context);
139 foreach ($avatars as $avatar) {
142 foreach ($avatar->attributes as $attributes) {
143 if ($attributes->name == "href") {
144 $href = $attributes->textContent;
146 if ($attributes->name == "width") {
147 $width = $attributes->textContent;
151 $avatarlist[$width] = $href;
154 if (count($avatarlist) > 0) {
156 $author["author-avatar"] = Probe::fixAvatar(current($avatarlist), $author["author-link"]);
159 $displayname = XML::getFirstNodeValue($xpath, 'atom:author/poco:displayName/text()', $context);
160 if ($displayname != "") {
161 $author["author-name"] = $displayname;
164 $author["owner-id"] = $author["author-id"];
166 // Only update the contacts if it is an OStatus contact
167 if (DBA::isResult($contact) && ($contact['id'] > 0) && !$onlyfetch && ($contact["network"] == Protocol::OSTATUS)) {
169 // Update contact data
171 unset($current['name-date']);
173 // This query doesn't seem to work
174 // $value = $xpath->query("atom:link[@rel='salmon']", $context)->item(0)->nodeValue;
176 // $contact["notify"] = $value;
178 // This query doesn't seem to work as well - I hate these queries
179 // $value = $xpath->query("atom:link[@rel='self' and @type='application/atom+xml']", $context)->item(0)->nodeValue;
181 // $contact["poll"] = $value;
183 $contact['url'] = $author["author-link"];
184 $contact['nurl'] = Strings::normaliseLink($contact['url']);
186 $value = XML::getFirstNodeValue($xpath, 'atom:author/atom:uri/text()', $context);
188 $contact["alias"] = $value;
191 $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:displayName/text()', $context);
193 $contact["name"] = $value;
196 $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:preferredUsername/text()', $context);
198 $contact["nick"] = $value;
201 $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:note/text()', $context);
203 $contact["about"] = HTML::toBBCode($value);
206 $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:address/poco:formatted/text()', $context);
208 $contact["location"] = $value;
211 $contact['name-date'] = DateTimeFormat::utcNow();
213 Contact::update($contact, ['id' => $contact["id"]], $current);
215 if (!empty($author["author-avatar"]) && ($author["author-avatar"] != $current['avatar'])) {
216 Logger::info("Update profile picture for contact ".$contact["id"]);
217 Contact::updateAvatar($contact["id"], $author["author-avatar"]);
220 // Ensure that we are having this contact (with uid=0)
221 $cid = Contact::getIdForURL($aliaslink);
224 $fields = ['url', 'nurl', 'name', 'nick', 'alias', 'about', 'location'];
225 $old_contact = DBA::selectFirst('contact', $fields, ['id' => $cid]);
227 // Update it with the current values
228 $fields = ['url' => $author["author-link"], 'name' => $contact["name"],
229 'nurl' => Strings::normaliseLink($author["author-link"]),
230 'nick' => $contact["nick"], 'alias' => $contact["alias"],
231 'about' => $contact["about"], 'location' => $contact["location"],
232 'success_update' => DateTimeFormat::utcNow(), 'last-update' => DateTimeFormat::utcNow()];
234 Contact::update($fields, ['id' => $cid], $old_contact);
237 if (!empty($author["author-avatar"])) {
238 Contact::updateAvatar($cid, $author["author-avatar"]);
241 } elseif (empty($contact["network"]) || ($contact["network"] != Protocol::DFRN)) {
249 * Fetches author data from a given XML string
251 * @param string $xml The XML
252 * @param array $importer user record of the importing user
254 * @return array Array of author related entries for the item
255 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
256 * @throws \ImagickException
258 public static function salmonAuthor($xml, array $importer)
264 $doc = new DOMDocument();
265 @$doc->loadXML($xml);
267 $xpath = new DOMXPath($doc);
268 $xpath->registerNamespace('atom', ActivityNamespace::ATOM1);
269 $xpath->registerNamespace('thr', ActivityNamespace::THREAD);
270 $xpath->registerNamespace('georss', ActivityNamespace::GEORSS);
271 $xpath->registerNamespace('activity', ActivityNamespace::ACTIVITY);
272 $xpath->registerNamespace('media', ActivityNamespace::MEDIA);
273 $xpath->registerNamespace('poco', ActivityNamespace::POCO);
274 $xpath->registerNamespace('ostatus', ActivityNamespace::OSTATUS);
275 $xpath->registerNamespace('statusnet', ActivityNamespace::STATUSNET);
277 $contact = ["id" => 0];
279 // Fetch the first author
280 $authordata = $xpath->query('//author')->item(0);
281 $author = self::fetchAuthor($xpath, $authordata, $importer, $contact, true);
286 * Read attributes from element
288 * @param object $element Element object
290 * @return array attributes
292 private static function readAttributes($element)
296 foreach ($element->attributes as $attributes) {
297 $attribute[$attributes->name] = $attributes->textContent;
304 * Imports an XML string containing OStatus elements
306 * @param string $xml The XML
307 * @param array $importer user record of the importing user
308 * @param array $contact contact
309 * @param string $hub Called by reference, returns the fetched hub data
311 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
312 * @throws \ImagickException
314 public static function import($xml, array $importer, array &$contact, &$hub)
316 self::process($xml, $importer, $contact, $hub, false, true, Conversation::PUSH);
320 * Internal feed processing
322 * @param string $xml The XML
323 * @param array $importer user record of the importing user
324 * @param array $contact contact
325 * @param string $hub Called by reference, returns the fetched hub data
326 * @param boolean $stored Is the post fresh imported or from the database?
327 * @param boolean $initialize Is it the leading post so that data has to be initialized?
329 * @return boolean Could the XML be processed?
330 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
331 * @throws \ImagickException
333 private static function process($xml, array $importer, array &$contact = null, &$hub, $stored = false, $initialize = true, $direction = Conversation::UNKNOWN)
336 self::$itemlist = [];
337 self::$conv_list = [];
340 Logger::info('Import OStatus message for user ' . $importer['uid']);
345 $doc = new DOMDocument();
346 @$doc->loadXML($xml);
348 $xpath = new DOMXPath($doc);
349 $xpath->registerNamespace('atom', ActivityNamespace::ATOM1);
350 $xpath->registerNamespace('thr', ActivityNamespace::THREAD);
351 $xpath->registerNamespace('georss', ActivityNamespace::GEORSS);
352 $xpath->registerNamespace('activity', ActivityNamespace::ACTIVITY);
353 $xpath->registerNamespace('media', ActivityNamespace::MEDIA);
354 $xpath->registerNamespace('poco', ActivityNamespace::POCO);
355 $xpath->registerNamespace('ostatus', ActivityNamespace::OSTATUS);
356 $xpath->registerNamespace('statusnet', ActivityNamespace::STATUSNET);
359 $hub_items = $xpath->query("/atom:feed/atom:link[@rel='hub']")->item(0);
360 if (is_object($hub_items)) {
361 $hub_attributes = $hub_items->attributes;
362 if (is_object($hub_attributes)) {
363 foreach ($hub_attributes as $hub_attribute) {
364 if ($hub_attribute->name == "href") {
365 $hub = $hub_attribute->textContent;
366 Logger::info("Found hub ".$hub);
373 $header["uid"] = $importer["uid"];
374 $header["network"] = Protocol::OSTATUS;
376 $header["origin"] = 0;
377 $header["gravity"] = GRAVITY_COMMENT;
379 if (!is_object($doc->firstChild) || empty($doc->firstChild->tagName)) {
383 $first_child = $doc->firstChild->tagName;
385 if ($first_child == "feed") {
386 $entries = $xpath->query('/atom:feed/atom:entry');
388 $entries = $xpath->query('/atom:entry');
391 if ($entries->length == 1) {
392 // We reformat the XML to make it better readable
393 $doc2 = new DOMDocument();
394 $doc2->loadXML($xml);
395 $doc2->preserveWhiteSpace = false;
396 $doc2->formatOutput = true;
397 $xml2 = $doc2->saveXML();
399 $header["protocol"] = Conversation::PARCEL_SALMON;
400 $header["source"] = $xml2;
401 $header["direction"] = $direction;
402 } elseif (!$initialize) {
406 // Fetch the first author
407 $authordata = $xpath->query('//author')->item(0);
408 $author = self::fetchAuthor($xpath, $authordata, $importer, $contact, $stored);
410 // Reverse the order of the entries
413 foreach ($entries as $entry) {
414 $entrylist[] = $entry;
417 foreach (array_reverse($entrylist) as $entry) {
419 $authorelement = $xpath->query('/atom:entry/atom:author', $entry);
421 if ($authorelement->length == 0) {
422 $authorelement = $xpath->query('atom:author', $entry);
425 if ($authorelement->length > 0) {
426 $author = self::fetchAuthor($xpath, $entry, $importer, $contact, $stored);
429 $item = array_merge($header, $author);
431 $item["uri"] = XML::getFirstNodeValue($xpath, 'atom:id/text()', $entry);
432 $item['uri-id'] = ItemURI::insert(['uri' => $item['uri']]);
434 $item["verb"] = XML::getFirstNodeValue($xpath, 'activity:verb/text()', $entry);
437 if (in_array($item["verb"], ['qvitter-delete-notice', Activity::DELETE, 'delete'])) {
438 self::deleteNotice($item);
442 if (in_array($item["verb"], [Activity::O_UNFAVOURITE, Activity::UNFAVORITE])) {
443 // Ignore "Unfavorite" message
444 Logger::info("Ignore unfavorite message ", ['item' => $item]);
448 // Deletions come with the same uri, so we check for duplicates after processing deletions
449 if (Post::exists(['uid' => $importer["uid"], 'uri' => $item["uri"]])) {
450 Logger::info('Post with URI '.$item["uri"].' already existed for user '.$importer["uid"].'.');
453 Logger::info('Processing post with URI '.$item["uri"].' for user '.$importer["uid"].'.');
456 if ($item["verb"] == Activity::JOIN) {
457 // ignore "Join" messages
458 Logger::info("Ignore join message ", ['item' => $item]);
462 if ($item["verb"] == "http://mastodon.social/schema/1.0/block") {
463 // ignore mastodon "block" messages
464 Logger::info("Ignore block message ", ['item' => $item]);
468 if ($item["verb"] == Activity::FOLLOW) {
469 Contact::addRelationship($importer, $contact, $item);
473 if ($item["verb"] == Activity::O_UNFOLLOW) {
475 Contact::removeFollower($contact);
479 if ($item["verb"] == Activity::FAVORITE) {
480 $orig_uri = $xpath->query("activity:object/atom:id", $entry)->item(0)->nodeValue;
481 Logger::notice("Favorite", ['uri' => $orig_uri, 'item' => $item]);
483 $item["verb"] = Activity::LIKE;
484 $item["thr-parent"] = $orig_uri;
485 $item["gravity"] = GRAVITY_ACTIVITY;
486 $item["object-type"] = Activity\ObjectType::NOTE;
489 // http://activitystrea.ms/schema/1.0/rsvp-yes
490 if (!in_array($item["verb"], [Activity::POST, Activity::LIKE, Activity::SHARE])) {
491 Logger::info("Unhandled verb", ['verb' => $item["verb"], 'item' => $item]);
494 self::processPost($xpath, $entry, $item, $importer);
496 if ($initialize && (count(self::$itemlist) > 0)) {
497 if (self::$itemlist[0]['uri'] == self::$itemlist[0]['thr-parent']) {
498 $uid = self::$itemlist[0]['uid'];
499 // We will import it everytime, when it is started by our contacts
500 $valid = Contact::isSharingByURL(self::$itemlist[0]['author-link'], $uid);
503 // If not, then it depends on this setting
504 $valid = !$uid || DI::pConfig()->get($uid, 'system', 'accept_only_sharer') != Item::COMPLETION_NONE;
507 Logger::info("Item with uri ".self::$itemlist[0]['uri']." will be imported due to the system settings.");
510 Logger::info("Item with uri ".self::$itemlist[0]['uri']." belongs to a contact (".self::$itemlist[0]['contact-id']."). It will be imported.");
513 if ($valid && DI::pConfig()->get($uid, 'system', 'accept_only_sharer') != Item::COMPLETION_LIKE) {
514 // Never post a thread when the only interaction by our contact was a like
516 $verbs = [Activity::POST, Activity::SHARE];
517 foreach (self::$itemlist as $item) {
518 if (in_array($item['verb'], $verbs) && Contact::isSharingByURL($item['author-link'], $item['uid'])) {
523 Logger::info("Item with uri ".self::$itemlist[0]['uri']." will be imported since the thread contains posts or shares.");
531 $default_contact = 0;
532 for ($key = count(self::$itemlist) - 1; $key >= 0; $key--) {
533 if (empty(self::$itemlist[$key]['contact-id'])) {
534 self::$itemlist[$key]['contact-id'] = $default_contact;
536 $default_contact = $item['contact-id'];
539 foreach (self::$itemlist as $item) {
540 $found = Post::exists(['uid' => $importer["uid"], 'uri' => $item["uri"]]);
542 Logger::notice("Item with uri ".$item["uri"]." for user ".$importer["uid"]." already exists.");
543 } elseif ($item['contact-id'] < 0) {
544 Logger::notice("Item with uri ".$item["uri"]." is from a blocked contact.");
546 $ret = Item::insert($item);
547 Logger::info("Item with uri ".$item["uri"]." for user ".$importer["uid"].' stored. Return value: '.$ret);
551 self::$itemlist = [];
553 Logger::info('Processing done for post with URI '.$item["uri"].' for user '.$importer["uid"].'.');
559 * Removes notice item from database
561 * @param array $item item
565 private static function deleteNotice(array $item)
567 $condition = ['uid' => $item['uid'], 'author-id' => $item['author-id'], 'uri' => $item['uri']];
568 if (!Post::exists($condition)) {
569 Logger::notice('Item from '.$item['author-link'].' with uri '.$item['uri'].' for user '.$item['uid']." wasn't found. We don't delete it.");
573 Item::markForDeletion($condition);
575 Logger::notice('Deleted item with uri '.$item['uri'].' for user '.$item['uid']);
579 * Processes the XML for a post
581 * @param DOMXPath $xpath The xpath object
582 * @param object $entry The xml entry that is processed
583 * @param array $item The item array
584 * @param array $importer user record of the importing user
586 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
587 * @throws \ImagickException
589 private static function processPost(DOMXPath $xpath, $entry, array &$item, array $importer)
591 $item["body"] = HTML::toBBCode(XML::getFirstNodeValue($xpath, 'atom:content/text()', $entry));
592 $item["object-type"] = XML::getFirstNodeValue($xpath, 'activity:object-type/text()', $entry);
593 if (($item["object-type"] == Activity\ObjectType::BOOKMARK) || ($item["object-type"] == Activity\ObjectType::EVENT)) {
594 $item["title"] = XML::getFirstNodeValue($xpath, 'atom:title/text()', $entry);
595 $item["body"] = XML::getFirstNodeValue($xpath, 'atom:summary/text()', $entry);
596 } elseif ($item["object-type"] == Activity\ObjectType::QUESTION) {
597 $item["title"] = XML::getFirstNodeValue($xpath, 'atom:title/text()', $entry);
600 $item["created"] = XML::getFirstNodeValue($xpath, 'atom:published/text()', $entry);
601 $item["edited"] = XML::getFirstNodeValue($xpath, 'atom:updated/text()', $entry);
602 $item['conversation-uri'] = XML::getFirstNodeValue($xpath, 'ostatus:conversation/text()', $entry);
604 $conv = $xpath->query('ostatus:conversation', $entry);
605 if (is_object($conv->item(0))) {
606 foreach ($conv->item(0)->attributes as $attributes) {
607 if ($attributes->name == "ref") {
608 $item['conversation-uri'] = $attributes->textContent;
610 if ($attributes->name == "href") {
611 $item['conversation-href'] = $attributes->textContent;
618 $inreplyto = $xpath->query('thr:in-reply-to', $entry);
619 if (is_object($inreplyto->item(0))) {
620 foreach ($inreplyto->item(0)->attributes as $attributes) {
621 if ($attributes->name == "ref") {
622 $item["thr-parent"] = $attributes->textContent;
624 if ($attributes->name == "href") {
625 $related = $attributes->textContent;
630 $georsspoint = $xpath->query('georss:point', $entry);
631 if (!empty($georsspoint) && ($georsspoint->length > 0)) {
632 $item["coord"] = $georsspoint->item(0)->nodeValue;
635 $categories = $xpath->query('atom:category', $entry);
637 foreach ($categories as $category) {
638 foreach ($category->attributes as $attributes) {
639 if ($attributes->name == 'term') {
641 Tag::store($item['uri-id'], Tag::HASHTAG, $attributes->textContent);
650 $links = $xpath->query('atom:link', $entry);
652 $link_data = self::processLinks($links, $item);
653 $self = $link_data['self'];
654 $add_body = $link_data['add_body'];
659 $notice_info = $xpath->query('statusnet:notice_info', $entry);
660 if ($notice_info && ($notice_info->length > 0)) {
661 foreach ($notice_info->item(0)->attributes as $attributes) {
662 if ($attributes->name == "source") {
663 $item["app"] = strip_tags($attributes->textContent);
665 if ($attributes->name == "repeat_of") {
666 $repeat_of = $attributes->textContent;
670 // Is it a repeated post?
671 if (($repeat_of != "") || ($item["verb"] == Activity::SHARE)) {
672 $link_data = self::processRepeatedItem($xpath, $entry, $item, $importer);
673 if (!empty($link_data['add_body'])) {
674 $add_body .= $link_data['add_body'];
678 $item["body"] .= $add_body;
680 Tag::storeFromBody($item['uri-id'], $item['body']);
682 // Mastodon Content Warning
683 if (($item["verb"] == Activity::POST) && $xpath->evaluate('boolean(atom:summary)', $entry)) {
684 $clear_text = XML::getFirstNodeValue($xpath, 'atom:summary/text()', $entry);
685 if (!empty($clear_text)) {
686 $item['content-warning'] = HTML::toBBCode($clear_text);
690 if (($self != '') && empty($item['protocol'])) {
691 self::fetchSelf($self, $item);
694 if (!empty($item["conversation-href"])) {
695 self::fetchConversation($item['conversation-href'], $item['conversation-uri']);
698 if (isset($item["thr-parent"])) {
699 if (!Post::exists(['uid' => $importer["uid"], 'uri' => $item['thr-parent']])) {
700 if ($related != '') {
701 self::fetchRelated($related, $item["thr-parent"], $importer);
704 Logger::info('Reply with URI '.$item["uri"].' already existed for user '.$importer["uid"].'.');
707 $item["thr-parent"] = $item["uri"];
708 $item["gravity"] = GRAVITY_PARENT;
711 if (($item['author-link'] != '') && !empty($item['protocol'])) {
712 $item = Conversation::insert($item);
715 self::$itemlist[] = $item;
719 * Fetch the conversation for posts
721 * @param string $conversation The link to the conversation
722 * @param string $conversation_uri The conversation in "uri" format
724 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
726 private static function fetchConversation($conversation, $conversation_uri)
728 // Ensure that we only store a conversation once in a process
729 if (isset(self::$conv_list[$conversation])) {
733 self::$conv_list[$conversation] = true;
735 $curlResult = DI::httpClient()->get($conversation, [HttpClientOptions::ACCEPT_CONTENT => 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 $xml = $curlResult->getBody();
749 $doc = new DOMDocument();
750 if (!@$doc->loadHTML($curlResult->getBody())) {
753 $xpath = new DOMXPath($doc);
755 $links = $xpath->query('//link');
758 foreach ($links as $link) {
759 $attribute = self::readAttributes($link);
760 if (($attribute['rel'] == 'alternate') && ($attribute['type'] == 'application/atom+xml')) {
761 $file = $attribute['href'];
765 $conversation_atom = DI::httpClient()->get($attribute['href'], [HttpClientOptions::ACCEPT_CONTENT => HttpClientAccept::ATOM_XML]);
767 if ($conversation_atom->isSuccess()) {
768 $xml = $conversation_atom->getBody();
778 self::storeConversation($xml, $conversation, $conversation_uri);
782 * Store a feed in several conversation entries
784 * @param string $xml The feed
785 * @param string $conversation conversation
786 * @param string $conversation_uri conversation uri
790 private static function storeConversation($xml, $conversation = '', $conversation_uri = '')
792 $doc = new DOMDocument();
793 @$doc->loadXML($xml);
795 $xpath = new DOMXPath($doc);
796 $xpath->registerNamespace('atom', ActivityNamespace::ATOM1);
797 $xpath->registerNamespace('thr', ActivityNamespace::THREAD);
798 $xpath->registerNamespace('ostatus', ActivityNamespace::OSTATUS);
800 $entries = $xpath->query('/atom:feed/atom:entry');
802 // Now store the entries
803 foreach ($entries as $entry) {
804 $doc2 = new DOMDocument();
805 $doc2->preserveWhiteSpace = false;
806 $doc2->formatOutput = true;
810 $conv_data['protocol'] = Conversation::PARCEL_SPLIT_CONVERSATION;
811 $conv_data['direction'] = Conversation::PULL;
812 $conv_data['network'] = Protocol::OSTATUS;
813 $conv_data['uri'] = XML::getFirstNodeValue($xpath, 'atom:id/text()', $entry);
815 $inreplyto = $xpath->query('thr:in-reply-to', $entry);
816 if (is_object($inreplyto->item(0))) {
817 foreach ($inreplyto->item(0)->attributes as $attributes) {
818 if ($attributes->name == "ref") {
819 $conv_data['reply-to-uri'] = $attributes->textContent;
824 $conv_data['conversation-uri'] = XML::getFirstNodeValue($xpath, 'ostatus:conversation/text()', $entry);
826 $conv = $xpath->query('ostatus:conversation', $entry);
827 if (is_object($conv->item(0))) {
828 foreach ($conv->item(0)->attributes as $attributes) {
829 if ($attributes->name == "ref") {
830 $conv_data['conversation-uri'] = $attributes->textContent;
832 if ($attributes->name == "href") {
833 $conv_data['conversation-href'] = $attributes->textContent;
838 if ($conversation != '') {
839 $conv_data['conversation-uri'] = $conversation;
842 if ($conversation_uri != '') {
843 $conv_data['conversation-uri'] = $conversation_uri;
846 $entry = $doc2->importNode($entry, true);
848 $doc2->appendChild($entry);
850 $conv_data['source'] = $doc2->saveXML();
852 Logger::info('Store conversation data for uri '.$conv_data['uri']);
853 Conversation::insert($conv_data);
858 * Fetch the own post so that it can be stored later
860 * We want to store the original data for later processing.
861 * This function is meant for cases where we process a feed with multiple entries.
862 * In that case we need to fetch the single posts here.
864 * @param string $self The link to the self item
865 * @param array $item The item array
867 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
869 private static function fetchSelf($self, array &$item)
871 $condition = ['item-uri' => $self, 'protocol' => [Conversation::PARCEL_DFRN,
872 Conversation::PARCEL_DIASPORA_DFRN, Conversation::PARCEL_LOCAL_DFRN,
873 Conversation::PARCEL_DIRECT, Conversation::PARCEL_SALMON]];
874 if (DBA::exists('conversation', $condition)) {
875 Logger::info('Conversation '.$item['uri'].' is already stored.');
879 $curlResult = DI::httpClient()->get($self, [HttpClientOptions::ACCEPT_CONTENT => HttpClientAccept::ATOM_XML]);
881 if (!$curlResult->isSuccess()) {
885 // We reformat the XML to make it better readable
886 $doc = new DOMDocument();
887 $doc->loadXML($curlResult->getBody());
888 $doc->preserveWhiteSpace = false;
889 $doc->formatOutput = true;
890 $xml = $doc->saveXML();
892 $item["protocol"] = Conversation::PARCEL_SALMON;
893 $item["source"] = $xml;
894 $item["direction"] = Conversation::PULL;
896 Logger::info('Conversation '.$item['uri'].' is now fetched.');
900 * Fetch related posts and processes them
902 * @param string $related The link to the related item
903 * @param string $related_uri The related item in "uri" format
904 * @param array $importer user record of the importing user
906 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
907 * @throws \ImagickException
909 private static function fetchRelated($related, $related_uri, $importer)
911 $condition = ['item-uri' => $related_uri, 'protocol' => [Conversation::PARCEL_DFRN,
912 Conversation::PARCEL_DIASPORA_DFRN, Conversation::PARCEL_LOCAL_DFRN,
913 Conversation::PARCEL_DIRECT, Conversation::PARCEL_SALMON]];
914 $conversation = DBA::selectFirst('conversation', ['source', 'protocol'], $condition);
915 if (DBA::isResult($conversation)) {
917 $xml = $conversation['source'];
918 if (self::process($xml, $importer, $contact, $hub, $stored, false, Conversation::PULL)) {
919 Logger::info('Got valid cached XML for URI '.$related_uri);
922 if ($conversation['protocol'] == Conversation::PARCEL_SALMON) {
923 Logger::info('Delete invalid cached XML for URI '.$related_uri);
924 DBA::delete('conversation', ['item-uri' => $related_uri]);
929 $curlResult = DI::httpClient()->get($related, [HttpClientOptions::ACCEPT_CONTENT => HttpClientAccept::ATOM_XML]);
931 if (!$curlResult->isSuccess() || empty($curlResult->getBody())) {
937 if ($curlResult->inHeader('Content-Type') &&
938 in_array('application/atom+xml', $curlResult->getHeader('Content-Type'))) {
939 Logger::info('Directly fetched XML for URI ' . $related_uri);
940 $xml = $curlResult->getBody();
944 $doc = new DOMDocument();
945 if (!@$doc->loadHTML($curlResult->getBody())) {
948 $xpath = new DOMXPath($doc);
952 $links = $xpath->query('//link');
954 foreach ($links as $link) {
955 $attribute = self::readAttributes($link);
956 if (($attribute['rel'] == 'alternate') && ($attribute['type'] == 'application/atom+xml')) {
957 $atom_file = $attribute['href'];
960 if ($atom_file != '') {
961 $curlResult = DI::httpClient()->get($atom_file, [HttpClientOptions::ACCEPT_CONTENT => HttpClientAccept::ATOM_XML]);
963 if ($curlResult->isSuccess()) {
964 Logger::info('Fetched XML for URI ' . $related_uri);
965 $xml = $curlResult->getBody();
971 // Workaround for older GNU Social servers
972 if (($xml == '') && strstr($related, '/notice/')) {
973 $curlResult = DI::httpClient()->get(str_replace('/notice/', '/api/statuses/show/', $related) . '.atom', [HttpClientOptions::ACCEPT_CONTENT => HttpClientAccept::ATOM_XML]);
975 if ($curlResult->isSuccess()) {
976 Logger::info('GNU Social workaround to fetch XML for URI ' . $related_uri);
977 $xml = $curlResult->getBody();
981 // Even more worse workaround for GNU Social ;-)
983 $related_guess = self::convertHref($related_uri);
984 $curlResult = DI::httpClient()->get(str_replace('/notice/', '/api/statuses/show/', $related_guess) . '.atom', [HttpClientOptions::ACCEPT_CONTENT => HttpClientAccept::ATOM_XML]);
986 if ($curlResult->isSuccess()) {
987 Logger::info('GNU Social workaround 2 to fetch XML for URI ' . $related_uri);
988 $xml = $curlResult->getBody();
992 // Finally we take the data that we fetched from "ostatus:conversation"
994 $condition = ['item-uri' => $related_uri, 'protocol' => Conversation::PARCEL_SPLIT_CONVERSATION];
995 $conversation = DBA::selectFirst('conversation', ['source'], $condition);
996 if (DBA::isResult($conversation)) {
998 Logger::info('Got cached XML from conversation for URI '.$related_uri);
999 $xml = $conversation['source'];
1004 self::process($xml, $importer, $contact, $hub, $stored, false, Conversation::PULL);
1006 Logger::info("XML couldn't be fetched for URI: ".$related_uri." - href: ".$related);
1012 * Processes the XML for a repeated post
1014 * @param DOMXPath $xpath The xpath object
1015 * @param object $entry The xml entry that is processed
1016 * @param array $item The item array
1017 * @param array $importer user record of the importing user
1019 * @return array with data from links
1020 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1021 * @throws \ImagickException
1023 private static function processRepeatedItem(DOMXPath $xpath, $entry, array &$item, array $importer)
1025 $activityobject = $xpath->query('activity:object', $entry)->item(0);
1027 if (!is_object($activityobject)) {
1033 $orig_uri = XML::getFirstNodeValue($xpath, 'atom:id/text()', $activityobject);
1035 $links = $xpath->query("atom:link", $activityobject);
1037 $link_data = self::processLinks($links, $item);
1040 $orig_body = XML::getFirstNodeValue($xpath, 'atom:content/text()', $activityobject);
1041 $orig_created = XML::getFirstNodeValue($xpath, 'atom:published/text()', $activityobject);
1042 $orig_edited = XML::getFirstNodeValue($xpath, 'atom:updated/text()', $activityobject);
1044 $orig_author = self::fetchAuthor($xpath, $activityobject, $importer, $dummy, false);
1046 $item["author-name"] = $orig_author["author-name"];
1047 $item["author-link"] = $orig_author["author-link"];
1048 $item["author-id"] = $orig_author["author-id"];
1050 $item["body"] = HTML::toBBCode($orig_body);
1051 $item["created"] = $orig_created;
1052 $item["edited"] = $orig_edited;
1054 $item["uri"] = $orig_uri;
1056 $item["verb"] = XML::getFirstNodeValue($xpath, 'activity:verb/text()', $activityobject);
1058 $item["object-type"] = XML::getFirstNodeValue($xpath, 'activity:object-type/text()', $activityobject);
1060 // Mastodon Content Warning
1061 if (($item["verb"] == Activity::POST) && $xpath->evaluate('boolean(atom:summary)', $activityobject)) {
1062 $clear_text = XML::getFirstNodeValue($xpath, 'atom:summary/text()', $activityobject);
1063 if (!empty($clear_text)) {
1064 $item['content-warning'] = HTML::toBBCode($clear_text);
1068 $inreplyto = $xpath->query('thr:in-reply-to', $activityobject);
1069 if (is_object($inreplyto->item(0))) {
1070 foreach ($inreplyto->item(0)->attributes as $attributes) {
1071 if ($attributes->name == "ref") {
1072 $item["thr-parent"] = $attributes->textContent;
1081 * Processes links in the XML
1083 * @param object $links The xml data that contain links
1084 * @param array $item The item array
1086 * @return array with data from the links
1088 private static function processLinks($links, array &$item)
1090 $link_data = ['add_body' => '', 'self' => ''];
1092 foreach ($links as $link) {
1093 $attribute = self::readAttributes($link);
1095 if (!empty($attribute['rel']) && !empty($attribute['href'])) {
1096 switch ($attribute['rel']) {
1098 $item["plink"] = $attribute['href'];
1099 if (($item["object-type"] == Activity\ObjectType::QUESTION)
1100 || ($item["object-type"] == Activity\ObjectType::EVENT)
1102 Post\Media::insert(['uri-id' => $item['uri-id'], 'type' => Post\Media::UNKNOWN,
1103 'url' => $attribute['href'], 'mimetype' => $attribute['type'] ?? null,
1104 'size' => $attribute['length'] ?? null, 'description' => $attribute['title'] ?? null]);
1107 case "ostatus:conversation":
1108 $link_data['conversation'] = $attribute['href'];
1109 $item['conversation-href'] = $link_data['conversation'];
1110 if (!isset($item['conversation-uri'])) {
1111 $item['conversation-uri'] = $item['conversation-href'];
1115 $filetype = strtolower(substr($attribute['type'], 0, strpos($attribute['type'], '/')));
1116 if ($filetype == 'image') {
1117 $link_data['add_body'] .= "\n[img]".$attribute['href'].'[/img]';
1119 Post\Media::insert(['uri-id' => $item['uri-id'], 'type' => Post\Media::DOCUMENT,
1120 'url' => $attribute['href'], 'mimetype' => $attribute['type'],
1121 'size' => $attribute['length'] ?? null, 'description' => $attribute['title'] ?? null]);
1125 if ($item["object-type"] != Activity\ObjectType::BOOKMARK) {
1126 if (!isset($item["thr-parent"])) {
1127 $item["thr-parent"] = $attribute['href'];
1129 $link_data['related'] = $attribute['href'];
1131 Post\Media::insert(['uri-id' => $item['uri-id'], 'type' => Post\Media::UNKNOWN,
1132 'url' => $attribute['href'], 'mimetype' => $attribute['type'] ?? null,
1133 'size' => $attribute['length'] ?? null, 'description' => $attribute['title'] ?? null]);
1137 if (empty($item["plink"])) {
1138 $item["plink"] = $attribute['href'];
1140 $link_data['self'] = $attribute['href'];
1149 * Create an url out of an uri
1151 * @param string $href URI in the format "parameter1:parameter1:..."
1153 * @return string URL in the format http(s)://....
1155 private static function convertHref($href)
1157 $elements = explode(":", $href);
1159 if ((count($elements) <= 2) || ($elements[0] != "tag")) {
1163 $server = explode(",", $elements[1]);
1164 $conversation = explode("=", $elements[2]);
1166 if ((count($elements) == 4) && ($elements[2] == "post")) {
1167 return "http://".$server[0]."/notice/".$elements[3];
1170 if ((count($conversation) != 2) || ($conversation[1] =="")) {
1173 if ($elements[3] == "objectType=thread") {
1174 return "http://".$server[0]."/conversation/".$conversation[1];
1176 return "http://".$server[0]."/notice/".$conversation[1];
1181 * Cleans the body of a post if it contains picture links
1183 * @param string $body The body
1185 * @return string The cleaned body
1186 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1188 public static function formatPicturePost($body, $uriid)
1190 $siteinfo = BBCode::getAttachedData($body);
1192 if (($siteinfo["type"] == "photo") && (!empty($siteinfo["preview"]) || !empty($siteinfo["image"]))) {
1193 if (isset($siteinfo["preview"])) {
1194 $preview = $siteinfo["preview"];
1196 $preview = $siteinfo["image"];
1199 // Is it a remote picture? Then make a smaller preview here
1200 $preview = Post\Link::getByLink($uriid, $preview, Proxy::SIZE_SMALL);
1202 // Is it a local picture? Then make it smaller here
1203 $preview = str_replace(["-0.jpg", "-0.png"], ["-2.jpg", "-2.png"], $preview);
1204 $preview = str_replace(["-1.jpg", "-1.png"], ["-2.jpg", "-2.png"], $preview);
1206 if (isset($siteinfo["url"])) {
1207 $url = $siteinfo["url"];
1209 $url = $siteinfo["image"];
1212 $body = trim($siteinfo["text"])." [url]".$url."[/url]\n[img]".$preview."[/img]";
1219 * Adds the header elements to the XML document
1221 * @param DOMDocument $doc XML document
1222 * @param array $owner Contact data of the poster
1223 * @param string $filter The related feed filter (activity, posts or comments)
1225 * @return object header root element
1226 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1228 private static function addHeader(DOMDocument $doc, array $owner, $filter)
1230 $root = $doc->createElementNS(ActivityNamespace::ATOM1, 'feed');
1231 $doc->appendChild($root);
1233 $root->setAttribute("xmlns:thr", ActivityNamespace::THREAD);
1234 $root->setAttribute("xmlns:georss", ActivityNamespace::GEORSS);
1235 $root->setAttribute("xmlns:activity", ActivityNamespace::ACTIVITY);
1236 $root->setAttribute("xmlns:media", ActivityNamespace::MEDIA);
1237 $root->setAttribute("xmlns:poco", ActivityNamespace::POCO);
1238 $root->setAttribute("xmlns:ostatus", ActivityNamespace::OSTATUS);
1239 $root->setAttribute("xmlns:statusnet", ActivityNamespace::STATUSNET);
1240 $root->setAttribute("xmlns:mastodon", ActivityNamespace::MASTODON);
1243 $selfUri = '/feed/' . $owner["nick"] . '/';
1246 $title = DI::l10n()->t('%s\'s timeline', $owner['name']);
1247 $selfUri .= $filter;
1250 $title = DI::l10n()->t('%s\'s posts', $owner['name']);
1253 $title = DI::l10n()->t('%s\'s comments', $owner['name']);
1254 $selfUri .= $filter;
1258 $selfUri = "/dfrn_poll/" . $owner["nick"];
1260 $attributes = ["uri" => "https://friendi.ca", "version" => FRIENDICA_VERSION . "-" . DB_UPDATE_VERSION];
1261 XML::addElement($doc, $root, "generator", FRIENDICA_PLATFORM, $attributes);
1262 XML::addElement($doc, $root, "id", DI::baseUrl() . "/profile/" . $owner["nick"]);
1263 XML::addElement($doc, $root, "title", $title);
1264 XML::addElement($doc, $root, "subtitle", sprintf("Updates from %s on %s", $owner["name"], DI::config()->get('config', 'sitename')));
1265 XML::addElement($doc, $root, "logo", User::getAvatarUrl($owner, Proxy::SIZE_SMALL));
1266 XML::addElement($doc, $root, "updated", DateTimeFormat::utcNow(DateTimeFormat::ATOM));
1268 $author = self::addAuthor($doc, $owner, true);
1269 $root->appendChild($author);
1271 $attributes = ["href" => $owner["url"], "rel" => "alternate", "type" => "text/html"];
1272 XML::addElement($doc, $root, "link", "", $attributes);
1274 /// @TODO We have to find out what this is
1275 /// $attributes = array("href" => DI::baseUrl()."/sup",
1276 /// "rel" => "http://api.friendfeed.com/2008/03#sup",
1277 /// "type" => "application/json");
1278 /// XML::addElement($doc, $root, "link", "", $attributes);
1280 self::hublinks($doc, $root, $owner["nick"]);
1282 $attributes = ["href" => DI::baseUrl() . "/salmon/" . $owner["nick"], "rel" => "salmon"];
1283 XML::addElement($doc, $root, "link", "", $attributes);
1285 $attributes = ["href" => DI::baseUrl() . "/salmon/" . $owner["nick"], "rel" => "http://salmon-protocol.org/ns/salmon-replies"];
1286 XML::addElement($doc, $root, "link", "", $attributes);
1288 $attributes = ["href" => DI::baseUrl() . "/salmon/" . $owner["nick"], "rel" => "http://salmon-protocol.org/ns/salmon-mention"];
1289 XML::addElement($doc, $root, "link", "", $attributes);
1291 $attributes = ["href" => DI::baseUrl() . $selfUri, "rel" => "self", "type" => "application/atom+xml"];
1292 XML::addElement($doc, $root, "link", "", $attributes);
1294 if ($owner['contact-type'] == Contact::TYPE_COMMUNITY) {
1295 $condition = ['uid' => $owner['uid'], 'self' => false, 'pending' => false,
1296 'archive' => false, 'hidden' => false, 'blocked' => false];
1297 $members = DBA::count('contact', $condition);
1298 XML::addElement($doc, $root, "statusnet:group_info", "", ["member_count" => $members]);
1305 * Add the link to the push hubs to the XML document
1307 * @param DOMDocument $doc XML document
1308 * @param object $root XML root element where the hub links are added
1309 * @param object $nick nick
1311 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1313 public static function hublinks(DOMDocument $doc, $root, $nick)
1315 $h = DI::baseUrl() . '/pubsubhubbub/'.$nick;
1316 XML::addElement($doc, $root, "link", "", ["href" => $h, "rel" => "hub"]);
1320 * Adds attachment data to the XML document
1322 * @param DOMDocument $doc XML document
1323 * @param object $root XML root element where the hub links are added
1324 * @param array $item Data of the item that is to be posted
1326 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1328 public static function getAttachment(DOMDocument $doc, $root, $item)
1330 $siteinfo = BBCode::getAttachedData($item["body"]);
1332 switch ($siteinfo["type"]) {
1334 if (!empty($siteinfo["image"])) {
1335 $imgdata = Images::getInfoFromURLCached($siteinfo["image"]);
1337 $attributes = ["rel" => "enclosure",
1338 "href" => $siteinfo["image"],
1339 "type" => $imgdata["mime"],
1340 "length" => intval($imgdata["size"])];
1341 XML::addElement($doc, $root, "link", "", $attributes);
1346 $attributes = ["rel" => "enclosure",
1347 "href" => $siteinfo["url"],
1348 "type" => "text/html; charset=UTF-8",
1350 "title" => ($siteinfo["title"] ?? '') ?: $siteinfo["url"],
1352 XML::addElement($doc, $root, "link", "", $attributes);
1358 if (!DI::config()->get('system', 'ostatus_not_attach_preview') && ($siteinfo["type"] != "photo") && isset($siteinfo["image"])) {
1359 $imgdata = Images::getInfoFromURLCached($siteinfo["image"]);
1361 $attributes = ["rel" => "enclosure",
1362 "href" => $siteinfo["image"],
1363 "type" => $imgdata["mime"],
1364 "length" => intval($imgdata["size"])];
1366 XML::addElement($doc, $root, "link", "", $attributes);
1370 foreach (Post\Media::getByURIId($item['uri-id'], [Post\Media::DOCUMENT, Post\Media::TORRENT, Post\Media::UNKNOWN]) as $attachment) {
1371 $attributes = ['rel' => 'enclosure',
1372 'href' => $attachment['url'],
1373 'type' => $attachment['mimetype']];
1375 if (!empty($attachment['size'])) {
1376 $attributes['length'] = intval($attachment['size']);
1378 if (!empty($attachment['description'])) {
1379 $attributes['title'] = $attachment['description'];
1382 XML::addElement($doc, $root, 'link', '', $attributes);
1387 * Adds the author element to the XML document
1389 * @param DOMDocument $doc XML document
1390 * @param array $owner Contact data of the poster
1391 * @param bool $show_profile Whether to show profile
1393 * @return \DOMElement author element
1394 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1396 private static function addAuthor(DOMDocument $doc, array $owner, $show_profile = true)
1398 $profile = DBA::selectFirst('profile', ['homepage', 'publish'], ['uid' => $owner['uid']]);
1399 $author = $doc->createElement("author");
1400 XML::addElement($doc, $author, "id", $owner["url"]);
1401 if ($owner['contact-type'] == Contact::TYPE_COMMUNITY) {
1402 XML::addElement($doc, $author, "activity:object-type", Activity\ObjectType::GROUP);
1404 XML::addElement($doc, $author, "activity:object-type", Activity\ObjectType::PERSON);
1407 XML::addElement($doc, $author, "uri", $owner["url"]);
1408 XML::addElement($doc, $author, "name", $owner["nick"]);
1409 XML::addElement($doc, $author, "email", $owner["addr"]);
1410 if ($show_profile) {
1411 XML::addElement($doc, $author, "summary", BBCode::convertForUriId($owner['uri-id'], $owner["about"], BBCode::OSTATUS));
1414 $attributes = ["rel" => "alternate", "type" => "text/html", "href" => $owner["url"]];
1415 XML::addElement($doc, $author, "link", "", $attributes);
1419 "type" => "image/jpeg", // To-Do?
1420 "media:width" => Proxy::PIXEL_SMALL,
1421 "media:height" => Proxy::PIXEL_SMALL,
1422 "href" => User::getAvatarUrl($owner, Proxy::SIZE_SMALL)];
1423 XML::addElement($doc, $author, "link", "", $attributes);
1425 if (isset($owner["thumb"])) {
1428 "type" => "image/jpeg", // To-Do?
1429 "media:width" => Proxy::PIXEL_THUMB,
1430 "media:height" => Proxy::PIXEL_THUMB,
1431 "href" => User::getAvatarUrl($owner, Proxy::SIZE_THUMB)];
1432 XML::addElement($doc, $author, "link", "", $attributes);
1435 XML::addElement($doc, $author, "poco:preferredUsername", $owner["nick"]);
1436 XML::addElement($doc, $author, "poco:displayName", $owner["name"]);
1437 if ($show_profile) {
1438 XML::addElement($doc, $author, "poco:note", BBCode::convertForUriId($owner['uri-id'], $owner["about"], BBCode::OSTATUS));
1440 if (trim($owner["location"]) != "") {
1441 $element = $doc->createElement("poco:address");
1442 XML::addElement($doc, $element, "poco:formatted", $owner["location"]);
1443 $author->appendChild($element);
1447 if (DBA::isResult($profile) && !$show_profile) {
1448 if (trim($profile["homepage"]) != "") {
1449 $urls = $doc->createElement("poco:urls");
1450 XML::addElement($doc, $urls, "poco:type", "homepage");
1451 XML::addElement($doc, $urls, "poco:value", $profile["homepage"]);
1452 XML::addElement($doc, $urls, "poco:primary", "true");
1453 $author->appendChild($urls);
1456 XML::addElement($doc, $author, "followers", "", ["url" => DI::baseUrl() . "/profile/" . $owner["nick"] . "/contacts/followers"]);
1457 XML::addElement($doc, $author, "statusnet:profile_info", "", ["local_id" => $owner["uid"]]);
1459 if ($profile["publish"]) {
1460 XML::addElement($doc, $author, "mastodon:scope", "public");
1468 * @TODO Picture attachments should look like this:
1469 * <a href="https://status.pirati.ca/attachment/572819" title="https://status.pirati.ca/file/heluecht-20151202T222602-rd3u49p.gif"
1470 * class="attachment thumbnail" id="attachment-572819" rel="nofollow external">https://status.pirati.ca/attachment/572819</a>
1474 * Returns the given activity if present - otherwise returns the "post" activity
1476 * @param array $item Data of the item that is to be posted
1478 * @return string activity
1480 public static function constructVerb(array $item)
1482 if (!empty($item['verb'])) {
1483 return $item['verb'];
1486 return Activity::POST;
1490 * Returns the given object type if present - otherwise returns the "note" object type
1492 * @param array $item Data of the item that is to be posted
1494 * @return string Object type
1496 private static function constructObjecttype(array $item)
1498 if (!empty($item['object-type']) && in_array($item['object-type'], [Activity\ObjectType::NOTE, Activity\ObjectType::COMMENT])) {
1499 return $item['object-type'];
1502 return Activity\ObjectType::NOTE;
1506 * Adds an entry element to the XML document
1508 * @param DOMDocument $doc XML document
1509 * @param array $item Data of the item that is to be posted
1510 * @param array $owner Contact data of the poster
1511 * @param bool $toplevel optional default false
1513 * @return \DOMElement Entry element
1514 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1515 * @throws \ImagickException
1517 private static function entry(DOMDocument $doc, array $item, array $owner, $toplevel = false)
1519 if ($item["verb"] == Activity::LIKE) {
1520 return self::likeEntry($doc, $item, $owner, $toplevel);
1521 } elseif (in_array($item["verb"], [Activity::FOLLOW, Activity::O_UNFOLLOW])) {
1522 return self::followEntry($doc, $item, $owner, $toplevel);
1524 return self::noteEntry($doc, $item, $owner, $toplevel);
1529 * Adds an entry element with a "like"
1531 * @param DOMDocument $doc XML document
1532 * @param array $item Data of the item that is to be posted
1533 * @param array $owner Contact data of the poster
1534 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1536 * @return \DOMElement Entry element with "like"
1537 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1538 * @throws \ImagickException
1540 private static function likeEntry(DOMDocument $doc, array $item, array $owner, $toplevel)
1542 if (($item['gravity'] != GRAVITY_PARENT) && (Strings::normaliseLink($item["author-link"]) != Strings::normaliseLink($owner["url"]))) {
1543 Logger::info("OStatus entry is from author ".$owner["url"]." - not from ".$item["author-link"].". Quitting.");
1546 $entry = self::entryHeader($doc, $owner, $item, $toplevel);
1548 $verb = ActivityNamespace::ACTIVITY_SCHEMA . "favorite";
1549 self::entryContent($doc, $entry, $item, $owner, "Favorite", $verb, false);
1551 $parent = Post::selectFirst([], ['uri' => $item["thr-parent"], 'uid' => $item["uid"]]);
1552 if (DBA::isResult($parent)) {
1553 $as_object = $doc->createElement("activity:object");
1555 XML::addElement($doc, $as_object, "activity:object-type", self::constructObjecttype($parent));
1557 self::entryContent($doc, $as_object, $parent, $owner, "New entry");
1559 $entry->appendChild($as_object);
1562 self::entryFooter($doc, $entry, $item, $owner);
1568 * Adds the person object element to the XML document
1570 * @param DOMDocument $doc XML document
1571 * @param array $owner Contact data of the poster
1572 * @param array $contact Contact data of the target
1574 * @return object author element
1576 private static function addPersonObject(DOMDocument $doc, array $owner, array $contact)
1578 $object = $doc->createElement("activity:object");
1579 XML::addElement($doc, $object, "activity:object-type", Activity\ObjectType::PERSON);
1581 if ($contact['network'] == Protocol::PHANTOM) {
1582 XML::addElement($doc, $object, "id", $contact['url']);
1586 XML::addElement($doc, $object, "id", $contact["alias"]);
1587 XML::addElement($doc, $object, "title", $contact["nick"]);
1589 $attributes = ["rel" => "alternate", "type" => "text/html", "href" => $contact["url"]];
1590 XML::addElement($doc, $object, "link", "", $attributes);
1594 "type" => "image/jpeg", // To-Do?
1595 "media:width" => 300,
1596 "media:height" => 300,
1597 "href" => $contact["photo"]];
1598 XML::addElement($doc, $object, "link", "", $attributes);
1600 XML::addElement($doc, $object, "poco:preferredUsername", $contact["nick"]);
1601 XML::addElement($doc, $object, "poco:displayName", $contact["name"]);
1603 if (trim($contact["location"]) != "") {
1604 $element = $doc->createElement("poco:address");
1605 XML::addElement($doc, $element, "poco:formatted", $contact["location"]);
1606 $object->appendChild($element);
1613 * Adds a follow/unfollow entry element
1615 * @param DOMDocument $doc XML document
1616 * @param array $item Data of the follow/unfollow message
1617 * @param array $owner Contact data of the poster
1618 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1620 * @return \DOMElement Entry element
1621 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1622 * @throws \ImagickException
1624 private static function followEntry(DOMDocument $doc, array $item, array $owner, $toplevel)
1626 $item["id"] = $item['parent'] = 0;
1627 $item["created"] = $item["edited"] = date("c");
1628 $item["private"] = Item::PRIVATE;
1630 $contact = Contact::getByURL($item['follow']);
1631 $item['follow'] = $contact['url'];
1633 if ($contact['alias']) {
1634 $item['follow'] = $contact['alias'];
1636 $contact['alias'] = $contact['url'];
1639 $condition = ['uid' => $owner['uid'], 'nurl' => Strings::normaliseLink($contact["url"])];
1640 $user_contact = DBA::selectFirst('contact', ['id'], $condition);
1642 if (DBA::isResult($user_contact)) {
1643 $connect_id = $user_contact['id'];
1648 if ($item['verb'] == Activity::FOLLOW) {
1649 $message = DI::l10n()->t('%s is now following %s.');
1650 $title = DI::l10n()->t('following');
1651 $action = "subscription";
1653 $message = DI::l10n()->t('%s stopped following %s.');
1654 $title = DI::l10n()->t('stopped following');
1655 $action = "unfollow";
1658 $item["uri"] = $item['parent-uri'] = $item['thr-parent']
1659 = 'tag:' . DI::baseUrl()->getHostname().
1660 ','.date('Y-m-d').':'.$action.':'.$owner['uid'].
1661 ':person:'.$connect_id.':'.$item['created'];
1663 $item["body"] = sprintf($message, $owner["nick"], $contact["nick"]);
1665 $entry = self::entryHeader($doc, $owner, $item, $toplevel);
1667 self::entryContent($doc, $entry, $item, $owner, $title);
1669 $object = self::addPersonObject($doc, $owner, $contact);
1670 $entry->appendChild($object);
1672 self::entryFooter($doc, $entry, $item, $owner);
1678 * Adds a regular entry element
1680 * @param DOMDocument $doc XML document
1681 * @param array $item Data of the item that is to be posted
1682 * @param array $owner Contact data of the poster
1683 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1685 * @return \DOMElement Entry element
1686 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1687 * @throws \ImagickException
1689 private static function noteEntry(DOMDocument $doc, array $item, array $owner, $toplevel)
1691 if (($item['gravity'] != GRAVITY_PARENT) && (Strings::normaliseLink($item["author-link"]) != Strings::normaliseLink($owner["url"]))) {
1692 Logger::info("OStatus entry is from author ".$owner["url"]." - not from ".$item["author-link"].". Quitting.");
1696 if (!empty($item['title'])) {
1697 $title = BBCode::convertForUriId($item['uri-id'], $item['title'], BBCode::OSTATUS);
1699 $title = sprintf("New note by %s", $owner["nick"]);
1702 $title = sprintf("New comment by %s", $owner["nick"]);
1705 $entry = self::entryHeader($doc, $owner, $item, $toplevel);
1707 XML::addElement($doc, $entry, "activity:object-type", Activity\ObjectType::NOTE);
1709 self::entryContent($doc, $entry, $item, $owner, $title, '', true);
1711 self::entryFooter($doc, $entry, $item, $owner, true);
1717 * Adds a header element to the XML document
1719 * @param DOMDocument $doc XML document
1720 * @param array $owner Contact data of the poster
1721 * @param array $item
1722 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1724 * @return \DOMElement The entry element where the elements are added
1725 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1726 * @throws \ImagickException
1728 public static function entryHeader(DOMDocument $doc, array $owner, array $item, $toplevel)
1731 $entry = $doc->createElement("entry");
1733 if ($owner['contact-type'] == Contact::TYPE_COMMUNITY) {
1734 $contact = Contact::getByURL($item['author-link']) ?: $owner;
1735 $contact['nickname'] = $contact['nickname'] ?? $contact['nick'];
1736 $author = self::addAuthor($doc, $contact, false);
1737 $entry->appendChild($author);
1740 $entry = $doc->createElementNS(ActivityNamespace::ATOM1, "entry");
1742 $entry->setAttribute("xmlns:thr", ActivityNamespace::THREAD);
1743 $entry->setAttribute("xmlns:georss", ActivityNamespace::GEORSS);
1744 $entry->setAttribute("xmlns:activity", ActivityNamespace::ACTIVITY);
1745 $entry->setAttribute("xmlns:media", ActivityNamespace::MEDIA);
1746 $entry->setAttribute("xmlns:poco", ActivityNamespace::POCO);
1747 $entry->setAttribute("xmlns:ostatus", ActivityNamespace::OSTATUS);
1748 $entry->setAttribute("xmlns:statusnet", ActivityNamespace::STATUSNET);
1749 $entry->setAttribute("xmlns:mastodon", ActivityNamespace::MASTODON);
1751 $author = self::addAuthor($doc, $owner);
1752 $entry->appendChild($author);
1759 * Adds elements to the XML document
1761 * @param DOMDocument $doc XML document
1762 * @param \DOMElement $entry Entry element where the content is added
1763 * @param array $item Data of the item that is to be posted
1764 * @param array $owner Contact data of the poster
1765 * @param string $title Title for the post
1766 * @param string $verb The activity verb
1767 * @param bool $complete Add the "status_net" element?
1769 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1771 private static function entryContent(DOMDocument $doc, \DOMElement $entry, array $item, array $owner, $title, $verb = "", $complete = true)
1774 $verb = self::constructVerb($item);
1777 XML::addElement($doc, $entry, "id", $item["uri"]);
1778 XML::addElement($doc, $entry, "title", html_entity_decode($title, ENT_QUOTES, 'UTF-8'));
1780 $body = Post\Media::addAttachmentsToBody($item['uri-id'], $item['body']);
1781 $body = self::formatPicturePost($body, $item['uri-id']);
1783 if (!empty($item['title'])) {
1784 $body = "[b]".$item['title']."[/b]\n\n".$body;
1787 $body = BBCode::convertForUriId($item['uri-id'], $body, BBCode::OSTATUS);
1789 XML::addElement($doc, $entry, "content", $body, ["type" => "html"]);
1791 XML::addElement($doc, $entry, "link", "", ["rel" => "alternate", "type" => "text/html",
1792 "href" => DI::baseUrl()."/display/".$item["guid"]]
1795 if ($complete && ($item["id"] > 0)) {
1796 XML::addElement($doc, $entry, "status_net", "", ["notice_id" => $item["id"]]);
1799 XML::addElement($doc, $entry, "activity:verb", $verb);
1801 XML::addElement($doc, $entry, "published", DateTimeFormat::utc($item["created"]."+00:00", DateTimeFormat::ATOM));
1802 XML::addElement($doc, $entry, "updated", DateTimeFormat::utc($item["edited"]."+00:00", DateTimeFormat::ATOM));
1806 * Adds the elements at the foot of an entry to the XML document
1808 * @param DOMDocument $doc XML document
1809 * @param object $entry The entry element where the elements are added
1810 * @param array $item Data of the item that is to be posted
1811 * @param array $owner Contact data of the poster
1812 * @param bool $complete default true
1814 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1816 private static function entryFooter(DOMDocument $doc, $entry, array $item, array $owner, $complete = true)
1820 if ($item['gravity'] != GRAVITY_PARENT) {
1821 $parent = Post::selectFirst(['guid', 'author-link', 'owner-link'], ['id' => $item['parent']]);
1823 $thrparent = Post::selectFirst(['guid', 'author-link', 'owner-link', 'plink'], ['uid' => $owner['uid'], 'uri' => $item['thr-parent']]);
1825 if (DBA::isResult($thrparent)) {
1826 $mentioned[$thrparent['author-link']] = $thrparent['author-link'];
1827 $mentioned[$thrparent['owner-link']] = $thrparent['owner-link'];
1828 $parent_plink = $thrparent['plink'];
1829 } elseif (DBA::isResult($parent)) {
1830 $mentioned[$parent['author-link']] = $parent['author-link'];
1831 $mentioned[$parent['owner-link']] = $parent['owner-link'];
1832 $parent_plink = DI::baseUrl() . '/display/' . $parent['guid'];
1834 DI::logger()->notice('Missing parent and thr-parent for child item', ['item' => $item]);
1837 if (isset($parent_plink)) {
1839 'ref' => $item['thr-parent'],
1840 'href' => $parent_plink];
1841 XML::addElement($doc, $entry, 'thr:in-reply-to', '', $attributes);
1845 'href' => $parent_plink];
1846 XML::addElement($doc, $entry, 'link', '', $attributes);
1850 if (intval($item['parent']) > 0) {
1851 $conversation_href = $conversation_uri = str_replace('/objects/', '/context/', $item['thr-parent']);
1853 if (isset($parent_item)) {
1854 $conversation = DBA::selectFirst('conversation', ['conversation-uri', 'conversation-href'], ['item-uri' => $parent_item]);
1855 if (DBA::isResult($conversation)) {
1856 if ($conversation['conversation-uri'] != '') {
1857 $conversation_uri = $conversation['conversation-uri'];
1859 if ($conversation['conversation-href'] != '') {
1860 $conversation_href = $conversation['conversation-href'];
1865 XML::addElement($doc, $entry, "link", "", ["rel" => "ostatus:conversation", "href" => $conversation_href]);
1868 "href" => $conversation_href,
1869 "local_id" => $item['parent'],
1870 "ref" => $conversation_uri];
1872 XML::addElement($doc, $entry, "ostatus:conversation", $conversation_uri, $attributes);
1875 // uri-id isn't present for follow entry pseudo-items
1876 $tags = Tag::getByURIId($item['uri-id'] ?? 0);
1877 foreach ($tags as $tag) {
1878 $mentioned[$tag['url']] = $tag['url'];
1881 // Make sure that mentions are accepted (GNU Social has problems with mixing HTTP and HTTPS)
1883 foreach ($mentioned as $mention) {
1884 $newmentions[str_replace("http://", "https://", $mention)] = str_replace("http://", "https://", $mention);
1885 $newmentions[str_replace("https://", "http://", $mention)] = str_replace("https://", "http://", $mention);
1887 $mentioned = $newmentions;
1889 foreach ($mentioned as $mention) {
1890 $contact = Contact::getByURL($mention, false, ['contact-type']);
1891 if (!empty($contact) && ($contact['contact-type'] == Contact::TYPE_COMMUNITY)) {
1892 XML::addElement($doc, $entry, "link", "",
1894 "rel" => "mentioned",
1895 "ostatus:object-type" => Activity\ObjectType::GROUP,
1899 XML::addElement($doc, $entry, "link", "",
1901 "rel" => "mentioned",
1902 "ostatus:object-type" => Activity\ObjectType::PERSON,
1908 if ($owner['contact-type'] == Contact::TYPE_COMMUNITY) {
1909 XML::addElement($doc, $entry, "link", "", [
1910 "rel" => "mentioned",
1911 "ostatus:object-type" => "http://activitystrea.ms/schema/1.0/group",
1912 "href" => $owner['url']
1916 if ($item['private'] != Item::PRIVATE) {
1917 XML::addElement($doc, $entry, "link", "", ["rel" => "ostatus:attention",
1918 "href" => "http://activityschema.org/collection/public"]);
1919 XML::addElement($doc, $entry, "link", "", ["rel" => "mentioned",
1920 "ostatus:object-type" => "http://activitystrea.ms/schema/1.0/collection",
1921 "href" => "http://activityschema.org/collection/public"]);
1922 XML::addElement($doc, $entry, "mastodon:scope", "public");
1925 foreach ($tags as $tag) {
1926 if ($tag['type'] == Tag::HASHTAG) {
1927 XML::addElement($doc, $entry, "category", "", ["term" => $tag['name']]);
1931 self::getAttachment($doc, $entry, $item);
1933 if ($complete && ($item["id"] > 0)) {
1934 $app = $item["app"];
1939 $attributes = ["local_id" => $item["id"], "source" => $app];
1941 if (isset($parent["id"])) {
1942 $attributes["repeat_of"] = $parent["id"];
1945 if ($item["coord"] != "") {
1946 XML::addElement($doc, $entry, "georss:point", $item["coord"]);
1949 XML::addElement($doc, $entry, "statusnet:notice_info", "", $attributes);
1954 * Creates the XML feed for a given nickname
1956 * Supported filters:
1957 * - activity (default): all the public posts
1958 * - posts: all the public top-level posts
1959 * - comments: all the public replies
1961 * Updates the provided last_update parameter if the result comes from the
1962 * cache or it is empty
1964 * @param string $owner_nick Nickname of the feed owner
1965 * @param string $last_update Date of the last update
1966 * @param integer $max_items Number of maximum items to fetch
1967 * @param string $filter Feed items filter (activity, posts or comments)
1968 * @param boolean $nocache Wether to bypass caching
1970 * @return string XML feed
1971 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1972 * @throws \ImagickException
1974 public static function feed($owner_nick, &$last_update, $max_items = 300, $filter = 'activity', $nocache = false)
1976 $stamp = microtime(true);
1978 $owner = User::getOwnerDataByNick($owner_nick);
1983 $cachekey = "ostatus:feed:" . $owner_nick . ":" . $filter . ":" . $last_update;
1985 $previous_created = $last_update;
1987 // Don't cache when the last item was posted less then 15 minutes ago (Cache duration)
1988 if ((time() - strtotime($owner['last-item'])) < 15*60) {
1989 $result = DI::cache()->get($cachekey);
1990 if (!$nocache && !is_null($result)) {
1991 Logger::info('Feed duration: ' . number_format(microtime(true) - $stamp, 3) . ' - ' . $owner_nick . ' - ' . $filter . ' - ' . $previous_created . ' (cached)');
1992 $last_update = $result['last_update'];
1993 return $result['feed'];
1997 if (!strlen($last_update)) {
1998 $last_update = 'now -30 days';
2001 $check_date = DateTimeFormat::utc($last_update);
2002 $authorid = Contact::getIdForURL($owner["url"]);
2004 $condition = ["`uid` = ? AND `received` > ? AND NOT `deleted`
2005 AND `private` != ? AND `visible` AND `wall` AND `parent-network` IN (?, ?)",
2006 $owner["uid"], $check_date, Item::PRIVATE, Protocol::OSTATUS, Protocol::DFRN];
2008 if ($filter === 'comments') {
2009 $condition[0] .= " AND `object-type` = ? ";
2010 $condition[] = Activity\ObjectType::COMMENT;
2013 if ($owner['contact-type'] != Contact::TYPE_COMMUNITY) {
2014 $condition[0] .= " AND `contact-id` = ? AND `author-id` = ?";
2015 $condition[] = $owner["id"];
2016 $condition[] = $authorid;
2019 $params = ['order' => ['received' => true], 'limit' => $max_items];
2021 if ($filter === 'posts') {
2022 $ret = Post::selectThread([], $condition, $params);
2024 $ret = Post::select([], $condition, $params);
2027 $items = Post::toArray($ret);
2029 $doc = new DOMDocument('1.0', 'utf-8');
2030 $doc->formatOutput = true;
2032 $root = self::addHeader($doc, $owner, $filter);
2034 foreach ($items as $item) {
2035 if (DI::config()->get('system', 'ostatus_debug')) {
2036 $item['body'] .= '🍼';
2039 if (in_array($item["verb"], [Activity::FOLLOW, Activity::O_UNFOLLOW, Activity::LIKE])) {
2043 $entry = self::entry($doc, $item, $owner, false);
2044 $root->appendChild($entry);
2046 if ($last_update < $item['created']) {
2047 $last_update = $item['created'];
2051 $feeddata = trim($doc->saveXML());
2053 $msg = ['feed' => $feeddata, 'last_update' => $last_update];
2054 DI::cache()->set($cachekey, $msg, Duration::QUARTER_HOUR);
2056 Logger::info('Feed duration: ' . number_format(microtime(true) - $stamp, 3) . ' - ' . $owner_nick . ' - ' . $filter . ' - ' . $previous_created);
2062 * Creates the XML for a salmon message
2064 * @param array $item Data of the item that is to be posted
2065 * @param array $owner Contact data of the poster
2067 * @return string XML for the salmon
2068 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2069 * @throws \ImagickException
2071 public static function salmon(array $item, array $owner)
2073 $doc = new DOMDocument('1.0', 'utf-8');
2074 $doc->formatOutput = true;
2076 if (DI::config()->get('system', 'ostatus_debug')) {
2077 $item['body'] .= '🐟';
2080 $entry = self::entry($doc, $item, $owner, true);
2082 $doc->appendChild($entry);
2084 return trim($doc->saveXML());
2088 * Checks if the given contact url does support OStatus
2090 * @param string $url profile url
2092 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2093 * @throws \ImagickException
2095 public static function isSupportedByContactUrl($url)
2097 $probe = Probe::uri($url, Protocol::OSTATUS);
2098 return $probe['network'] == Protocol::OSTATUS;