3 * @copyright Copyright (C) 2010-2021, the Friendica project
5 * @license GNU AGPL version 3 or any later version
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU Affero General Public License as
9 * published by the Free Software Foundation, either version 3 of the
10 * License, or (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU Affero General Public License for more details.
17 * You should have received a copy of the GNU Affero General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
22 namespace Friendica\Protocol;
26 use Friendica\Content\Text\BBCode;
27 use Friendica\Content\Text\HTML;
28 use Friendica\Core\Cache\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\Probe;
42 use Friendica\Util\DateTimeFormat;
43 use Friendica\Util\Images;
44 use Friendica\Util\Proxy as ProxyUtils;
45 use Friendica\Util\Strings;
46 use Friendica\Util\XML;
49 * This class contain functions for the OStatus protocol
53 private static $itemlist;
54 private static $conv_list = [];
59 * @param DOMXPath $xpath The xpath object
60 * @param object $context The xml context of the author details
61 * @param array $importer user record of the importing user
62 * @param array $contact Called by reference, will contain the fetched contact
63 * @param bool $onlyfetch Only fetch the header without updating the contact entries
65 * @return array Array of author related entries for the item
66 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
67 * @throws \ImagickException
69 private static function fetchAuthor(DOMXPath $xpath, $context, array $importer, array &$contact = null, $onlyfetch)
72 $author["author-link"] = XML::getFirstNodeValue($xpath, 'atom:author/atom:uri/text()', $context);
73 $author["author-name"] = XML::getFirstNodeValue($xpath, 'atom:author/atom:name/text()', $context);
74 $addr = XML::getFirstNodeValue($xpath, 'atom:author/atom:email/text()', $context);
76 $aliaslink = $author["author-link"];
78 $alternate_item = $xpath->query("atom:author/atom:link[@rel='alternate']", $context)->item(0);
79 if (is_object($alternate_item)) {
80 foreach ($alternate_item->attributes as $attributes) {
81 if (($attributes->name == "href") && ($attributes->textContent != "")) {
82 $author["author-link"] = $attributes->textContent;
86 $author["author-id"] = Contact::getIdForURL($author["author-link"]);
88 $author['contact-id'] = ($contact['id'] ?? 0) ?: $author['author-id'];
93 This here would be better, but we would get problems with contacts from the statusnet addon
94 This is kept here as a reminder for the future
96 $cid = Contact::getIdForURL($author["author-link"], $importer["uid"]);
98 $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
101 if ($aliaslink != '') {
102 $condition = ["`uid` = ? AND `alias` = ? AND `network` != ? AND `rel` IN (?, ?)",
103 $importer["uid"], $aliaslink, Protocol::STATUSNET,
104 Contact::SHARING, Contact::FRIEND];
105 $contact = DBA::selectFirst('contact', [], $condition);
108 if (!DBA::isResult($contact) && $author["author-link"] != '') {
109 if ($aliaslink == "") {
110 $aliaslink = $author["author-link"];
113 $condition = ["`uid` = ? AND `nurl` IN (?, ?) AND `network` != ? AND `rel` IN (?, ?)",
114 $importer["uid"], Strings::normaliseLink($author["author-link"]), Strings::normaliseLink($aliaslink),
115 Protocol::STATUSNET, Contact::SHARING, Contact::FRIEND];
116 $contact = DBA::selectFirst('contact', [], $condition);
119 if (!DBA::isResult($contact) && ($addr != '')) {
120 $condition = ["`uid` = ? AND `addr` = ? AND `network` != ? AND `rel` IN (?, ?)",
121 $importer["uid"], $addr, Protocol::STATUSNET,
122 Contact::SHARING, Contact::FRIEND];
123 $contact = DBA::selectFirst('contact', [], $condition);
126 if (DBA::isResult($contact)) {
127 if ($contact['blocked']) {
129 } elseif (!empty(APContact::getByURL($contact['url'], false))) {
130 ActivityPub\Receiver::switchContact($contact['id'], $importer['uid'], $contact['url']);
132 $author["contact-id"] = $contact["id"];
136 $avatars = $xpath->query("atom:author/atom:link[@rel='avatar']", $context);
137 foreach ($avatars as $avatar) {
140 foreach ($avatar->attributes as $attributes) {
141 if ($attributes->name == "href") {
142 $href = $attributes->textContent;
144 if ($attributes->name == "width") {
145 $width = $attributes->textContent;
149 $avatarlist[$width] = $href;
152 if (count($avatarlist) > 0) {
154 $author["author-avatar"] = Probe::fixAvatar(current($avatarlist), $author["author-link"]);
157 $displayname = XML::getFirstNodeValue($xpath, 'atom:author/poco:displayName/text()', $context);
158 if ($displayname != "") {
159 $author["author-name"] = $displayname;
162 $author["owner-id"] = $author["author-id"];
164 // Only update the contacts if it is an OStatus contact
165 if (DBA::isResult($contact) && ($contact['id'] > 0) && !$onlyfetch && ($contact["network"] == Protocol::OSTATUS)) {
167 // Update contact data
169 unset($current['name-date']);
171 // This query doesn't seem to work
172 // $value = $xpath->query("atom:link[@rel='salmon']", $context)->item(0)->nodeValue;
174 // $contact["notify"] = $value;
176 // This query doesn't seem to work as well - I hate these queries
177 // $value = $xpath->query("atom:link[@rel='self' and @type='application/atom+xml']", $context)->item(0)->nodeValue;
179 // $contact["poll"] = $value;
181 $contact['url'] = $author["author-link"];
182 $contact['nurl'] = Strings::normaliseLink($contact['url']);
184 $value = XML::getFirstNodeValue($xpath, 'atom:author/atom:uri/text()', $context);
186 $contact["alias"] = $value;
189 $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:displayName/text()', $context);
191 $contact["name"] = $value;
194 $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:preferredUsername/text()', $context);
196 $contact["nick"] = $value;
199 $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:note/text()', $context);
201 $contact["about"] = HTML::toBBCode($value);
204 $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:address/poco:formatted/text()', $context);
206 $contact["location"] = $value;
209 $contact['name-date'] = DateTimeFormat::utcNow();
211 DBA::update('contact', $contact, ['id' => $contact["id"]], $current);
213 if (!empty($author["author-avatar"]) && ($author["author-avatar"] != $current['avatar'])) {
214 Logger::log("Update profile picture for contact ".$contact["id"], Logger::DEBUG);
215 Contact::updateAvatar($contact["id"], $author["author-avatar"]);
218 // Ensure that we are having this contact (with uid=0)
219 $cid = Contact::getIdForURL($aliaslink);
222 $fields = ['url', 'nurl', 'name', 'nick', 'alias', 'about', 'location'];
223 $old_contact = DBA::selectFirst('contact', $fields, ['id' => $cid]);
225 // Update it with the current values
226 $fields = ['url' => $author["author-link"], 'name' => $contact["name"],
227 'nurl' => Strings::normaliseLink($author["author-link"]),
228 'nick' => $contact["nick"], 'alias' => $contact["alias"],
229 'about' => $contact["about"], 'location' => $contact["location"],
230 'success_update' => DateTimeFormat::utcNow(), 'last-update' => DateTimeFormat::utcNow()];
232 DBA::update('contact', $fields, ['id' => $cid], $old_contact);
235 if (!empty($author["author-avatar"])) {
236 Contact::updateAvatar($cid, $author["author-avatar"]);
239 } elseif (empty($contact["network"]) || ($contact["network"] != Protocol::DFRN)) {
247 * Fetches author data from a given XML string
249 * @param string $xml The XML
250 * @param array $importer user record of the importing user
252 * @return array Array of author related entries for the item
253 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
254 * @throws \ImagickException
256 public static function salmonAuthor($xml, array $importer)
262 $doc = new DOMDocument();
263 @$doc->loadXML($xml);
265 $xpath = new DOMXPath($doc);
266 $xpath->registerNamespace('atom', ActivityNamespace::ATOM1);
267 $xpath->registerNamespace('thr', ActivityNamespace::THREAD);
268 $xpath->registerNamespace('georss', ActivityNamespace::GEORSS);
269 $xpath->registerNamespace('activity', ActivityNamespace::ACTIVITY);
270 $xpath->registerNamespace('media', ActivityNamespace::MEDIA);
271 $xpath->registerNamespace('poco', ActivityNamespace::POCO);
272 $xpath->registerNamespace('ostatus', ActivityNamespace::OSTATUS);
273 $xpath->registerNamespace('statusnet', ActivityNamespace::STATUSNET);
275 $contact = ["id" => 0];
277 // Fetch the first author
278 $authordata = $xpath->query('//author')->item(0);
279 $author = self::fetchAuthor($xpath, $authordata, $importer, $contact, true);
284 * Read attributes from element
286 * @param object $element Element object
288 * @return array attributes
290 private static function readAttributes($element)
294 foreach ($element->attributes as $attributes) {
295 $attribute[$attributes->name] = $attributes->textContent;
302 * Imports an XML string containing OStatus elements
304 * @param string $xml The XML
305 * @param array $importer user record of the importing user
306 * @param array $contact contact
307 * @param string $hub Called by reference, returns the fetched hub data
309 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
310 * @throws \ImagickException
312 public static function import($xml, array $importer, array &$contact, &$hub)
314 self::process($xml, $importer, $contact, $hub, false, true, Conversation::PUSH);
318 * Internal feed processing
320 * @param string $xml The XML
321 * @param array $importer user record of the importing user
322 * @param array $contact contact
323 * @param string $hub Called by reference, returns the fetched hub data
324 * @param boolean $stored Is the post fresh imported or from the database?
325 * @param boolean $initialize Is it the leading post so that data has to be initialized?
327 * @return boolean Could the XML be processed?
328 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
329 * @throws \ImagickException
331 private static function process($xml, array $importer, array &$contact = null, &$hub, $stored = false, $initialize = true, $direction = Conversation::UNKNOWN)
334 self::$itemlist = [];
335 self::$conv_list = [];
338 Logger::log('Import OStatus message for user ' . $importer['uid'], Logger::DEBUG);
343 $doc = new DOMDocument();
344 @$doc->loadXML($xml);
346 $xpath = new DOMXPath($doc);
347 $xpath->registerNamespace('atom', ActivityNamespace::ATOM1);
348 $xpath->registerNamespace('thr', ActivityNamespace::THREAD);
349 $xpath->registerNamespace('georss', ActivityNamespace::GEORSS);
350 $xpath->registerNamespace('activity', ActivityNamespace::ACTIVITY);
351 $xpath->registerNamespace('media', ActivityNamespace::MEDIA);
352 $xpath->registerNamespace('poco', ActivityNamespace::POCO);
353 $xpath->registerNamespace('ostatus', ActivityNamespace::OSTATUS);
354 $xpath->registerNamespace('statusnet', ActivityNamespace::STATUSNET);
357 $hub_items = $xpath->query("/atom:feed/atom:link[@rel='hub']")->item(0);
358 if (is_object($hub_items)) {
359 $hub_attributes = $hub_items->attributes;
360 if (is_object($hub_attributes)) {
361 foreach ($hub_attributes as $hub_attribute) {
362 if ($hub_attribute->name == "href") {
363 $hub = $hub_attribute->textContent;
364 Logger::log("Found hub ".$hub, Logger::DEBUG);
371 $header["uid"] = $importer["uid"];
372 $header["network"] = Protocol::OSTATUS;
374 $header["origin"] = 0;
375 $header["gravity"] = GRAVITY_COMMENT;
377 if (!is_object($doc->firstChild) || empty($doc->firstChild->tagName)) {
381 $first_child = $doc->firstChild->tagName;
383 if ($first_child == "feed") {
384 $entries = $xpath->query('/atom:feed/atom:entry');
386 $entries = $xpath->query('/atom:entry');
389 if ($entries->length == 1) {
390 // We reformat the XML to make it better readable
391 $doc2 = new DOMDocument();
392 $doc2->loadXML($xml);
393 $doc2->preserveWhiteSpace = false;
394 $doc2->formatOutput = true;
395 $xml2 = $doc2->saveXML();
397 $header["protocol"] = Conversation::PARCEL_SALMON;
398 $header["source"] = $xml2;
399 $header["direction"] = $direction;
400 } elseif (!$initialize) {
404 // Fetch the first author
405 $authordata = $xpath->query('//author')->item(0);
406 $author = self::fetchAuthor($xpath, $authordata, $importer, $contact, $stored);
408 // Reverse the order of the entries
411 foreach ($entries as $entry) {
412 $entrylist[] = $entry;
415 foreach (array_reverse($entrylist) as $entry) {
417 $authorelement = $xpath->query('/atom:entry/atom:author', $entry);
419 if ($authorelement->length == 0) {
420 $authorelement = $xpath->query('atom:author', $entry);
423 if ($authorelement->length > 0) {
424 $author = self::fetchAuthor($xpath, $entry, $importer, $contact, $stored);
427 $item = array_merge($header, $author);
429 $item["uri"] = XML::getFirstNodeValue($xpath, 'atom:id/text()', $entry);
430 $item['uri-id'] = ItemURI::insert(['uri' => $item['uri']]);
432 $item["verb"] = XML::getFirstNodeValue($xpath, 'activity:verb/text()', $entry);
435 if (in_array($item["verb"], ['qvitter-delete-notice', Activity::DELETE, 'delete'])) {
436 self::deleteNotice($item);
440 if (in_array($item["verb"], [Activity::O_UNFAVOURITE, Activity::UNFAVORITE])) {
441 // Ignore "Unfavorite" message
442 Logger::log("Ignore unfavorite message ".print_r($item, true), Logger::DEBUG);
446 // Deletions come with the same uri, so we check for duplicates after processing deletions
447 if (Post::exists(['uid' => $importer["uid"], 'uri' => $item["uri"]])) {
448 Logger::log('Post with URI '.$item["uri"].' already existed for user '.$importer["uid"].'.', Logger::DEBUG);
451 Logger::log('Processing post with URI '.$item["uri"].' for user '.$importer["uid"].'.', Logger::DEBUG);
454 if ($item["verb"] == Activity::JOIN) {
455 // ignore "Join" messages
456 Logger::log("Ignore join message ".print_r($item, true), Logger::DEBUG);
460 if ($item["verb"] == "http://mastodon.social/schema/1.0/block") {
461 // ignore mastodon "block" messages
462 Logger::log("Ignore block message ".print_r($item, true), Logger::DEBUG);
466 if ($item["verb"] == Activity::FOLLOW) {
467 Contact::addRelationship($importer, $contact, $item);
471 if ($item["verb"] == Activity::O_UNFOLLOW) {
473 Contact::removeFollower($importer, $contact, $item, $dummy);
477 if ($item["verb"] == Activity::FAVORITE) {
478 $orig_uri = $xpath->query("activity:object/atom:id", $entry)->item(0)->nodeValue;
479 Logger::log("Favorite ".$orig_uri." ".print_r($item, true));
481 $item["verb"] = Activity::LIKE;
482 $item["thr-parent"] = $orig_uri;
483 $item["gravity"] = GRAVITY_ACTIVITY;
484 $item["object-type"] = Activity\ObjectType::NOTE;
487 // http://activitystrea.ms/schema/1.0/rsvp-yes
488 if (!in_array($item["verb"], [Activity::POST, Activity::LIKE, Activity::SHARE])) {
489 Logger::log("Unhandled verb ".$item["verb"]." ".print_r($item, true), Logger::DEBUG);
492 self::processPost($xpath, $entry, $item, $importer);
494 if ($initialize && (count(self::$itemlist) > 0)) {
495 if (self::$itemlist[0]['uri'] == self::$itemlist[0]['thr-parent']) {
496 // We will import it everytime, when it is started by our contacts
497 $valid = Contact::isSharingByURL(self::$itemlist[0]['author-link'], self::$itemlist[0]['uid']);
500 // If not, then it depends on this setting
501 $valid = ((self::$itemlist[0]['uid'] == 0) || !DI::pConfig()->get(self::$itemlist[0]['uid'], 'system', 'accept_only_sharer', false));
503 Logger::log("Item with uri ".self::$itemlist[0]['uri']." will be imported due to the system settings.", Logger::DEBUG);
506 Logger::log("Item with uri ".self::$itemlist[0]['uri']." belongs to a contact (".self::$itemlist[0]['contact-id']."). It will be imported.", Logger::DEBUG);
509 // Never post a thread when the only interaction by our contact was a like
511 $verbs = [Activity::POST, Activity::SHARE];
512 foreach (self::$itemlist as $item) {
513 if (in_array($item['verb'], $verbs) && Contact::isSharingByURL($item['author-link'], $item['uid'])) {
518 Logger::log("Item with uri ".self::$itemlist[0]['uri']." will be imported since the thread contains posts or shares.", Logger::DEBUG);
526 $default_contact = 0;
527 for ($key = count(self::$itemlist) - 1; $key >= 0; $key--) {
528 if (empty(self::$itemlist[$key]['contact-id'])) {
529 self::$itemlist[$key]['contact-id'] = $default_contact;
531 $default_contact = $item['contact-id'];
534 foreach (self::$itemlist as $item) {
535 $found = Post::exists(['uid' => $importer["uid"], 'uri' => $item["uri"]]);
537 Logger::log("Item with uri ".$item["uri"]." for user ".$importer["uid"]." already exists.", Logger::DEBUG);
538 } elseif ($item['contact-id'] < 0) {
539 Logger::log("Item with uri ".$item["uri"]." is from a blocked contact.", Logger::DEBUG);
541 $ret = Item::insert($item);
542 Logger::log("Item with uri ".$item["uri"]." for user ".$importer["uid"].' stored. Return value: '.$ret);
546 self::$itemlist = [];
548 Logger::log('Processing done for post with URI '.$item["uri"].' for user '.$importer["uid"].'.', Logger::DEBUG);
554 * Removes notice item from database
556 * @param array $item item
560 private static function deleteNotice(array $item)
562 $condition = ['uid' => $item['uid'], 'author-id' => $item['author-id'], 'uri' => $item['uri']];
563 if (!Post::exists($condition)) {
564 Logger::log('Item from '.$item['author-link'].' with uri '.$item['uri'].' for user '.$item['uid']." wasn't found. We don't delete it.");
568 Item::markForDeletion($condition);
570 Logger::log('Deleted item with uri '.$item['uri'].' for user '.$item['uid']);
574 * Processes the XML for a post
576 * @param DOMXPath $xpath The xpath object
577 * @param object $entry The xml entry that is processed
578 * @param array $item The item array
579 * @param array $importer user record of the importing user
581 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
582 * @throws \ImagickException
584 private static function processPost(DOMXPath $xpath, $entry, array &$item, array $importer)
586 $item["body"] = HTML::toBBCode(XML::getFirstNodeValue($xpath, 'atom:content/text()', $entry));
587 $item["object-type"] = XML::getFirstNodeValue($xpath, 'activity:object-type/text()', $entry);
588 if (($item["object-type"] == Activity\ObjectType::BOOKMARK) || ($item["object-type"] == Activity\ObjectType::EVENT)) {
589 $item["title"] = XML::getFirstNodeValue($xpath, 'atom:title/text()', $entry);
590 $item["body"] = XML::getFirstNodeValue($xpath, 'atom:summary/text()', $entry);
591 } elseif ($item["object-type"] == Activity\ObjectType::QUESTION) {
592 $item["title"] = XML::getFirstNodeValue($xpath, 'atom:title/text()', $entry);
595 $item["created"] = XML::getFirstNodeValue($xpath, 'atom:published/text()', $entry);
596 $item["edited"] = XML::getFirstNodeValue($xpath, 'atom:updated/text()', $entry);
597 $item['conversation-uri'] = XML::getFirstNodeValue($xpath, 'ostatus:conversation/text()', $entry);
599 $conv = $xpath->query('ostatus:conversation', $entry);
600 if (is_object($conv->item(0))) {
601 foreach ($conv->item(0)->attributes as $attributes) {
602 if ($attributes->name == "ref") {
603 $item['conversation-uri'] = $attributes->textContent;
605 if ($attributes->name == "href") {
606 $item['conversation-href'] = $attributes->textContent;
613 $inreplyto = $xpath->query('thr:in-reply-to', $entry);
614 if (is_object($inreplyto->item(0))) {
615 foreach ($inreplyto->item(0)->attributes as $attributes) {
616 if ($attributes->name == "ref") {
617 $item["thr-parent"] = $attributes->textContent;
619 if ($attributes->name == "href") {
620 $related = $attributes->textContent;
625 $georsspoint = $xpath->query('georss:point', $entry);
626 if (!empty($georsspoint) && ($georsspoint->length > 0)) {
627 $item["coord"] = $georsspoint->item(0)->nodeValue;
630 $categories = $xpath->query('atom:category', $entry);
632 foreach ($categories as $category) {
633 foreach ($category->attributes as $attributes) {
634 if ($attributes->name == 'term') {
636 Tag::store($item['uri-id'], Tag::HASHTAG, $attributes->textContent);
645 $links = $xpath->query('atom:link', $entry);
647 $link_data = self::processLinks($links, $item);
648 $self = $link_data['self'];
649 $add_body = $link_data['add_body'];
654 $notice_info = $xpath->query('statusnet:notice_info', $entry);
655 if ($notice_info && ($notice_info->length > 0)) {
656 foreach ($notice_info->item(0)->attributes as $attributes) {
657 if ($attributes->name == "source") {
658 $item["app"] = strip_tags($attributes->textContent);
660 if ($attributes->name == "repeat_of") {
661 $repeat_of = $attributes->textContent;
665 // Is it a repeated post?
666 if (($repeat_of != "") || ($item["verb"] == Activity::SHARE)) {
667 $link_data = self::processRepeatedItem($xpath, $entry, $item, $importer);
668 if (!empty($link_data['add_body'])) {
669 $add_body .= $link_data['add_body'];
673 $item["body"] .= $add_body;
675 Tag::storeFromBody($item['uri-id'], $item['body']);
677 // Mastodon Content Warning
678 if (($item["verb"] == Activity::POST) && $xpath->evaluate('boolean(atom:summary)', $entry)) {
679 $clear_text = XML::getFirstNodeValue($xpath, 'atom:summary/text()', $entry);
680 if (!empty($clear_text)) {
681 $item['content-warning'] = HTML::toBBCode($clear_text);
685 if (($self != '') && empty($item['protocol'])) {
686 self::fetchSelf($self, $item);
689 if (!empty($item["conversation-href"])) {
690 self::fetchConversation($item['conversation-href'], $item['conversation-uri']);
693 if (isset($item["thr-parent"])) {
694 if (!Post::exists(['uid' => $importer["uid"], 'uri' => $item['thr-parent']])) {
695 if ($related != '') {
696 self::fetchRelated($related, $item["thr-parent"], $importer);
699 Logger::log('Reply with URI '.$item["uri"].' already existed for user '.$importer["uid"].'.', Logger::DEBUG);
702 $item["thr-parent"] = $item["uri"];
703 $item["gravity"] = GRAVITY_PARENT;
706 if (($item['author-link'] != '') && !empty($item['protocol'])) {
707 $item = Conversation::insert($item);
710 self::$itemlist[] = $item;
714 * Fetch the conversation for posts
716 * @param string $conversation The link to the conversation
717 * @param string $conversation_uri The conversation in "uri" format
719 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
721 private static function fetchConversation($conversation, $conversation_uri)
723 // Ensure that we only store a conversation once in a process
724 if (isset(self::$conv_list[$conversation])) {
728 self::$conv_list[$conversation] = true;
730 $curlResult = DI::httpRequest()->get($conversation, ['accept_content' => 'application/atom+xml, text/html']);
732 if (!$curlResult->isSuccess() || empty($curlResult->getBody())) {
738 if ($curlResult->inHeader('Content-Type') &&
739 in_array('application/atom+xml', $curlResult->getHeader('Content-Type'))) {
740 $xml = $curlResult->getBody();
744 $doc = new DOMDocument();
745 if (!@$doc->loadHTML($curlResult->getBody())) {
748 $xpath = new DOMXPath($doc);
750 $links = $xpath->query('//link');
753 foreach ($links as $link) {
754 $attribute = self::readAttributes($link);
755 if (($attribute['rel'] == 'alternate') && ($attribute['type'] == 'application/atom+xml')) {
756 $file = $attribute['href'];
760 $conversation_atom = DI::httpRequest()->get($attribute['href']);
762 if ($conversation_atom->isSuccess()) {
763 $xml = $conversation_atom->getBody();
773 self::storeConversation($xml, $conversation, $conversation_uri);
777 * Store a feed in several conversation entries
779 * @param string $xml The feed
780 * @param string $conversation conversation
781 * @param string $conversation_uri conversation uri
785 private static function storeConversation($xml, $conversation = '', $conversation_uri = '')
787 $doc = new DOMDocument();
788 @$doc->loadXML($xml);
790 $xpath = new DOMXPath($doc);
791 $xpath->registerNamespace('atom', ActivityNamespace::ATOM1);
792 $xpath->registerNamespace('thr', ActivityNamespace::THREAD);
793 $xpath->registerNamespace('ostatus', ActivityNamespace::OSTATUS);
795 $entries = $xpath->query('/atom:feed/atom:entry');
797 // Now store the entries
798 foreach ($entries as $entry) {
799 $doc2 = new DOMDocument();
800 $doc2->preserveWhiteSpace = false;
801 $doc2->formatOutput = true;
805 $conv_data['protocol'] = Conversation::PARCEL_SPLIT_CONVERSATION;
806 $conv_data['direction'] = Conversation::PULL;
807 $conv_data['network'] = Protocol::OSTATUS;
808 $conv_data['uri'] = XML::getFirstNodeValue($xpath, 'atom:id/text()', $entry);
810 $inreplyto = $xpath->query('thr:in-reply-to', $entry);
811 if (is_object($inreplyto->item(0))) {
812 foreach ($inreplyto->item(0)->attributes as $attributes) {
813 if ($attributes->name == "ref") {
814 $conv_data['reply-to-uri'] = $attributes->textContent;
819 $conv_data['conversation-uri'] = XML::getFirstNodeValue($xpath, 'ostatus:conversation/text()', $entry);
821 $conv = $xpath->query('ostatus:conversation', $entry);
822 if (is_object($conv->item(0))) {
823 foreach ($conv->item(0)->attributes as $attributes) {
824 if ($attributes->name == "ref") {
825 $conv_data['conversation-uri'] = $attributes->textContent;
827 if ($attributes->name == "href") {
828 $conv_data['conversation-href'] = $attributes->textContent;
833 if ($conversation != '') {
834 $conv_data['conversation-uri'] = $conversation;
837 if ($conversation_uri != '') {
838 $conv_data['conversation-uri'] = $conversation_uri;
841 $entry = $doc2->importNode($entry, true);
843 $doc2->appendChild($entry);
845 $conv_data['source'] = $doc2->saveXML();
847 Logger::log('Store conversation data for uri '.$conv_data['uri'], Logger::DEBUG);
848 Conversation::insert($conv_data);
853 * Fetch the own post so that it can be stored later
855 * We want to store the original data for later processing.
856 * This function is meant for cases where we process a feed with multiple entries.
857 * In that case we need to fetch the single posts here.
859 * @param string $self The link to the self item
860 * @param array $item The item array
862 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
864 private static function fetchSelf($self, array &$item)
866 $condition = ['item-uri' => $self, 'protocol' => [Conversation::PARCEL_DFRN,
867 Conversation::PARCEL_DIASPORA_DFRN, Conversation::PARCEL_LEGACY_DFRN,
868 Conversation::PARCEL_LOCAL_DFRN, Conversation::PARCEL_DIRECT, Conversation::PARCEL_SALMON]];
869 if (DBA::exists('conversation', $condition)) {
870 Logger::log('Conversation '.$item['uri'].' is already stored.', Logger::DEBUG);
874 $curlResult = DI::httpRequest()->get($self);
876 if (!$curlResult->isSuccess()) {
880 // We reformat the XML to make it better readable
881 $doc = new DOMDocument();
882 $doc->loadXML($curlResult->getBody());
883 $doc->preserveWhiteSpace = false;
884 $doc->formatOutput = true;
885 $xml = $doc->saveXML();
887 $item["protocol"] = Conversation::PARCEL_SALMON;
888 $item["source"] = $xml;
889 $item["direction"] = Conversation::PULL;
891 Logger::log('Conversation '.$item['uri'].' is now fetched.', Logger::DEBUG);
895 * Fetch related posts and processes them
897 * @param string $related The link to the related item
898 * @param string $related_uri The related item in "uri" format
899 * @param array $importer user record of the importing user
901 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
902 * @throws \ImagickException
904 private static function fetchRelated($related, $related_uri, $importer)
906 $condition = ['item-uri' => $related_uri, 'protocol' => [Conversation::PARCEL_DFRN,
907 Conversation::PARCEL_DIASPORA_DFRN, Conversation::PARCEL_LEGACY_DFRN,
908 Conversation::PARCEL_LOCAL_DFRN, Conversation::PARCEL_DIRECT, Conversation::PARCEL_SALMON]];
909 $conversation = DBA::selectFirst('conversation', ['source', 'protocol'], $condition);
910 if (DBA::isResult($conversation)) {
912 $xml = $conversation['source'];
913 if (self::process($xml, $importer, $contact, $hub, $stored, false, Conversation::PULL)) {
914 Logger::log('Got valid cached XML for URI '.$related_uri, Logger::DEBUG);
917 if ($conversation['protocol'] == Conversation::PARCEL_SALMON) {
918 Logger::log('Delete invalid cached XML for URI '.$related_uri, Logger::DEBUG);
919 DBA::delete('conversation', ['item-uri' => $related_uri]);
924 $curlResult = DI::httpRequest()->get($related, ['accept_content' => 'application/atom+xml, text/html']);
926 if (!$curlResult->isSuccess() || empty($curlResult->getBody())) {
932 if ($curlResult->inHeader('Content-Type') &&
933 in_array('application/atom+xml', $curlResult->getHeader('Content-Type'))) {
934 Logger::log('Directly fetched XML for URI ' . $related_uri, Logger::DEBUG);
935 $xml = $curlResult->getBody();
939 $doc = new DOMDocument();
940 if (!@$doc->loadHTML($curlResult->getBody())) {
943 $xpath = new DOMXPath($doc);
947 $links = $xpath->query('//link');
949 foreach ($links as $link) {
950 $attribute = self::readAttributes($link);
951 if (($attribute['rel'] == 'alternate') && ($attribute['type'] == 'application/atom+xml')) {
952 $atom_file = $attribute['href'];
955 if ($atom_file != '') {
956 $curlResult = DI::httpRequest()->get($atom_file);
958 if ($curlResult->isSuccess()) {
959 Logger::log('Fetched XML for URI ' . $related_uri, Logger::DEBUG);
960 $xml = $curlResult->getBody();
966 // Workaround for older GNU Social servers
967 if (($xml == '') && strstr($related, '/notice/')) {
968 $curlResult = DI::httpRequest()->get(str_replace('/notice/', '/api/statuses/show/', $related) . '.atom');
970 if ($curlResult->isSuccess()) {
971 Logger::log('GNU Social workaround to fetch XML for URI ' . $related_uri, Logger::DEBUG);
972 $xml = $curlResult->getBody();
976 // Even more worse workaround for GNU Social ;-)
978 $related_guess = self::convertHref($related_uri);
979 $curlResult = DI::httpRequest()->get(str_replace('/notice/', '/api/statuses/show/', $related_guess) . '.atom');
981 if ($curlResult->isSuccess()) {
982 Logger::log('GNU Social workaround 2 to fetch XML for URI ' . $related_uri, Logger::DEBUG);
983 $xml = $curlResult->getBody();
987 // Finally we take the data that we fetched from "ostatus:conversation"
989 $condition = ['item-uri' => $related_uri, 'protocol' => Conversation::PARCEL_SPLIT_CONVERSATION];
990 $conversation = DBA::selectFirst('conversation', ['source'], $condition);
991 if (DBA::isResult($conversation)) {
993 Logger::log('Got cached XML from conversation for URI '.$related_uri, Logger::DEBUG);
994 $xml = $conversation['source'];
999 self::process($xml, $importer, $contact, $hub, $stored, false, Conversation::PULL);
1001 Logger::log("XML couldn't be fetched for URI: ".$related_uri." - href: ".$related, Logger::DEBUG);
1007 * Processes the XML for a repeated post
1009 * @param DOMXPath $xpath The xpath object
1010 * @param object $entry The xml entry that is processed
1011 * @param array $item The item array
1012 * @param array $importer user record of the importing user
1014 * @return array with data from links
1015 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1016 * @throws \ImagickException
1018 private static function processRepeatedItem(DOMXPath $xpath, $entry, array &$item, array $importer)
1020 $activityobject = $xpath->query('activity:object', $entry)->item(0);
1022 if (!is_object($activityobject)) {
1028 $orig_uri = XML::getFirstNodeValue($xpath, 'atom:id/text()', $activityobject);
1030 $links = $xpath->query("atom:link", $activityobject);
1032 $link_data = self::processLinks($links, $item);
1035 $orig_body = XML::getFirstNodeValue($xpath, 'atom:content/text()', $activityobject);
1036 $orig_created = XML::getFirstNodeValue($xpath, 'atom:published/text()', $activityobject);
1037 $orig_edited = XML::getFirstNodeValue($xpath, 'atom:updated/text()', $activityobject);
1039 $orig_author = self::fetchAuthor($xpath, $activityobject, $importer, $dummy, false);
1041 $item["author-name"] = $orig_author["author-name"];
1042 $item["author-link"] = $orig_author["author-link"];
1043 $item["author-id"] = $orig_author["author-id"];
1045 $item["body"] = HTML::toBBCode($orig_body);
1046 $item["created"] = $orig_created;
1047 $item["edited"] = $orig_edited;
1049 $item["uri"] = $orig_uri;
1051 $item["verb"] = XML::getFirstNodeValue($xpath, 'activity:verb/text()', $activityobject);
1053 $item["object-type"] = XML::getFirstNodeValue($xpath, 'activity:object-type/text()', $activityobject);
1055 // Mastodon Content Warning
1056 if (($item["verb"] == Activity::POST) && $xpath->evaluate('boolean(atom:summary)', $activityobject)) {
1057 $clear_text = XML::getFirstNodeValue($xpath, 'atom:summary/text()', $activityobject);
1058 if (!empty($clear_text)) {
1059 $item['content-warning'] = HTML::toBBCode($clear_text);
1063 $inreplyto = $xpath->query('thr:in-reply-to', $activityobject);
1064 if (is_object($inreplyto->item(0))) {
1065 foreach ($inreplyto->item(0)->attributes as $attributes) {
1066 if ($attributes->name == "ref") {
1067 $item["thr-parent"] = $attributes->textContent;
1076 * Processes links in the XML
1078 * @param object $links The xml data that contain links
1079 * @param array $item The item array
1081 * @return array with data from the links
1083 private static function processLinks($links, array &$item)
1085 $link_data = ['add_body' => '', 'self' => ''];
1087 foreach ($links as $link) {
1088 $attribute = self::readAttributes($link);
1090 if (!empty($attribute['rel']) && !empty($attribute['href'])) {
1091 switch ($attribute['rel']) {
1093 $item["plink"] = $attribute['href'];
1094 if (($item["object-type"] == Activity\ObjectType::QUESTION)
1095 || ($item["object-type"] == Activity\ObjectType::EVENT)
1097 Post\Media::insert(['uri-id' => $item['uri-id'], 'type' => Post\Media::UNKNOWN,
1098 'url' => $attribute['href'], 'mimetype' => $attribute['type'] ?? null,
1099 'size' => $attribute['length'] ?? null, 'description' => $attribute['title'] ?? null]);
1102 case "ostatus:conversation":
1103 $link_data['conversation'] = $attribute['href'];
1104 $item['conversation-href'] = $link_data['conversation'];
1105 if (!isset($item['conversation-uri'])) {
1106 $item['conversation-uri'] = $item['conversation-href'];
1110 $filetype = strtolower(substr($attribute['type'], 0, strpos($attribute['type'], '/')));
1111 if ($filetype == 'image') {
1112 $link_data['add_body'] .= "\n[img]".$attribute['href'].'[/img]';
1114 Post\Media::insert(['uri-id' => $item['uri-id'], 'type' => Post\Media::DOCUMENT,
1115 'url' => $attribute['href'], 'mimetype' => $attribute['type'],
1116 'size' => $attribute['length'] ?? null, 'description' => $attribute['title'] ?? null]);
1120 if ($item["object-type"] != Activity\ObjectType::BOOKMARK) {
1121 if (!isset($item["thr-parent"])) {
1122 $item["thr-parent"] = $attribute['href'];
1124 $link_data['related'] = $attribute['href'];
1126 Post\Media::insert(['uri-id' => $item['uri-id'], 'type' => Post\Media::UNKNOWN,
1127 'url' => $attribute['href'], 'mimetype' => $attribute['type'] ?? null,
1128 'size' => $attribute['length'] ?? null, 'description' => $attribute['title'] ?? null]);
1132 if (empty($item["plink"])) {
1133 $item["plink"] = $attribute['href'];
1135 $link_data['self'] = $attribute['href'];
1144 * Create an url out of an uri
1146 * @param string $href URI in the format "parameter1:parameter1:..."
1148 * @return string URL in the format http(s)://....
1150 private static function convertHref($href)
1152 $elements = explode(":", $href);
1154 if ((count($elements) <= 2) || ($elements[0] != "tag")) {
1158 $server = explode(",", $elements[1]);
1159 $conversation = explode("=", $elements[2]);
1161 if ((count($elements) == 4) && ($elements[2] == "post")) {
1162 return "http://".$server[0]."/notice/".$elements[3];
1165 if ((count($conversation) != 2) || ($conversation[1] =="")) {
1168 if ($elements[3] == "objectType=thread") {
1169 return "http://".$server[0]."/conversation/".$conversation[1];
1171 return "http://".$server[0]."/notice/".$conversation[1];
1176 * Checks if the current post is a reshare
1178 * @param array $item The item array of thw post
1180 * @return string The guid if the post is a reshare
1182 public static function getResharedGuid(array $item)
1184 $reshared = Item::getShareArray($item);
1185 if (empty($reshared['guid']) || !empty($reshared['comment'])) {
1189 return $reshared['guid'];
1193 * Cleans the body of a post if it contains picture links
1195 * @param string $body The body
1197 * @return string The cleaned body
1198 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1200 public static function formatPicturePost($body, $uriid)
1202 $siteinfo = BBCode::getAttachedData($body);
1204 if (($siteinfo["type"] == "photo") && (!empty($siteinfo["preview"]) || !empty($siteinfo["image"]))) {
1205 if (isset($siteinfo["preview"])) {
1206 $preview = $siteinfo["preview"];
1208 $preview = $siteinfo["image"];
1211 // Is it a remote picture? Then make a smaller preview here
1212 $preview = Post\Link::getByLink($uriid, $preview, ProxyUtils::SIZE_SMALL);
1214 // Is it a local picture? Then make it smaller here
1215 $preview = str_replace(["-0.jpg", "-0.png"], ["-2.jpg", "-2.png"], $preview);
1216 $preview = str_replace(["-1.jpg", "-1.png"], ["-2.jpg", "-2.png"], $preview);
1218 if (isset($siteinfo["url"])) {
1219 $url = $siteinfo["url"];
1221 $url = $siteinfo["image"];
1224 $body = trim($siteinfo["text"])." [url]".$url."[/url]\n[img]".$preview."[/img]";
1231 * Adds the header elements to the XML document
1233 * @param DOMDocument $doc XML document
1234 * @param array $owner Contact data of the poster
1235 * @param string $filter The related feed filter (activity, posts or comments)
1237 * @return object header root element
1238 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1240 private static function addHeader(DOMDocument $doc, array $owner, $filter)
1242 $root = $doc->createElementNS(ActivityNamespace::ATOM1, 'feed');
1243 $doc->appendChild($root);
1245 $root->setAttribute("xmlns:thr", ActivityNamespace::THREAD);
1246 $root->setAttribute("xmlns:georss", ActivityNamespace::GEORSS);
1247 $root->setAttribute("xmlns:activity", ActivityNamespace::ACTIVITY);
1248 $root->setAttribute("xmlns:media", ActivityNamespace::MEDIA);
1249 $root->setAttribute("xmlns:poco", ActivityNamespace::POCO);
1250 $root->setAttribute("xmlns:ostatus", ActivityNamespace::OSTATUS);
1251 $root->setAttribute("xmlns:statusnet", ActivityNamespace::STATUSNET);
1252 $root->setAttribute("xmlns:mastodon", ActivityNamespace::MASTODON);
1255 $selfUri = '/feed/' . $owner["nick"] . '/';
1258 $title = DI::l10n()->t('%s\'s timeline', $owner['name']);
1259 $selfUri .= $filter;
1262 $title = DI::l10n()->t('%s\'s posts', $owner['name']);
1265 $title = DI::l10n()->t('%s\'s comments', $owner['name']);
1266 $selfUri .= $filter;
1270 $selfUri = "/dfrn_poll/" . $owner["nick"];
1272 $attributes = ["uri" => "https://friendi.ca", "version" => FRIENDICA_VERSION . "-" . DB_UPDATE_VERSION];
1273 XML::addElement($doc, $root, "generator", FRIENDICA_PLATFORM, $attributes);
1274 XML::addElement($doc, $root, "id", DI::baseUrl() . "/profile/" . $owner["nick"]);
1275 XML::addElement($doc, $root, "title", $title);
1276 XML::addElement($doc, $root, "subtitle", sprintf("Updates from %s on %s", $owner["name"], DI::config()->get('config', 'sitename')));
1277 XML::addElement($doc, $root, "logo", Contact::getAvatarUrlForId($owner['id'], ProxyUtils::SIZE_SMALL, $owner['updated']));
1278 XML::addElement($doc, $root, "updated", DateTimeFormat::utcNow(DateTimeFormat::ATOM));
1280 $author = self::addAuthor($doc, $owner, true);
1281 $root->appendChild($author);
1283 $attributes = ["href" => $owner["url"], "rel" => "alternate", "type" => "text/html"];
1284 XML::addElement($doc, $root, "link", "", $attributes);
1286 /// @TODO We have to find out what this is
1287 /// $attributes = array("href" => DI::baseUrl()."/sup",
1288 /// "rel" => "http://api.friendfeed.com/2008/03#sup",
1289 /// "type" => "application/json");
1290 /// XML::addElement($doc, $root, "link", "", $attributes);
1292 self::hublinks($doc, $root, $owner["nick"]);
1294 $attributes = ["href" => DI::baseUrl() . "/salmon/" . $owner["nick"], "rel" => "salmon"];
1295 XML::addElement($doc, $root, "link", "", $attributes);
1297 $attributes = ["href" => DI::baseUrl() . "/salmon/" . $owner["nick"], "rel" => "http://salmon-protocol.org/ns/salmon-replies"];
1298 XML::addElement($doc, $root, "link", "", $attributes);
1300 $attributes = ["href" => DI::baseUrl() . "/salmon/" . $owner["nick"], "rel" => "http://salmon-protocol.org/ns/salmon-mention"];
1301 XML::addElement($doc, $root, "link", "", $attributes);
1303 $attributes = ["href" => DI::baseUrl() . $selfUri, "rel" => "self", "type" => "application/atom+xml"];
1304 XML::addElement($doc, $root, "link", "", $attributes);
1306 if ($owner['contact-type'] == Contact::TYPE_COMMUNITY) {
1307 $condition = ['uid' => $owner['uid'], 'self' => false, 'pending' => false,
1308 'archive' => false, 'hidden' => false, 'blocked' => false];
1309 $members = DBA::count('contact', $condition);
1310 XML::addElement($doc, $root, "statusnet:group_info", "", ["member_count" => $members]);
1317 * Add the link to the push hubs to the XML document
1319 * @param DOMDocument $doc XML document
1320 * @param object $root XML root element where the hub links are added
1321 * @param object $nick nick
1323 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1325 public static function hublinks(DOMDocument $doc, $root, $nick)
1327 $h = DI::baseUrl() . '/pubsubhubbub/'.$nick;
1328 XML::addElement($doc, $root, "link", "", ["href" => $h, "rel" => "hub"]);
1332 * Adds attachment data to the XML document
1334 * @param DOMDocument $doc XML document
1335 * @param object $root XML root element where the hub links are added
1336 * @param array $item Data of the item that is to be posted
1338 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1340 public static function getAttachment(DOMDocument $doc, $root, $item)
1342 $siteinfo = BBCode::getAttachedData($item["body"]);
1344 switch ($siteinfo["type"]) {
1346 if (!empty($siteinfo["image"])) {
1347 $imgdata = Images::getInfoFromURLCached($siteinfo["image"]);
1349 $attributes = ["rel" => "enclosure",
1350 "href" => $siteinfo["image"],
1351 "type" => $imgdata["mime"],
1352 "length" => intval($imgdata["size"])];
1353 XML::addElement($doc, $root, "link", "", $attributes);
1358 $attributes = ["rel" => "enclosure",
1359 "href" => $siteinfo["url"],
1360 "type" => "text/html; charset=UTF-8",
1362 "title" => ($siteinfo["title"] ?? '') ?: $siteinfo["url"],
1364 XML::addElement($doc, $root, "link", "", $attributes);
1370 if (!DI::config()->get('system', 'ostatus_not_attach_preview') && ($siteinfo["type"] != "photo") && isset($siteinfo["image"])) {
1371 $imgdata = Images::getInfoFromURLCached($siteinfo["image"]);
1373 $attributes = ["rel" => "enclosure",
1374 "href" => $siteinfo["image"],
1375 "type" => $imgdata["mime"],
1376 "length" => intval($imgdata["size"])];
1378 XML::addElement($doc, $root, "link", "", $attributes);
1382 foreach (Post\Media::getByURIId($item['uri-id'], [Post\Media::DOCUMENT, Post\Media::TORRENT, Post\Media::UNKNOWN]) as $attachment) {
1383 $attributes = ['rel' => 'enclosure',
1384 'href' => $attachment['url'],
1385 'type' => $attachment['mimetype']];
1387 if (!empty($attachment['size'])) {
1388 $attributes['length'] = intval($attachment['size']);
1390 if (!empty($attachment['description'])) {
1391 $attributes['title'] = $attachment['description'];
1394 XML::addElement($doc, $root, 'link', '', $attributes);
1399 * Adds the author element to the XML document
1401 * @param DOMDocument $doc XML document
1402 * @param array $owner Contact data of the poster
1403 * @param bool $show_profile Whether to show profile
1405 * @return \DOMElement author element
1406 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1408 private static function addAuthor(DOMDocument $doc, array $owner, $show_profile = true)
1410 $profile = DBA::selectFirst('profile', ['homepage', 'publish'], ['uid' => $owner['uid']]);
1411 $author = $doc->createElement("author");
1412 XML::addElement($doc, $author, "id", $owner["url"]);
1413 if ($owner['contact-type'] == Contact::TYPE_COMMUNITY) {
1414 XML::addElement($doc, $author, "activity:object-type", Activity\ObjectType::GROUP);
1416 XML::addElement($doc, $author, "activity:object-type", Activity\ObjectType::PERSON);
1419 XML::addElement($doc, $author, "uri", $owner["url"]);
1420 XML::addElement($doc, $author, "name", $owner["nick"]);
1421 XML::addElement($doc, $author, "email", $owner["addr"]);
1422 if ($show_profile) {
1423 XML::addElement($doc, $author, "summary", BBCode::convertForUriId($owner['uri-id'], $owner["about"], BBCode::OSTATUS));
1426 $attributes = ["rel" => "alternate", "type" => "text/html", "href" => $owner["url"]];
1427 XML::addElement($doc, $author, "link", "", $attributes);
1431 "type" => "image/jpeg", // To-Do?
1432 "media:width" => ProxyUtils::PIXEL_SMALL,
1433 "media:height" => ProxyUtils::PIXEL_SMALL,
1434 "href" => Contact::getAvatarUrlForId($owner['id'], ProxyUtils::SIZE_SMALL, $owner['updated'])];
1435 XML::addElement($doc, $author, "link", "", $attributes);
1437 if (isset($owner["thumb"])) {
1440 "type" => "image/jpeg", // To-Do?
1441 "media:width" => ProxyUtils::PIXEL_THUMB,
1442 "media:height" => ProxyUtils::PIXEL_THUMB,
1443 "href" => Contact::getAvatarUrlForId($owner['id'], ProxyUtils::SIZE_THUMB, $owner['updated'])];
1444 XML::addElement($doc, $author, "link", "", $attributes);
1447 XML::addElement($doc, $author, "poco:preferredUsername", $owner["nick"]);
1448 XML::addElement($doc, $author, "poco:displayName", $owner["name"]);
1449 if ($show_profile) {
1450 XML::addElement($doc, $author, "poco:note", BBCode::convertForUriId($owner['uri-id'], $owner["about"], BBCode::OSTATUS));
1452 if (trim($owner["location"]) != "") {
1453 $element = $doc->createElement("poco:address");
1454 XML::addElement($doc, $element, "poco:formatted", $owner["location"]);
1455 $author->appendChild($element);
1459 if (DBA::isResult($profile) && !$show_profile) {
1460 if (trim($profile["homepage"]) != "") {
1461 $urls = $doc->createElement("poco:urls");
1462 XML::addElement($doc, $urls, "poco:type", "homepage");
1463 XML::addElement($doc, $urls, "poco:value", $profile["homepage"]);
1464 XML::addElement($doc, $urls, "poco:primary", "true");
1465 $author->appendChild($urls);
1468 XML::addElement($doc, $author, "followers", "", ["url" => DI::baseUrl() . "/profile/" . $owner["nick"] . "/contacts/followers"]);
1469 XML::addElement($doc, $author, "statusnet:profile_info", "", ["local_id" => $owner["uid"]]);
1471 if ($profile["publish"]) {
1472 XML::addElement($doc, $author, "mastodon:scope", "public");
1480 * @TODO Picture attachments should look like this:
1481 * <a href="https://status.pirati.ca/attachment/572819" title="https://status.pirati.ca/file/heluecht-20151202T222602-rd3u49p.gif"
1482 * class="attachment thumbnail" id="attachment-572819" rel="nofollow external">https://status.pirati.ca/attachment/572819</a>
1486 * Returns the given activity if present - otherwise returns the "post" activity
1488 * @param array $item Data of the item that is to be posted
1490 * @return string activity
1492 public static function constructVerb(array $item)
1494 if (!empty($item['verb'])) {
1495 return $item['verb'];
1498 return Activity::POST;
1502 * Returns the given object type if present - otherwise returns the "note" object type
1504 * @param array $item Data of the item that is to be posted
1506 * @return string Object type
1508 private static function constructObjecttype(array $item)
1510 if (!empty($item['object-type']) && in_array($item['object-type'], [Activity\ObjectType::NOTE, Activity\ObjectType::COMMENT])) {
1511 return $item['object-type'];
1514 return Activity\ObjectType::NOTE;
1518 * Adds an entry element to the XML document
1520 * @param DOMDocument $doc XML document
1521 * @param array $item Data of the item that is to be posted
1522 * @param array $owner Contact data of the poster
1523 * @param bool $toplevel optional default false
1525 * @return \DOMElement Entry element
1526 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1527 * @throws \ImagickException
1529 private static function entry(DOMDocument $doc, array $item, array $owner, $toplevel = false)
1533 $repeated_guid = self::getResharedGuid($item);
1534 if ($repeated_guid != "") {
1535 $xml = self::reshareEntry($doc, $item, $owner, $repeated_guid, $toplevel);
1542 if ($item["verb"] == Activity::LIKE) {
1543 return self::likeEntry($doc, $item, $owner, $toplevel);
1544 } elseif (in_array($item["verb"], [Activity::FOLLOW, Activity::O_UNFOLLOW])) {
1545 return self::followEntry($doc, $item, $owner, $toplevel);
1547 return self::noteEntry($doc, $item, $owner, $toplevel);
1552 * Adds a source entry to the XML document
1554 * @param DOMDocument $doc XML document
1555 * @param array $contact Array of the contact that is added
1557 * @return \DOMElement Source element
1558 * @throws \Exception
1560 private static function sourceEntry(DOMDocument $doc, array $contact)
1562 $source = $doc->createElement("source");
1563 XML::addElement($doc, $source, "id", $contact["poll"]);
1564 XML::addElement($doc, $source, "title", $contact["name"]);
1565 XML::addElement($doc, $source, "link", "", ["rel" => "alternate", "type" => "text/html", "href" => $contact["alias"]]);
1566 XML::addElement($doc, $source, "link", "", ["rel" => "self", "type" => "application/atom+xml", "href" => $contact["poll"]]);
1567 XML::addElement($doc, $source, "icon", $contact["photo"]);
1568 XML::addElement($doc, $source, "updated", DateTimeFormat::utc($contact["success_update"]."+00:00", DateTimeFormat::ATOM));
1574 * Adds an entry element with reshared content
1576 * @param DOMDocument $doc XML document
1577 * @param array $item Data of the item that is to be posted
1578 * @param array $owner Contact data of the poster
1579 * @param string $repeated_guid guid
1580 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1582 * @return bool Entry element
1583 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1584 * @throws \ImagickException
1586 private static function reshareEntry(DOMDocument $doc, array $item, array $owner, $repeated_guid, $toplevel)
1588 if (($item['gravity'] != GRAVITY_PARENT) && (Strings::normaliseLink($item["author-link"]) != Strings::normaliseLink($owner["url"]))) {
1589 Logger::log("OStatus entry is from author ".$owner["url"]." - not from ".$item["author-link"].". Quitting.", Logger::DEBUG);
1592 $entry = self::entryHeader($doc, $owner, $item, $toplevel);
1594 $condition = ['uid' => $owner["uid"], 'guid' => $repeated_guid, 'private' => [Item::PUBLIC, Item::UNLISTED],
1595 'network' => [Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS]];
1596 $repeated_item = Post::selectFirst([], $condition);
1597 if (!DBA::isResult($repeated_item)) {
1601 $contact = Contact::getByURL($repeated_item['author-link']) ?: $owner;
1603 $title = $owner["nick"]." repeated a notice by ".$contact["nick"];
1605 self::entryContent($doc, $entry, $item, $owner, $title, Activity::SHARE, false);
1607 $as_object = $doc->createElement("activity:object");
1609 XML::addElement($doc, $as_object, "activity:object-type", ActivityNamespace::ACTIVITY_SCHEMA . "activity");
1611 self::entryContent($doc, $as_object, $repeated_item, $owner, "", "", false);
1613 $author = self::addAuthor($doc, $contact, false);
1614 $as_object->appendChild($author);
1616 $as_object2 = $doc->createElement("activity:object");
1618 XML::addElement($doc, $as_object2, "activity:object-type", self::constructObjecttype($repeated_item));
1620 $title = sprintf("New comment by %s", $contact["nick"]);
1622 self::entryContent($doc, $as_object2, $repeated_item, $owner, $title);
1624 $as_object->appendChild($as_object2);
1626 self::entryFooter($doc, $as_object, $item, $owner, false);
1628 $source = self::sourceEntry($doc, $contact);
1630 $as_object->appendChild($source);
1632 $entry->appendChild($as_object);
1634 self::entryFooter($doc, $entry, $item, $owner, true);
1640 * Adds an entry element with a "like"
1642 * @param DOMDocument $doc XML document
1643 * @param array $item Data of the item that is to be posted
1644 * @param array $owner Contact data of the poster
1645 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1647 * @return \DOMElement Entry element with "like"
1648 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1649 * @throws \ImagickException
1651 private static function likeEntry(DOMDocument $doc, array $item, array $owner, $toplevel)
1653 if (($item['gravity'] != GRAVITY_PARENT) && (Strings::normaliseLink($item["author-link"]) != Strings::normaliseLink($owner["url"]))) {
1654 Logger::log("OStatus entry is from author ".$owner["url"]." - not from ".$item["author-link"].". Quitting.", Logger::DEBUG);
1657 $entry = self::entryHeader($doc, $owner, $item, $toplevel);
1659 $verb = ActivityNamespace::ACTIVITY_SCHEMA . "favorite";
1660 self::entryContent($doc, $entry, $item, $owner, "Favorite", $verb, false);
1662 $parent = Post::selectFirst([], ['uri' => $item["thr-parent"], 'uid' => $item["uid"]]);
1663 if (DBA::isResult($parent)) {
1664 $as_object = $doc->createElement("activity:object");
1666 XML::addElement($doc, $as_object, "activity:object-type", self::constructObjecttype($parent));
1668 self::entryContent($doc, $as_object, $parent, $owner, "New entry");
1670 $entry->appendChild($as_object);
1673 self::entryFooter($doc, $entry, $item, $owner);
1679 * Adds the person object element to the XML document
1681 * @param DOMDocument $doc XML document
1682 * @param array $owner Contact data of the poster
1683 * @param array $contact Contact data of the target
1685 * @return object author element
1687 private static function addPersonObject(DOMDocument $doc, array $owner, array $contact)
1689 $object = $doc->createElement("activity:object");
1690 XML::addElement($doc, $object, "activity:object-type", Activity\ObjectType::PERSON);
1692 if ($contact['network'] == Protocol::PHANTOM) {
1693 XML::addElement($doc, $object, "id", $contact['url']);
1697 XML::addElement($doc, $object, "id", $contact["alias"]);
1698 XML::addElement($doc, $object, "title", $contact["nick"]);
1700 $attributes = ["rel" => "alternate", "type" => "text/html", "href" => $contact["url"]];
1701 XML::addElement($doc, $object, "link", "", $attributes);
1705 "type" => "image/jpeg", // To-Do?
1706 "media:width" => 300,
1707 "media:height" => 300,
1708 "href" => $contact["photo"]];
1709 XML::addElement($doc, $object, "link", "", $attributes);
1711 XML::addElement($doc, $object, "poco:preferredUsername", $contact["nick"]);
1712 XML::addElement($doc, $object, "poco:displayName", $contact["name"]);
1714 if (trim($contact["location"]) != "") {
1715 $element = $doc->createElement("poco:address");
1716 XML::addElement($doc, $element, "poco:formatted", $contact["location"]);
1717 $object->appendChild($element);
1724 * Adds a follow/unfollow entry element
1726 * @param DOMDocument $doc XML document
1727 * @param array $item Data of the follow/unfollow message
1728 * @param array $owner Contact data of the poster
1729 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1731 * @return \DOMElement Entry element
1732 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1733 * @throws \ImagickException
1735 private static function followEntry(DOMDocument $doc, array $item, array $owner, $toplevel)
1737 $item["id"] = $item['parent'] = 0;
1738 $item["created"] = $item["edited"] = date("c");
1739 $item["private"] = Item::PRIVATE;
1741 $contact = Contact::getByURL($item['follow']);
1742 $item['follow'] = $contact['url'];
1744 if ($contact['alias']) {
1745 $item['follow'] = $contact['alias'];
1747 $contact['alias'] = $contact['url'];
1750 $condition = ['uid' => $owner['uid'], 'nurl' => Strings::normaliseLink($contact["url"])];
1751 $user_contact = DBA::selectFirst('contact', ['id'], $condition);
1753 if (DBA::isResult($user_contact)) {
1754 $connect_id = $user_contact['id'];
1759 if ($item['verb'] == Activity::FOLLOW) {
1760 $message = DI::l10n()->t('%s is now following %s.');
1761 $title = DI::l10n()->t('following');
1762 $action = "subscription";
1764 $message = DI::l10n()->t('%s stopped following %s.');
1765 $title = DI::l10n()->t('stopped following');
1766 $action = "unfollow";
1769 $item["uri"] = $item['parent-uri'] = $item['thr-parent']
1770 = 'tag:' . DI::baseUrl()->getHostname().
1771 ','.date('Y-m-d').':'.$action.':'.$owner['uid'].
1772 ':person:'.$connect_id.':'.$item['created'];
1774 $item["body"] = sprintf($message, $owner["nick"], $contact["nick"]);
1776 $entry = self::entryHeader($doc, $owner, $item, $toplevel);
1778 self::entryContent($doc, $entry, $item, $owner, $title);
1780 $object = self::addPersonObject($doc, $owner, $contact);
1781 $entry->appendChild($object);
1783 self::entryFooter($doc, $entry, $item, $owner);
1789 * Adds a regular entry element
1791 * @param DOMDocument $doc XML document
1792 * @param array $item Data of the item that is to be posted
1793 * @param array $owner Contact data of the poster
1794 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1796 * @return \DOMElement Entry element
1797 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1798 * @throws \ImagickException
1800 private static function noteEntry(DOMDocument $doc, array $item, array $owner, $toplevel)
1802 if (($item['gravity'] != GRAVITY_PARENT) && (Strings::normaliseLink($item["author-link"]) != Strings::normaliseLink($owner["url"]))) {
1803 Logger::log("OStatus entry is from author ".$owner["url"]." - not from ".$item["author-link"].". Quitting.", Logger::DEBUG);
1807 if (!empty($item['title'])) {
1808 $title = BBCode::convertForUriId($item['uri-id'], $item['title'], BBCode::OSTATUS);
1810 $title = sprintf("New note by %s", $owner["nick"]);
1813 $title = sprintf("New comment by %s", $owner["nick"]);
1816 $entry = self::entryHeader($doc, $owner, $item, $toplevel);
1818 XML::addElement($doc, $entry, "activity:object-type", Activity\ObjectType::NOTE);
1820 self::entryContent($doc, $entry, $item, $owner, $title, '', true);
1822 self::entryFooter($doc, $entry, $item, $owner, true);
1828 * Adds a header element to the XML document
1830 * @param DOMDocument $doc XML document
1831 * @param array $owner Contact data of the poster
1832 * @param array $item
1833 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1835 * @return \DOMElement The entry element where the elements are added
1836 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1837 * @throws \ImagickException
1839 public static function entryHeader(DOMDocument $doc, array $owner, array $item, $toplevel)
1842 $entry = $doc->createElement("entry");
1844 if ($owner['contact-type'] == Contact::TYPE_COMMUNITY) {
1845 $contact = Contact::getByURL($item['author-link']) ?: $owner;
1846 $author = self::addAuthor($doc, $contact, false);
1847 $entry->appendChild($author);
1850 $entry = $doc->createElementNS(ActivityNamespace::ATOM1, "entry");
1852 $entry->setAttribute("xmlns:thr", ActivityNamespace::THREAD);
1853 $entry->setAttribute("xmlns:georss", ActivityNamespace::GEORSS);
1854 $entry->setAttribute("xmlns:activity", ActivityNamespace::ACTIVITY);
1855 $entry->setAttribute("xmlns:media", ActivityNamespace::MEDIA);
1856 $entry->setAttribute("xmlns:poco", ActivityNamespace::POCO);
1857 $entry->setAttribute("xmlns:ostatus", ActivityNamespace::OSTATUS);
1858 $entry->setAttribute("xmlns:statusnet", ActivityNamespace::STATUSNET);
1859 $entry->setAttribute("xmlns:mastodon", ActivityNamespace::MASTODON);
1861 $author = self::addAuthor($doc, $owner);
1862 $entry->appendChild($author);
1869 * Adds elements to the XML document
1871 * @param DOMDocument $doc XML document
1872 * @param \DOMElement $entry Entry element where the content is added
1873 * @param array $item Data of the item that is to be posted
1874 * @param array $owner Contact data of the poster
1875 * @param string $title Title for the post
1876 * @param string $verb The activity verb
1877 * @param bool $complete Add the "status_net" element?
1879 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1881 private static function entryContent(DOMDocument $doc, \DOMElement $entry, array $item, array $owner, $title, $verb = "", $complete = true)
1884 $verb = self::constructVerb($item);
1887 XML::addElement($doc, $entry, "id", $item["uri"]);
1888 XML::addElement($doc, $entry, "title", html_entity_decode($title, ENT_QUOTES, 'UTF-8'));
1890 $body = Post\Media::addAttachmentsToBody($item['uri-id'], $item['body']);
1891 $body = self::formatPicturePost($body, $item['uri-id']);
1893 if (!empty($item['title'])) {
1894 $body = "[b]".$item['title']."[/b]\n\n".$body;
1897 $body = BBCode::convertForUriId($item['uri-id'], $body, BBCode::OSTATUS);
1899 XML::addElement($doc, $entry, "content", $body, ["type" => "html"]);
1901 XML::addElement($doc, $entry, "link", "", ["rel" => "alternate", "type" => "text/html",
1902 "href" => DI::baseUrl()."/display/".$item["guid"]]
1905 if ($complete && ($item["id"] > 0)) {
1906 XML::addElement($doc, $entry, "status_net", "", ["notice_id" => $item["id"]]);
1909 XML::addElement($doc, $entry, "activity:verb", $verb);
1911 XML::addElement($doc, $entry, "published", DateTimeFormat::utc($item["created"]."+00:00", DateTimeFormat::ATOM));
1912 XML::addElement($doc, $entry, "updated", DateTimeFormat::utc($item["edited"]."+00:00", DateTimeFormat::ATOM));
1916 * Adds the elements at the foot of an entry to the XML document
1918 * @param DOMDocument $doc XML document
1919 * @param object $entry The entry element where the elements are added
1920 * @param array $item Data of the item that is to be posted
1921 * @param array $owner Contact data of the poster
1922 * @param bool $complete default true
1924 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1926 private static function entryFooter(DOMDocument $doc, $entry, array $item, array $owner, $complete = true)
1930 if ($item['gravity'] != GRAVITY_PARENT) {
1931 $parent = Post::selectFirst(['guid', 'author-link', 'owner-link'], ['id' => $item['parent']]);
1933 $thrparent = Post::selectFirst(['guid', 'author-link', 'owner-link', 'plink'], ['uid' => $owner["uid"], 'uri' => $item['thr-parent']]);
1935 if (DBA::isResult($thrparent)) {
1936 $mentioned[$thrparent["author-link"]] = $thrparent["author-link"];
1937 $mentioned[$thrparent["owner-link"]] = $thrparent["owner-link"];
1938 $parent_plink = $thrparent["plink"];
1940 $mentioned[$parent["author-link"]] = $parent["author-link"];
1941 $mentioned[$parent["owner-link"]] = $parent["owner-link"];
1942 $parent_plink = DI::baseUrl()."/display/".$parent["guid"];
1946 "ref" => $item['thr-parent'],
1947 "href" => $parent_plink];
1948 XML::addElement($doc, $entry, "thr:in-reply-to", "", $attributes);
1952 "href" => $parent_plink];
1953 XML::addElement($doc, $entry, "link", "", $attributes);
1956 if (intval($item['parent']) > 0) {
1957 $conversation_href = $conversation_uri = str_replace('/objects/', '/context/', $item['thr-parent']);
1959 if (isset($parent_item)) {
1960 $conversation = DBA::selectFirst('conversation', ['conversation-uri', 'conversation-href'], ['item-uri' => $parent_item]);
1961 if (DBA::isResult($conversation)) {
1962 if ($conversation['conversation-uri'] != '') {
1963 $conversation_uri = $conversation['conversation-uri'];
1965 if ($conversation['conversation-href'] != '') {
1966 $conversation_href = $conversation['conversation-href'];
1971 XML::addElement($doc, $entry, "link", "", ["rel" => "ostatus:conversation", "href" => $conversation_href]);
1974 "href" => $conversation_href,
1975 "local_id" => $item['parent'],
1976 "ref" => $conversation_uri];
1978 XML::addElement($doc, $entry, "ostatus:conversation", $conversation_uri, $attributes);
1981 // uri-id isn't present for follow entry pseudo-items
1982 $tags = Tag::getByURIId($item['uri-id'] ?? 0);
1983 foreach ($tags as $tag) {
1984 $mentioned[$tag['url']] = $tag['url'];
1987 // Make sure that mentions are accepted (GNU Social has problems with mixing HTTP and HTTPS)
1989 foreach ($mentioned as $mention) {
1990 $newmentions[str_replace("http://", "https://", $mention)] = str_replace("http://", "https://", $mention);
1991 $newmentions[str_replace("https://", "http://", $mention)] = str_replace("https://", "http://", $mention);
1993 $mentioned = $newmentions;
1995 foreach ($mentioned as $mention) {
1996 $contact = Contact::getByURL($mention, false, ['contact-type']);
1997 if (!empty($contact) && ($contact['contact-type'] == Contact::TYPE_COMMUNITY)) {
1998 XML::addElement($doc, $entry, "link", "",
2000 "rel" => "mentioned",
2001 "ostatus:object-type" => Activity\ObjectType::GROUP,
2005 XML::addElement($doc, $entry, "link", "",
2007 "rel" => "mentioned",
2008 "ostatus:object-type" => Activity\ObjectType::PERSON,
2014 if ($owner['contact-type'] == Contact::TYPE_COMMUNITY) {
2015 XML::addElement($doc, $entry, "link", "", [
2016 "rel" => "mentioned",
2017 "ostatus:object-type" => "http://activitystrea.ms/schema/1.0/group",
2018 "href" => $owner['url']
2022 if ($item['private'] != Item::PRIVATE) {
2023 XML::addElement($doc, $entry, "link", "", ["rel" => "ostatus:attention",
2024 "href" => "http://activityschema.org/collection/public"]);
2025 XML::addElement($doc, $entry, "link", "", ["rel" => "mentioned",
2026 "ostatus:object-type" => "http://activitystrea.ms/schema/1.0/collection",
2027 "href" => "http://activityschema.org/collection/public"]);
2028 XML::addElement($doc, $entry, "mastodon:scope", "public");
2031 foreach ($tags as $tag) {
2032 if ($tag['type'] == Tag::HASHTAG) {
2033 XML::addElement($doc, $entry, "category", "", ["term" => $tag['name']]);
2037 self::getAttachment($doc, $entry, $item);
2039 if ($complete && ($item["id"] > 0)) {
2040 $app = $item["app"];
2045 $attributes = ["local_id" => $item["id"], "source" => $app];
2047 if (isset($parent["id"])) {
2048 $attributes["repeat_of"] = $parent["id"];
2051 if ($item["coord"] != "") {
2052 XML::addElement($doc, $entry, "georss:point", $item["coord"]);
2055 XML::addElement($doc, $entry, "statusnet:notice_info", "", $attributes);
2060 * Creates the XML feed for a given nickname
2062 * Supported filters:
2063 * - activity (default): all the public posts
2064 * - posts: all the public top-level posts
2065 * - comments: all the public replies
2067 * Updates the provided last_update parameter if the result comes from the
2068 * cache or it is empty
2070 * @param string $owner_nick Nickname of the feed owner
2071 * @param string $last_update Date of the last update
2072 * @param integer $max_items Number of maximum items to fetch
2073 * @param string $filter Feed items filter (activity, posts or comments)
2074 * @param boolean $nocache Wether to bypass caching
2076 * @return string XML feed
2077 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2078 * @throws \ImagickException
2080 public static function feed($owner_nick, &$last_update, $max_items = 300, $filter = 'activity', $nocache = false)
2082 $stamp = microtime(true);
2084 $owner = User::getOwnerDataByNick($owner_nick);
2089 $cachekey = "ostatus:feed:" . $owner_nick . ":" . $filter . ":" . $last_update;
2091 $previous_created = $last_update;
2093 // Don't cache when the last item was posted less then 15 minutes ago (Cache duration)
2094 if ((time() - strtotime($owner['last-item'])) < 15*60) {
2095 $result = DI::cache()->get($cachekey);
2096 if (!$nocache && !is_null($result)) {
2097 Logger::log('Feed duration: ' . number_format(microtime(true) - $stamp, 3) . ' - ' . $owner_nick . ' - ' . $filter . ' - ' . $previous_created . ' (cached)', Logger::DEBUG);
2098 $last_update = $result['last_update'];
2099 return $result['feed'];
2103 if (!strlen($last_update)) {
2104 $last_update = 'now -30 days';
2107 $check_date = DateTimeFormat::utc($last_update);
2108 $authorid = Contact::getIdForURL($owner["url"]);
2110 $condition = ["`uid` = ? AND `received` > ? AND NOT `deleted`
2111 AND `private` != ? AND `visible` AND `wall` AND `parent-network` IN (?, ?)",
2112 $owner["uid"], $check_date, Item::PRIVATE, Protocol::OSTATUS, Protocol::DFRN];
2114 if ($filter === 'comments') {
2115 $condition[0] .= " AND `object-type` = ? ";
2116 $condition[] = Activity\ObjectType::COMMENT;
2119 if ($owner['contact-type'] != Contact::TYPE_COMMUNITY) {
2120 $condition[0] .= " AND `contact-id` = ? AND `author-id` = ?";
2121 $condition[] = $owner["id"];
2122 $condition[] = $authorid;
2125 $params = ['order' => ['received' => true], 'limit' => $max_items];
2127 if ($filter === 'posts') {
2128 $ret = Post::selectThread([], $condition, $params);
2130 $ret = Post::select([], $condition, $params);
2133 $items = Post::toArray($ret);
2135 $doc = new DOMDocument('1.0', 'utf-8');
2136 $doc->formatOutput = true;
2138 $root = self::addHeader($doc, $owner, $filter);
2140 foreach ($items as $item) {
2141 if (DI::config()->get('system', 'ostatus_debug')) {
2142 $item['body'] .= '🍼';
2145 if (in_array($item["verb"], [Activity::FOLLOW, Activity::O_UNFOLLOW, Activity::LIKE])) {
2149 $entry = self::entry($doc, $item, $owner, false);
2150 $root->appendChild($entry);
2152 if ($last_update < $item['created']) {
2153 $last_update = $item['created'];
2157 $feeddata = trim($doc->saveXML());
2159 $msg = ['feed' => $feeddata, 'last_update' => $last_update];
2160 DI::cache()->set($cachekey, $msg, Duration::QUARTER_HOUR);
2162 Logger::log('Feed duration: ' . number_format(microtime(true) - $stamp, 3) . ' - ' . $owner_nick . ' - ' . $filter . ' - ' . $previous_created, Logger::DEBUG);
2168 * Creates the XML for a salmon message
2170 * @param array $item Data of the item that is to be posted
2171 * @param array $owner Contact data of the poster
2173 * @return string XML for the salmon
2174 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2175 * @throws \ImagickException
2177 public static function salmon(array $item, array $owner)
2179 $doc = new DOMDocument('1.0', 'utf-8');
2180 $doc->formatOutput = true;
2182 if (DI::config()->get('system', 'ostatus_debug')) {
2183 $item['body'] .= '🐟';
2186 $entry = self::entry($doc, $item, $owner, true);
2188 $doc->appendChild($entry);
2190 return trim($doc->saveXML());
2194 * Checks if the given contact url does support OStatus
2196 * @param string $url profile url
2198 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2199 * @throws \ImagickException
2201 public static function isSupportedByContactUrl($url)
2203 $probe = Probe::uri($url, Protocol::OSTATUS);
2204 return $probe['network'] == Protocol::OSTATUS;