3 * @copyright Copyright (C) 2020, Friendica
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\PageInfo;
27 use Friendica\Content\Text\BBCode;
28 use Friendica\Content\Text\HTML;
29 use Friendica\Core\Cache\Duration;
30 use Friendica\Core\Logger;
31 use Friendica\Core\Protocol;
32 use Friendica\Database\DBA;
34 use Friendica\Model\APContact;
35 use Friendica\Model\Contact;
36 use Friendica\Model\Conversation;
37 use Friendica\Model\Item;
38 use Friendica\Model\ItemURI;
39 use Friendica\Model\Post;
40 use Friendica\Model\Tag;
41 use Friendica\Model\User;
42 use Friendica\Network\Probe;
43 use Friendica\Util\DateTimeFormat;
44 use Friendica\Util\Images;
45 use Friendica\Util\Proxy as ProxyUtils;
46 use Friendica\Util\Strings;
47 use Friendica\Util\XML;
49 require_once 'mod/share.php';
50 require_once 'include/api.php';
53 * This class contain functions for the OStatus protocol
57 private static $itemlist;
58 private static $conv_list = [];
63 * @param DOMXPath $xpath The xpath object
64 * @param object $context The xml context of the author details
65 * @param array $importer user record of the importing user
66 * @param array $contact Called by reference, will contain the fetched contact
67 * @param bool $onlyfetch Only fetch the header without updating the contact entries
69 * @return array Array of author related entries for the item
70 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
71 * @throws \ImagickException
73 private static function fetchAuthor(DOMXPath $xpath, $context, array $importer, array &$contact = null, $onlyfetch)
76 $author["author-link"] = XML::getFirstNodeValue($xpath, 'atom:author/atom:uri/text()', $context);
77 $author["author-name"] = XML::getFirstNodeValue($xpath, 'atom:author/atom:name/text()', $context);
78 $addr = XML::getFirstNodeValue($xpath, 'atom:author/atom:email/text()', $context);
80 $aliaslink = $author["author-link"];
82 $alternate_item = $xpath->query("atom:author/atom:link[@rel='alternate']", $context)->item(0);
83 if (is_object($alternate_item)) {
84 foreach ($alternate_item->attributes as $attributes) {
85 if (($attributes->name == "href") && ($attributes->textContent != "")) {
86 $author["author-link"] = $attributes->textContent;
90 $author["author-id"] = Contact::getIdForURL($author["author-link"]);
92 $author['contact-id'] = ($contact['id'] ?? 0) ?: $author['author-id'];
97 This here would be better, but we would get problems with contacts from the statusnet addon
98 This is kept here as a reminder for the future
100 $cid = Contact::getIdForURL($author["author-link"], $importer["uid"]);
102 $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
105 if ($aliaslink != '') {
106 $condition = ["`uid` = ? AND `alias` = ? AND `network` != ? AND `rel` IN (?, ?)",
107 $importer["uid"], $aliaslink, Protocol::STATUSNET,
108 Contact::SHARING, Contact::FRIEND];
109 $contact = DBA::selectFirst('contact', [], $condition);
112 if (!DBA::isResult($contact) && $author["author-link"] != '') {
113 if ($aliaslink == "") {
114 $aliaslink = $author["author-link"];
117 $condition = ["`uid` = ? AND `nurl` IN (?, ?) AND `network` != ? AND `rel` IN (?, ?)",
118 $importer["uid"], Strings::normaliseLink($author["author-link"]), Strings::normaliseLink($aliaslink),
119 Protocol::STATUSNET, Contact::SHARING, Contact::FRIEND];
120 $contact = DBA::selectFirst('contact', [], $condition);
123 if (!DBA::isResult($contact) && ($addr != '')) {
124 $condition = ["`uid` = ? AND `addr` = ? AND `network` != ? AND `rel` IN (?, ?)",
125 $importer["uid"], $addr, Protocol::STATUSNET,
126 Contact::SHARING, Contact::FRIEND];
127 $contact = DBA::selectFirst('contact', [], $condition);
130 if (DBA::isResult($contact)) {
131 if ($contact['blocked']) {
133 } elseif (!empty(APContact::getByURL($contact['url'], false))) {
134 ActivityPub\Receiver::switchContact($contact['id'], $importer['uid'], $contact['url']);
136 $author["contact-id"] = $contact["id"];
140 $avatars = $xpath->query("atom:author/atom:link[@rel='avatar']", $context);
141 foreach ($avatars as $avatar) {
144 foreach ($avatar->attributes as $attributes) {
145 if ($attributes->name == "href") {
146 $href = $attributes->textContent;
148 if ($attributes->name == "width") {
149 $width = $attributes->textContent;
153 $avatarlist[$width] = $href;
156 if (count($avatarlist) > 0) {
158 $author["author-avatar"] = Probe::fixAvatar(current($avatarlist), $author["author-link"]);
161 $displayname = XML::getFirstNodeValue($xpath, 'atom:author/poco:displayName/text()', $context);
162 if ($displayname != "") {
163 $author["author-name"] = $displayname;
166 $author["owner-id"] = $author["author-id"];
168 // Only update the contacts if it is an OStatus contact
169 if (DBA::isResult($contact) && ($contact['id'] > 0) && !$onlyfetch && ($contact["network"] == Protocol::OSTATUS)) {
171 // Update contact data
173 unset($current['name-date']);
175 // This query doesn't seem to work
176 // $value = $xpath->query("atom:link[@rel='salmon']", $context)->item(0)->nodeValue;
178 // $contact["notify"] = $value;
180 // This query doesn't seem to work as well - I hate these queries
181 // $value = $xpath->query("atom:link[@rel='self' and @type='application/atom+xml']", $context)->item(0)->nodeValue;
183 // $contact["poll"] = $value;
185 $contact['url'] = $author["author-link"];
186 $contact['nurl'] = Strings::normaliseLink($contact['url']);
188 $value = XML::getFirstNodeValue($xpath, 'atom:author/atom:uri/text()', $context);
190 $contact["alias"] = $value;
193 $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:displayName/text()', $context);
195 $contact["name"] = $value;
198 $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:preferredUsername/text()', $context);
200 $contact["nick"] = $value;
203 $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:note/text()', $context);
205 $contact["about"] = HTML::toBBCode($value);
208 $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:address/poco:formatted/text()', $context);
210 $contact["location"] = $value;
213 $contact['name-date'] = DateTimeFormat::utcNow();
215 DBA::update('contact', $contact, ['id' => $contact["id"]], $current);
217 if (!empty($author["author-avatar"]) && ($author["author-avatar"] != $current['avatar'])) {
218 Logger::log("Update profile picture for contact ".$contact["id"], Logger::DEBUG);
219 Contact::updateAvatar($contact["id"], $author["author-avatar"]);
222 // Ensure that we are having this contact (with uid=0)
223 $cid = Contact::getIdForURL($aliaslink);
226 $fields = ['url', 'nurl', 'name', 'nick', 'alias', 'about', 'location'];
227 $old_contact = DBA::selectFirst('contact', $fields, ['id' => $cid]);
229 // Update it with the current values
230 $fields = ['url' => $author["author-link"], 'name' => $contact["name"],
231 'nurl' => Strings::normaliseLink($author["author-link"]),
232 'nick' => $contact["nick"], 'alias' => $contact["alias"],
233 'about' => $contact["about"], 'location' => $contact["location"],
234 'success_update' => DateTimeFormat::utcNow(), 'last-update' => DateTimeFormat::utcNow()];
236 DBA::update('contact', $fields, ['id' => $cid], $old_contact);
239 if (!empty($author["author-avatar"])) {
240 Contact::updateAvatar($cid, $author["author-avatar"]);
243 } elseif (empty($contact["network"]) || ($contact["network"] != Protocol::DFRN)) {
251 * Fetches author data from a given XML string
253 * @param string $xml The XML
254 * @param array $importer user record of the importing user
256 * @return array Array of author related entries for the item
257 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
258 * @throws \ImagickException
260 public static function salmonAuthor($xml, array $importer)
266 $doc = new DOMDocument();
267 @$doc->loadXML($xml);
269 $xpath = new DOMXPath($doc);
270 $xpath->registerNamespace('atom', ActivityNamespace::ATOM1);
271 $xpath->registerNamespace('thr', ActivityNamespace::THREAD);
272 $xpath->registerNamespace('georss', ActivityNamespace::GEORSS);
273 $xpath->registerNamespace('activity', ActivityNamespace::ACTIVITY);
274 $xpath->registerNamespace('media', ActivityNamespace::MEDIA);
275 $xpath->registerNamespace('poco', ActivityNamespace::POCO);
276 $xpath->registerNamespace('ostatus', ActivityNamespace::OSTATUS);
277 $xpath->registerNamespace('statusnet', ActivityNamespace::STATUSNET);
279 $contact = ["id" => 0];
281 // Fetch the first author
282 $authordata = $xpath->query('//author')->item(0);
283 $author = self::fetchAuthor($xpath, $authordata, $importer, $contact, true);
288 * Read attributes from element
290 * @param object $element Element object
292 * @return array attributes
294 private static function readAttributes($element)
298 foreach ($element->attributes as $attributes) {
299 $attribute[$attributes->name] = $attributes->textContent;
306 * Imports an XML string containing OStatus elements
308 * @param string $xml The XML
309 * @param array $importer user record of the importing user
310 * @param array $contact contact
311 * @param string $hub Called by reference, returns the fetched hub data
313 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
314 * @throws \ImagickException
316 public static function import($xml, array $importer, array &$contact, &$hub)
318 self::process($xml, $importer, $contact, $hub);
322 * Internal feed processing
324 * @param string $xml The XML
325 * @param array $importer user record of the importing user
326 * @param array $contact contact
327 * @param string $hub Called by reference, returns the fetched hub data
328 * @param boolean $stored Is the post fresh imported or from the database?
329 * @param boolean $initialize Is it the leading post so that data has to be initialized?
331 * @return boolean Could the XML be processed?
332 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
333 * @throws \ImagickException
335 private static function process($xml, array $importer, array &$contact = null, &$hub, $stored = false, $initialize = true)
338 self::$itemlist = [];
339 self::$conv_list = [];
342 Logger::log('Import OStatus message for user ' . $importer['uid'], Logger::DEBUG);
347 $doc = new DOMDocument();
348 @$doc->loadXML($xml);
350 $xpath = new DOMXPath($doc);
351 $xpath->registerNamespace('atom', ActivityNamespace::ATOM1);
352 $xpath->registerNamespace('thr', ActivityNamespace::THREAD);
353 $xpath->registerNamespace('georss', ActivityNamespace::GEORSS);
354 $xpath->registerNamespace('activity', ActivityNamespace::ACTIVITY);
355 $xpath->registerNamespace('media', ActivityNamespace::MEDIA);
356 $xpath->registerNamespace('poco', ActivityNamespace::POCO);
357 $xpath->registerNamespace('ostatus', ActivityNamespace::OSTATUS);
358 $xpath->registerNamespace('statusnet', ActivityNamespace::STATUSNET);
361 $hub_items = $xpath->query("/atom:feed/atom:link[@rel='hub']")->item(0);
362 if (is_object($hub_items)) {
363 $hub_attributes = $hub_items->attributes;
364 if (is_object($hub_attributes)) {
365 foreach ($hub_attributes as $hub_attribute) {
366 if ($hub_attribute->name == "href") {
367 $hub = $hub_attribute->textContent;
368 Logger::log("Found hub ".$hub, Logger::DEBUG);
375 $header["uid"] = $importer["uid"];
376 $header["network"] = Protocol::OSTATUS;
378 $header["origin"] = 0;
379 $header["gravity"] = GRAVITY_COMMENT;
381 if (!is_object($doc->firstChild) || empty($doc->firstChild->tagName)) {
385 $first_child = $doc->firstChild->tagName;
387 if ($first_child == "feed") {
388 $entries = $xpath->query('/atom:feed/atom:entry');
390 $entries = $xpath->query('/atom:entry');
393 if ($entries->length == 1) {
394 // We reformat the XML to make it better readable
395 $doc2 = new DOMDocument();
396 $doc2->loadXML($xml);
397 $doc2->preserveWhiteSpace = false;
398 $doc2->formatOutput = true;
399 $xml2 = $doc2->saveXML();
401 $header["protocol"] = Conversation::PARCEL_SALMON;
402 $header["source"] = $xml2;
403 } elseif (!$initialize) {
407 // Fetch the first author
408 $authordata = $xpath->query('//author')->item(0);
409 $author = self::fetchAuthor($xpath, $authordata, $importer, $contact, $stored);
411 // Reverse the order of the entries
414 foreach ($entries as $entry) {
415 $entrylist[] = $entry;
418 foreach (array_reverse($entrylist) as $entry) {
420 $authorelement = $xpath->query('/atom:entry/atom:author', $entry);
422 if ($authorelement->length == 0) {
423 $authorelement = $xpath->query('atom:author', $entry);
426 if ($authorelement->length > 0) {
427 $author = self::fetchAuthor($xpath, $entry, $importer, $contact, $stored);
430 $item = array_merge($header, $author);
432 $item["uri"] = XML::getFirstNodeValue($xpath, 'atom:id/text()', $entry);
433 $item['uri-id'] = ItemURI::insert(['uri' => $item['uri']]);
435 $item["verb"] = XML::getFirstNodeValue($xpath, 'activity:verb/text()', $entry);
438 if (in_array($item["verb"], ['qvitter-delete-notice', Activity::DELETE, 'delete'])) {
439 self::deleteNotice($item);
443 if (in_array($item["verb"], [Activity::O_UNFAVOURITE, Activity::UNFAVORITE])) {
444 // Ignore "Unfavorite" message
445 Logger::log("Ignore unfavorite message ".print_r($item, true), Logger::DEBUG);
449 // Deletions come with the same uri, so we check for duplicates after processing deletions
450 if (Item::exists(['uid' => $importer["uid"], 'uri' => $item["uri"]])) {
451 Logger::log('Post with URI '.$item["uri"].' already existed for user '.$importer["uid"].'.', Logger::DEBUG);
454 Logger::log('Processing post with URI '.$item["uri"].' for user '.$importer["uid"].'.', Logger::DEBUG);
457 if ($item["verb"] == Activity::JOIN) {
458 // ignore "Join" messages
459 Logger::log("Ignore join message ".print_r($item, true), Logger::DEBUG);
463 if ($item["verb"] == "http://mastodon.social/schema/1.0/block") {
464 // ignore mastodon "block" messages
465 Logger::log("Ignore block message ".print_r($item, true), Logger::DEBUG);
469 if ($item["verb"] == Activity::FOLLOW) {
470 Contact::addRelationship($importer, $contact, $item);
474 if ($item["verb"] == Activity::O_UNFOLLOW) {
476 Contact::removeFollower($importer, $contact, $item, $dummy);
480 if ($item["verb"] == Activity::FAVORITE) {
481 $orig_uri = $xpath->query("activity:object/atom:id", $entry)->item(0)->nodeValue;
482 Logger::log("Favorite ".$orig_uri." ".print_r($item, true));
484 $item["verb"] = Activity::LIKE;
485 $item["thr-parent"] = $orig_uri;
486 $item["gravity"] = GRAVITY_ACTIVITY;
487 $item["object-type"] = Activity\ObjectType::NOTE;
490 // http://activitystrea.ms/schema/1.0/rsvp-yes
491 if (!in_array($item["verb"], [Activity::POST, Activity::LIKE, Activity::SHARE])) {
492 Logger::log("Unhandled verb ".$item["verb"]." ".print_r($item, true), Logger::DEBUG);
495 self::processPost($xpath, $entry, $item, $importer);
497 if ($initialize && (count(self::$itemlist) > 0)) {
498 if (self::$itemlist[0]['uri'] == self::$itemlist[0]['thr-parent']) {
499 // We will import it everytime, when it is started by our contacts
500 $valid = Contact::isSharingByURL(self::$itemlist[0]['author-link'], self::$itemlist[0]['uid']);
503 // If not, then it depends on this setting
504 $valid = ((self::$itemlist[0]['uid'] == 0) || !DI::pConfig()->get(self::$itemlist[0]['uid'], 'system', 'accept_only_sharer', false));
506 Logger::log("Item with uri ".self::$itemlist[0]['uri']." will be imported due to the system settings.", Logger::DEBUG);
509 Logger::log("Item with uri ".self::$itemlist[0]['uri']." belongs to a contact (".self::$itemlist[0]['contact-id']."). It will be imported.", Logger::DEBUG);
512 // Never post a thread when the only interaction by our contact was a like
514 $verbs = [Activity::POST, Activity::SHARE];
515 foreach (self::$itemlist as $item) {
516 if (in_array($item['verb'], $verbs) && Contact::isSharingByURL($item['author-link'], $item['uid'])) {
521 Logger::log("Item with uri ".self::$itemlist[0]['uri']." will be imported since the thread contains posts or shares.", Logger::DEBUG);
529 $default_contact = 0;
530 for ($key = count(self::$itemlist) - 1; $key >= 0; $key--) {
531 if (empty(self::$itemlist[$key]['contact-id'])) {
532 self::$itemlist[$key]['contact-id'] = $default_contact;
534 $default_contact = $item['contact-id'];
537 foreach (self::$itemlist as $item) {
538 $found = Item::exists(['uid' => $importer["uid"], 'uri' => $item["uri"]]);
540 Logger::log("Item with uri ".$item["uri"]." for user ".$importer["uid"]." already exists.", Logger::DEBUG);
541 } elseif ($item['contact-id'] < 0) {
542 Logger::log("Item with uri ".$item["uri"]." is from a blocked contact.", Logger::DEBUG);
544 $ret = Item::insert($item);
545 Logger::log("Item with uri ".$item["uri"]." for user ".$importer["uid"].' stored. Return value: '.$ret);
549 self::$itemlist = [];
551 Logger::log('Processing done for post with URI '.$item["uri"].' for user '.$importer["uid"].'.', Logger::DEBUG);
557 * Removes notice item from database
559 * @param array $item item
563 private static function deleteNotice(array $item)
565 $condition = ['uid' => $item['uid'], 'author-id' => $item['author-id'], 'uri' => $item['uri']];
566 if (!Item::exists($condition)) {
567 Logger::log('Item from '.$item['author-link'].' with uri '.$item['uri'].' for user '.$item['uid']." wasn't found. We don't delete it.");
571 Item::markForDeletion($condition);
573 Logger::log('Deleted item with uri '.$item['uri'].' for user '.$item['uid']);
577 * Processes the XML for a post
579 * @param DOMXPath $xpath The xpath object
580 * @param object $entry The xml entry that is processed
581 * @param array $item The item array
582 * @param array $importer user record of the importing user
584 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
585 * @throws \ImagickException
587 private static function processPost(DOMXPath $xpath, $entry, array &$item, array $importer)
589 $item["body"] = HTML::toBBCode(XML::getFirstNodeValue($xpath, 'atom:content/text()', $entry));
590 $item["object-type"] = XML::getFirstNodeValue($xpath, 'activity:object-type/text()', $entry);
591 if (($item["object-type"] == Activity\ObjectType::BOOKMARK) || ($item["object-type"] == Activity\ObjectType::EVENT)) {
592 $item["title"] = XML::getFirstNodeValue($xpath, 'atom:title/text()', $entry);
593 $item["body"] = XML::getFirstNodeValue($xpath, 'atom:summary/text()', $entry);
594 } elseif ($item["object-type"] == Activity\ObjectType::QUESTION) {
595 $item["title"] = XML::getFirstNodeValue($xpath, 'atom:title/text()', $entry);
598 $item["created"] = XML::getFirstNodeValue($xpath, 'atom:published/text()', $entry);
599 $item["edited"] = XML::getFirstNodeValue($xpath, 'atom:updated/text()', $entry);
600 $item['conversation-uri'] = XML::getFirstNodeValue($xpath, 'ostatus:conversation/text()', $entry);
602 $conv = $xpath->query('ostatus:conversation', $entry);
603 if (is_object($conv->item(0))) {
604 foreach ($conv->item(0)->attributes as $attributes) {
605 if ($attributes->name == "ref") {
606 $item['conversation-uri'] = $attributes->textContent;
608 if ($attributes->name == "href") {
609 $item['conversation-href'] = $attributes->textContent;
616 $inreplyto = $xpath->query('thr:in-reply-to', $entry);
617 if (is_object($inreplyto->item(0))) {
618 foreach ($inreplyto->item(0)->attributes as $attributes) {
619 if ($attributes->name == "ref") {
620 $item["thr-parent"] = $attributes->textContent;
622 if ($attributes->name == "href") {
623 $related = $attributes->textContent;
628 $georsspoint = $xpath->query('georss:point', $entry);
629 if (!empty($georsspoint) && ($georsspoint->length > 0)) {
630 $item["coord"] = $georsspoint->item(0)->nodeValue;
633 $categories = $xpath->query('atom:category', $entry);
635 foreach ($categories as $category) {
636 foreach ($category->attributes as $attributes) {
637 if ($attributes->name == 'term') {
639 Tag::store($item['uri-id'], Tag::HASHTAG, $attributes->textContent);
648 $links = $xpath->query('atom:link', $entry);
650 $link_data = self::processLinks($links, $item);
651 $self = $link_data['self'];
652 $add_body = $link_data['add_body'];
657 $notice_info = $xpath->query('statusnet:notice_info', $entry);
658 if ($notice_info && ($notice_info->length > 0)) {
659 foreach ($notice_info->item(0)->attributes as $attributes) {
660 if ($attributes->name == "source") {
661 $item["app"] = strip_tags($attributes->textContent);
663 if ($attributes->name == "repeat_of") {
664 $repeat_of = $attributes->textContent;
668 // Is it a repeated post?
669 if (($repeat_of != "") || ($item["verb"] == Activity::SHARE)) {
670 $link_data = self::processRepeatedItem($xpath, $entry, $item, $importer);
671 if (!empty($link_data['add_body'])) {
672 $add_body .= $link_data['add_body'];
676 $item["body"] .= $add_body;
678 // Only add additional data when there is no picture in the post
679 if (!strstr($item["body"], '[/img]')) {
680 $item["body"] = PageInfo::searchAndAppendToBody($item["body"]);
683 Tag::storeFromBody($item['uri-id'], $item['body']);
685 // Mastodon Content Warning
686 if (($item["verb"] == Activity::POST) && $xpath->evaluate('boolean(atom:summary)', $entry)) {
687 $clear_text = XML::getFirstNodeValue($xpath, 'atom:summary/text()', $entry);
688 if (!empty($clear_text)) {
689 $item['content-warning'] = HTML::toBBCode($clear_text);
693 if (($self != '') && empty($item['protocol'])) {
694 self::fetchSelf($self, $item);
697 if (!empty($item["conversation-href"])) {
698 self::fetchConversation($item['conversation-href'], $item['conversation-uri']);
701 if (isset($item["thr-parent"])) {
702 if (!Item::exists(['uid' => $importer["uid"], 'uri' => $item['thr-parent']])) {
703 if ($related != '') {
704 self::fetchRelated($related, $item["thr-parent"], $importer);
707 Logger::log('Reply with URI '.$item["uri"].' already existed for user '.$importer["uid"].'.', Logger::DEBUG);
710 $item["thr-parent"] = $item["uri"];
711 $item["gravity"] = GRAVITY_PARENT;
714 if (($item['author-link'] != '') && !empty($item['protocol'])) {
715 $item = Conversation::insert($item);
718 self::$itemlist[] = $item;
722 * Fetch the conversation for posts
724 * @param string $conversation The link to the conversation
725 * @param string $conversation_uri The conversation in "uri" format
727 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
729 private static function fetchConversation($conversation, $conversation_uri)
731 // Ensure that we only store a conversation once in a process
732 if (isset(self::$conv_list[$conversation])) {
736 self::$conv_list[$conversation] = true;
738 $curlResult = DI::httpRequest()->get($conversation, ['accept_content' => 'application/atom+xml, text/html']);
740 if (!$curlResult->isSuccess()) {
746 if (stristr($curlResult->getHeader(), 'Content-Type: application/atom+xml')) {
747 $xml = $curlResult->getBody();
751 $doc = new DOMDocument();
752 if (!@$doc->loadHTML($curlResult->getBody())) {
755 $xpath = new DOMXPath($doc);
757 $links = $xpath->query('//link');
760 foreach ($links as $link) {
761 $attribute = self::readAttributes($link);
762 if (($attribute['rel'] == 'alternate') && ($attribute['type'] == 'application/atom+xml')) {
763 $file = $attribute['href'];
767 $conversation_atom = DI::httpRequest()->get($attribute['href']);
769 if ($conversation_atom->isSuccess()) {
770 $xml = $conversation_atom->getBody();
780 self::storeConversation($xml, $conversation, $conversation_uri);
784 * Store a feed in several conversation entries
786 * @param string $xml The feed
787 * @param string $conversation conversation
788 * @param string $conversation_uri conversation uri
792 private static function storeConversation($xml, $conversation = '', $conversation_uri = '')
794 $doc = new DOMDocument();
795 @$doc->loadXML($xml);
797 $xpath = new DOMXPath($doc);
798 $xpath->registerNamespace('atom', ActivityNamespace::ATOM1);
799 $xpath->registerNamespace('thr', ActivityNamespace::THREAD);
800 $xpath->registerNamespace('ostatus', ActivityNamespace::OSTATUS);
802 $entries = $xpath->query('/atom:feed/atom:entry');
804 // Now store the entries
805 foreach ($entries as $entry) {
806 $doc2 = new DOMDocument();
807 $doc2->preserveWhiteSpace = false;
808 $doc2->formatOutput = true;
812 $conv_data['protocol'] = Conversation::PARCEL_SPLIT_CONVERSATION;
813 $conv_data['network'] = Protocol::OSTATUS;
814 $conv_data['uri'] = XML::getFirstNodeValue($xpath, 'atom:id/text()', $entry);
816 $inreplyto = $xpath->query('thr:in-reply-to', $entry);
817 if (is_object($inreplyto->item(0))) {
818 foreach ($inreplyto->item(0)->attributes as $attributes) {
819 if ($attributes->name == "ref") {
820 $conv_data['reply-to-uri'] = $attributes->textContent;
825 $conv_data['conversation-uri'] = XML::getFirstNodeValue($xpath, 'ostatus:conversation/text()', $entry);
827 $conv = $xpath->query('ostatus:conversation', $entry);
828 if (is_object($conv->item(0))) {
829 foreach ($conv->item(0)->attributes as $attributes) {
830 if ($attributes->name == "ref") {
831 $conv_data['conversation-uri'] = $attributes->textContent;
833 if ($attributes->name == "href") {
834 $conv_data['conversation-href'] = $attributes->textContent;
839 if ($conversation != '') {
840 $conv_data['conversation-uri'] = $conversation;
843 if ($conversation_uri != '') {
844 $conv_data['conversation-uri'] = $conversation_uri;
847 $entry = $doc2->importNode($entry, true);
849 $doc2->appendChild($entry);
851 $conv_data['source'] = $doc2->saveXML();
853 $condition = ['item-uri' => $conv_data['uri'],'protocol' => Conversation::PARCEL_FEED];
854 if (DBA::exists('conversation', $condition)) {
855 Logger::log('Delete deprecated entry for URI '.$conv_data['uri'], Logger::DEBUG);
856 DBA::delete('conversation', ['item-uri' => $conv_data['uri']]);
859 Logger::log('Store conversation data for uri '.$conv_data['uri'], Logger::DEBUG);
860 Conversation::insert($conv_data);
865 * Fetch the own post so that it can be stored later
867 * We want to store the original data for later processing.
868 * This function is meant for cases where we process a feed with multiple entries.
869 * In that case we need to fetch the single posts here.
871 * @param string $self The link to the self item
872 * @param array $item The item array
874 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
876 private static function fetchSelf($self, array &$item)
878 $condition = ['`item-uri` = ? AND `protocol` IN (?, ?)', $self, Conversation::PARCEL_DFRN, Conversation::PARCEL_SALMON];
879 if (DBA::exists('conversation', $condition)) {
880 Logger::log('Conversation '.$item['uri'].' is already stored.', Logger::DEBUG);
884 $curlResult = DI::httpRequest()->get($self);
886 if (!$curlResult->isSuccess()) {
890 // We reformat the XML to make it better readable
891 $doc = new DOMDocument();
892 $doc->loadXML($curlResult->getBody());
893 $doc->preserveWhiteSpace = false;
894 $doc->formatOutput = true;
895 $xml = $doc->saveXML();
897 $item["protocol"] = Conversation::PARCEL_SALMON;
898 $item["source"] = $xml;
900 Logger::log('Conversation '.$item['uri'].' is now fetched.', Logger::DEBUG);
904 * Fetch related posts and processes them
906 * @param string $related The link to the related item
907 * @param string $related_uri The related item in "uri" format
908 * @param array $importer user record of the importing user
910 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
911 * @throws \ImagickException
913 private static function fetchRelated($related, $related_uri, $importer)
915 $condition = ['`item-uri` = ? AND `protocol` IN (?, ?)', $related_uri, Conversation::PARCEL_DFRN, Conversation::PARCEL_SALMON];
916 $conversation = DBA::selectFirst('conversation', ['source', 'protocol'], $condition);
917 if (DBA::isResult($conversation)) {
919 $xml = $conversation['source'];
920 if (self::process($xml, $importer, $contact, $hub, $stored, false)) {
921 Logger::log('Got valid cached XML for URI '.$related_uri, Logger::DEBUG);
924 if ($conversation['protocol'] == Conversation::PARCEL_SALMON) {
925 Logger::log('Delete invalid cached XML for URI '.$related_uri, Logger::DEBUG);
926 DBA::delete('conversation', ['item-uri' => $related_uri]);
931 $curlResult = DI::httpRequest()->get($related, ['accept_content' => 'application/atom+xml, text/html']);
933 if (!$curlResult->isSuccess()) {
939 if (stristr($curlResult->getHeader(), 'Content-Type: application/atom+xml')) {
940 Logger::log('Directly fetched XML for URI ' . $related_uri, Logger::DEBUG);
941 $xml = $curlResult->getBody();
945 $doc = new DOMDocument();
946 if (!@$doc->loadHTML($curlResult->getBody())) {
949 $xpath = new DOMXPath($doc);
953 $links = $xpath->query('//link');
955 foreach ($links as $link) {
956 $attribute = self::readAttributes($link);
957 if (($attribute['rel'] == 'alternate') && ($attribute['type'] == 'application/atom+xml')) {
958 $atom_file = $attribute['href'];
961 if ($atom_file != '') {
962 $curlResult = DI::httpRequest()->get($atom_file);
964 if ($curlResult->isSuccess()) {
965 Logger::log('Fetched XML for URI ' . $related_uri, Logger::DEBUG);
966 $xml = $curlResult->getBody();
972 // Workaround for older GNU Social servers
973 if (($xml == '') && strstr($related, '/notice/')) {
974 $curlResult = DI::httpRequest()->get(str_replace('/notice/', '/api/statuses/show/', $related) . '.atom');
976 if ($curlResult->isSuccess()) {
977 Logger::log('GNU Social workaround to fetch XML for URI ' . $related_uri, Logger::DEBUG);
978 $xml = $curlResult->getBody();
982 // Even more worse workaround for GNU Social ;-)
984 $related_guess = self::convertHref($related_uri);
985 $curlResult = DI::httpRequest()->get(str_replace('/notice/', '/api/statuses/show/', $related_guess) . '.atom');
987 if ($curlResult->isSuccess()) {
988 Logger::log('GNU Social workaround 2 to fetch XML for URI ' . $related_uri, Logger::DEBUG);
989 $xml = $curlResult->getBody();
993 // Finally we take the data that we fetched from "ostatus:conversation"
995 $condition = ['item-uri' => $related_uri, 'protocol' => Conversation::PARCEL_SPLIT_CONVERSATION];
996 $conversation = DBA::selectFirst('conversation', ['source'], $condition);
997 if (DBA::isResult($conversation)) {
999 Logger::log('Got cached XML from conversation for URI '.$related_uri, Logger::DEBUG);
1000 $xml = $conversation['source'];
1005 self::process($xml, $importer, $contact, $hub, $stored, false);
1007 Logger::log("XML couldn't be fetched for URI: ".$related_uri." - href: ".$related, Logger::DEBUG);
1013 * Processes the XML for a repeated post
1015 * @param DOMXPath $xpath The xpath object
1016 * @param object $entry The xml entry that is processed
1017 * @param array $item The item array
1018 * @param array $importer user record of the importing user
1020 * @return array with data from links
1021 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1022 * @throws \ImagickException
1024 private static function processRepeatedItem(DOMXPath $xpath, $entry, array &$item, array $importer)
1026 $activityobject = $xpath->query('activity:object', $entry)->item(0);
1028 if (!is_object($activityobject)) {
1034 $orig_uri = XML::getFirstNodeValue($xpath, 'atom:id/text()', $activityobject);
1036 $links = $xpath->query("atom:link", $activityobject);
1038 $link_data = self::processLinks($links, $item);
1041 $orig_body = XML::getFirstNodeValue($xpath, 'atom:content/text()', $activityobject);
1042 $orig_created = XML::getFirstNodeValue($xpath, 'atom:published/text()', $activityobject);
1043 $orig_edited = XML::getFirstNodeValue($xpath, 'atom:updated/text()', $activityobject);
1045 $orig_author = self::fetchAuthor($xpath, $activityobject, $importer, $dummy, false);
1047 $item["author-name"] = $orig_author["author-name"];
1048 $item["author-link"] = $orig_author["author-link"];
1049 $item["author-id"] = $orig_author["author-id"];
1051 $item["body"] = HTML::toBBCode($orig_body);
1052 $item["created"] = $orig_created;
1053 $item["edited"] = $orig_edited;
1055 $item["uri"] = $orig_uri;
1057 $item["verb"] = XML::getFirstNodeValue($xpath, 'activity:verb/text()', $activityobject);
1059 $item["object-type"] = XML::getFirstNodeValue($xpath, 'activity:object-type/text()', $activityobject);
1061 // Mastodon Content Warning
1062 if (($item["verb"] == Activity::POST) && $xpath->evaluate('boolean(atom:summary)', $activityobject)) {
1063 $clear_text = XML::getFirstNodeValue($xpath, 'atom:summary/text()', $activityobject);
1064 if (!empty($clear_text)) {
1065 $item['content-warning'] = HTML::toBBCode($clear_text);
1069 $inreplyto = $xpath->query('thr:in-reply-to', $activityobject);
1070 if (is_object($inreplyto->item(0))) {
1071 foreach ($inreplyto->item(0)->attributes as $attributes) {
1072 if ($attributes->name == "ref") {
1073 $item["thr-parent"] = $attributes->textContent;
1082 * Processes links in the XML
1084 * @param object $links The xml data that contain links
1085 * @param array $item The item array
1087 * @return array with data from the links
1089 private static function processLinks($links, array &$item)
1091 $link_data = ['add_body' => '', 'self' => ''];
1093 foreach ($links as $link) {
1094 $attribute = self::readAttributes($link);
1096 if (!empty($attribute['rel']) && !empty($attribute['href'])) {
1097 switch ($attribute['rel']) {
1099 $item["plink"] = $attribute['href'];
1100 if (($item["object-type"] == Activity\ObjectType::QUESTION)
1101 || ($item["object-type"] == Activity\ObjectType::EVENT)
1103 $item["body"] .= "\n" . PageInfo::getFooterFromUrl($attribute['href']);
1106 case "ostatus:conversation":
1107 $link_data['conversation'] = $attribute['href'];
1108 $item['conversation-href'] = $link_data['conversation'];
1109 if (!isset($item['conversation-uri'])) {
1110 $item['conversation-uri'] = $item['conversation-href'];
1114 $filetype = strtolower(substr($attribute['type'], 0, strpos($attribute['type'], '/')));
1115 if ($filetype == 'image') {
1116 $link_data['add_body'] .= "\n[img]".$attribute['href'].'[/img]';
1118 Post\Media::insert(['uri-id' => $item['uri-id'], 'type' => Post\Media::DOCUMENT,
1119 'url' => $attribute['href'], 'mimetype' => $attribute['type'],
1120 'size' => $attribute['length'] ?? null, 'description' => $attribute['title'] ?? null]);
1124 if ($item["object-type"] != Activity\ObjectType::BOOKMARK) {
1125 if (!isset($item["thr-parent"])) {
1126 $item["thr-parent"] = $attribute['href'];
1128 $link_data['related'] = $attribute['href'];
1130 $item["body"] .= "\n" . PageInfo::getFooterFromUrl($attribute['href']);
1134 if (empty($item["plink"])) {
1135 $item["plink"] = $attribute['href'];
1137 $link_data['self'] = $attribute['href'];
1146 * Create an url out of an uri
1148 * @param string $href URI in the format "parameter1:parameter1:..."
1150 * @return string URL in the format http(s)://....
1152 private static function convertHref($href)
1154 $elements = explode(":", $href);
1156 if ((count($elements) <= 2) || ($elements[0] != "tag")) {
1160 $server = explode(",", $elements[1]);
1161 $conversation = explode("=", $elements[2]);
1163 if ((count($elements) == 4) && ($elements[2] == "post")) {
1164 return "http://".$server[0]."/notice/".$elements[3];
1167 if ((count($conversation) != 2) || ($conversation[1] =="")) {
1170 if ($elements[3] == "objectType=thread") {
1171 return "http://".$server[0]."/conversation/".$conversation[1];
1173 return "http://".$server[0]."/notice/".$conversation[1];
1178 * Checks if the current post is a reshare
1180 * @param array $item The item array of thw post
1182 * @return string The guid if the post is a reshare
1184 public static function getResharedGuid(array $item)
1186 $reshared = Item::getShareArray($item);
1187 if (empty($reshared['guid']) || !empty($reshared['comment'])) {
1191 return $reshared['guid'];
1195 * Cleans the body of a post if it contains picture links
1197 * @param string $body The body
1199 * @return string The cleaned body
1200 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1202 public static function formatPicturePost($body)
1204 $siteinfo = BBCode::getAttachedData($body);
1206 if (($siteinfo["type"] == "photo") && (!empty($siteinfo["preview"]) || !empty($siteinfo["image"]))) {
1207 if (isset($siteinfo["preview"])) {
1208 $preview = $siteinfo["preview"];
1210 $preview = $siteinfo["image"];
1213 // Is it a remote picture? Then make a smaller preview here
1214 $preview = ProxyUtils::proxifyUrl($preview, false, ProxyUtils::SIZE_SMALL);
1216 // Is it a local picture? Then make it smaller here
1217 $preview = str_replace(["-0.jpg", "-0.png"], ["-2.jpg", "-2.png"], $preview);
1218 $preview = str_replace(["-1.jpg", "-1.png"], ["-2.jpg", "-2.png"], $preview);
1220 if (isset($siteinfo["url"])) {
1221 $url = $siteinfo["url"];
1223 $url = $siteinfo["image"];
1226 $body = trim($siteinfo["text"])." [url]".$url."[/url]\n[img]".$preview."[/img]";
1233 * Adds the header elements to the XML document
1235 * @param DOMDocument $doc XML document
1236 * @param array $owner Contact data of the poster
1237 * @param string $filter The related feed filter (activity, posts or comments)
1239 * @return object header root element
1240 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1242 private static function addHeader(DOMDocument $doc, array $owner, $filter)
1244 $root = $doc->createElementNS(ActivityNamespace::ATOM1, 'feed');
1245 $doc->appendChild($root);
1247 $root->setAttribute("xmlns:thr", ActivityNamespace::THREAD);
1248 $root->setAttribute("xmlns:georss", ActivityNamespace::GEORSS);
1249 $root->setAttribute("xmlns:activity", ActivityNamespace::ACTIVITY);
1250 $root->setAttribute("xmlns:media", ActivityNamespace::MEDIA);
1251 $root->setAttribute("xmlns:poco", ActivityNamespace::POCO);
1252 $root->setAttribute("xmlns:ostatus", ActivityNamespace::OSTATUS);
1253 $root->setAttribute("xmlns:statusnet", ActivityNamespace::STATUSNET);
1254 $root->setAttribute("xmlns:mastodon", ActivityNamespace::MASTODON);
1257 $selfUri = '/feed/' . $owner["nick"] . '/';
1260 $title = DI::l10n()->t('%s\'s timeline', $owner['name']);
1261 $selfUri .= $filter;
1264 $title = DI::l10n()->t('%s\'s posts', $owner['name']);
1267 $title = DI::l10n()->t('%s\'s comments', $owner['name']);
1268 $selfUri .= $filter;
1272 $selfUri = "/dfrn_poll/" . $owner["nick"];
1274 $attributes = ["uri" => "https://friendi.ca", "version" => FRIENDICA_VERSION . "-" . DB_UPDATE_VERSION];
1275 XML::addElement($doc, $root, "generator", FRIENDICA_PLATFORM, $attributes);
1276 XML::addElement($doc, $root, "id", DI::baseUrl() . "/profile/" . $owner["nick"]);
1277 XML::addElement($doc, $root, "title", $title);
1278 XML::addElement($doc, $root, "subtitle", sprintf("Updates from %s on %s", $owner["name"], DI::config()->get('config', 'sitename')));
1279 XML::addElement($doc, $root, "logo", $owner["photo"]);
1280 XML::addElement($doc, $root, "updated", DateTimeFormat::utcNow(DateTimeFormat::ATOM));
1282 $author = self::addAuthor($doc, $owner, true);
1283 $root->appendChild($author);
1285 $attributes = ["href" => $owner["url"], "rel" => "alternate", "type" => "text/html"];
1286 XML::addElement($doc, $root, "link", "", $attributes);
1288 /// @TODO We have to find out what this is
1289 /// $attributes = array("href" => DI::baseUrl()."/sup",
1290 /// "rel" => "http://api.friendfeed.com/2008/03#sup",
1291 /// "type" => "application/json");
1292 /// XML::addElement($doc, $root, "link", "", $attributes);
1294 self::hublinks($doc, $root, $owner["nick"]);
1296 $attributes = ["href" => DI::baseUrl() . "/salmon/" . $owner["nick"], "rel" => "salmon"];
1297 XML::addElement($doc, $root, "link", "", $attributes);
1299 $attributes = ["href" => DI::baseUrl() . "/salmon/" . $owner["nick"], "rel" => "http://salmon-protocol.org/ns/salmon-replies"];
1300 XML::addElement($doc, $root, "link", "", $attributes);
1302 $attributes = ["href" => DI::baseUrl() . "/salmon/" . $owner["nick"], "rel" => "http://salmon-protocol.org/ns/salmon-mention"];
1303 XML::addElement($doc, $root, "link", "", $attributes);
1305 $attributes = ["href" => DI::baseUrl() . $selfUri, "rel" => "self", "type" => "application/atom+xml"];
1306 XML::addElement($doc, $root, "link", "", $attributes);
1308 if ($owner['contact-type'] == Contact::TYPE_COMMUNITY) {
1309 $condition = ['uid' => $owner['uid'], 'self' => false, 'pending' => false,
1310 'archive' => false, 'hidden' => false, 'blocked' => false];
1311 $members = DBA::count('contact', $condition);
1312 XML::addElement($doc, $root, "statusnet:group_info", "", ["member_count" => $members]);
1319 * Add the link to the push hubs to the XML document
1321 * @param DOMDocument $doc XML document
1322 * @param object $root XML root element where the hub links are added
1323 * @param object $nick nick
1325 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1327 public static function hublinks(DOMDocument $doc, $root, $nick)
1329 $h = DI::baseUrl() . '/pubsubhubbub/'.$nick;
1330 XML::addElement($doc, $root, "link", "", ["href" => $h, "rel" => "hub"]);
1334 * Adds attachment data to the XML document
1336 * @param DOMDocument $doc XML document
1337 * @param object $root XML root element where the hub links are added
1338 * @param array $item Data of the item that is to be posted
1340 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1342 public static function getAttachment(DOMDocument $doc, $root, $item)
1344 $siteinfo = BBCode::getAttachedData($item["body"]);
1346 switch ($siteinfo["type"]) {
1348 if (!empty($siteinfo["image"])) {
1349 $imgdata = Images::getInfoFromURLCached($siteinfo["image"]);
1351 $attributes = ["rel" => "enclosure",
1352 "href" => $siteinfo["image"],
1353 "type" => $imgdata["mime"],
1354 "length" => intval($imgdata["size"])];
1355 XML::addElement($doc, $root, "link", "", $attributes);
1360 $attributes = ["rel" => "enclosure",
1361 "href" => $siteinfo["url"],
1362 "type" => "text/html; charset=UTF-8",
1364 "title" => ($siteinfo["title"] ?? '') ?: $siteinfo["url"],
1366 XML::addElement($doc, $root, "link", "", $attributes);
1372 if (!DI::config()->get('system', 'ostatus_not_attach_preview') && ($siteinfo["type"] != "photo") && isset($siteinfo["image"])) {
1373 $imgdata = Images::getInfoFromURLCached($siteinfo["image"]);
1375 $attributes = ["rel" => "enclosure",
1376 "href" => $siteinfo["image"],
1377 "type" => $imgdata["mime"],
1378 "length" => intval($imgdata["size"])];
1380 XML::addElement($doc, $root, "link", "", $attributes);
1384 foreach (Post\Media::getByURIId($item['uri-id'], [Post\Media::DOCUMENT, Post\Media::TORRENT, Post\Media::UNKNOWN]) as $attachment) {
1385 $attributes = ['rel' => 'enclosure',
1386 'href' => $attachment['url'],
1387 'type' => $attachment['mimetype']];
1389 if (!empty($attachment['size'])) {
1390 $attributes['length'] = intval($attachment['size']);
1392 if (!empty($attachment['description'])) {
1393 $attributes['title'] = $attachment['description'];
1396 XML::addElement($doc, $root, 'link', '', $attributes);
1401 * Adds the author element to the XML document
1403 * @param DOMDocument $doc XML document
1404 * @param array $owner Contact data of the poster
1405 * @param bool $show_profile Whether to show profile
1407 * @return \DOMElement author element
1408 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1410 private static function addAuthor(DOMDocument $doc, array $owner, $show_profile = true)
1412 $profile = DBA::selectFirst('profile', ['homepage', 'publish'], ['uid' => $owner['uid']]);
1413 $author = $doc->createElement("author");
1414 XML::addElement($doc, $author, "id", $owner["url"]);
1415 if ($owner['contact-type'] == Contact::TYPE_COMMUNITY) {
1416 XML::addElement($doc, $author, "activity:object-type", Activity\ObjectType::GROUP);
1418 XML::addElement($doc, $author, "activity:object-type", Activity\ObjectType::PERSON);
1421 XML::addElement($doc, $author, "uri", $owner["url"]);
1422 XML::addElement($doc, $author, "name", $owner["nick"]);
1423 XML::addElement($doc, $author, "email", $owner["addr"]);
1424 if ($show_profile) {
1425 XML::addElement($doc, $author, "summary", BBCode::convert($owner["about"], false, BBCode::OSTATUS));
1428 $attributes = ["rel" => "alternate", "type" => "text/html", "href" => $owner["url"]];
1429 XML::addElement($doc, $author, "link", "", $attributes);
1433 "type" => "image/jpeg", // To-Do?
1434 "media:width" => 300,
1435 "media:height" => 300,
1436 "href" => $owner["photo"]];
1437 XML::addElement($doc, $author, "link", "", $attributes);
1439 if (isset($owner["thumb"])) {
1442 "type" => "image/jpeg", // To-Do?
1443 "media:width" => 80,
1444 "media:height" => 80,
1445 "href" => $owner["thumb"]];
1446 XML::addElement($doc, $author, "link", "", $attributes);
1449 XML::addElement($doc, $author, "poco:preferredUsername", $owner["nick"]);
1450 XML::addElement($doc, $author, "poco:displayName", $owner["name"]);
1451 if ($show_profile) {
1452 XML::addElement($doc, $author, "poco:note", BBCode::convert($owner["about"], false, BBCode::OSTATUS));
1454 if (trim($owner["location"]) != "") {
1455 $element = $doc->createElement("poco:address");
1456 XML::addElement($doc, $element, "poco:formatted", $owner["location"]);
1457 $author->appendChild($element);
1461 if (DBA::isResult($profile) && !$show_profile) {
1462 if (trim($profile["homepage"]) != "") {
1463 $urls = $doc->createElement("poco:urls");
1464 XML::addElement($doc, $urls, "poco:type", "homepage");
1465 XML::addElement($doc, $urls, "poco:value", $profile["homepage"]);
1466 XML::addElement($doc, $urls, "poco:primary", "true");
1467 $author->appendChild($urls);
1470 XML::addElement($doc, $author, "followers", "", ["url" => DI::baseUrl() . "/profile/" . $owner["nick"] . "/contacts/followers"]);
1471 XML::addElement($doc, $author, "statusnet:profile_info", "", ["local_id" => $owner["uid"]]);
1473 if ($profile["publish"]) {
1474 XML::addElement($doc, $author, "mastodon:scope", "public");
1482 * @TODO Picture attachments should look like this:
1483 * <a href="https://status.pirati.ca/attachment/572819" title="https://status.pirati.ca/file/heluecht-20151202T222602-rd3u49p.gif"
1484 * class="attachment thumbnail" id="attachment-572819" rel="nofollow external">https://status.pirati.ca/attachment/572819</a>
1488 * Returns the given activity if present - otherwise returns the "post" activity
1490 * @param array $item Data of the item that is to be posted
1492 * @return string activity
1494 public static function constructVerb(array $item)
1496 if (!empty($item['verb'])) {
1497 return $item['verb'];
1500 return Activity::POST;
1504 * Returns the given object type if present - otherwise returns the "note" object type
1506 * @param array $item Data of the item that is to be posted
1508 * @return string Object type
1510 private static function constructObjecttype(array $item)
1512 if (!empty($item['object-type']) && in_array($item['object-type'], [Activity\ObjectType::NOTE, Activity\ObjectType::COMMENT])) {
1513 return $item['object-type'];
1516 return Activity\ObjectType::NOTE;
1520 * Adds an entry element to the XML document
1522 * @param DOMDocument $doc XML document
1523 * @param array $item Data of the item that is to be posted
1524 * @param array $owner Contact data of the poster
1525 * @param bool $toplevel optional default false
1527 * @return \DOMElement Entry element
1528 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1529 * @throws \ImagickException
1531 private static function entry(DOMDocument $doc, array $item, array $owner, $toplevel = false)
1535 $repeated_guid = self::getResharedGuid($item);
1536 if ($repeated_guid != "") {
1537 $xml = self::reshareEntry($doc, $item, $owner, $repeated_guid, $toplevel);
1544 if ($item["verb"] == Activity::LIKE) {
1545 return self::likeEntry($doc, $item, $owner, $toplevel);
1546 } elseif (in_array($item["verb"], [Activity::FOLLOW, Activity::O_UNFOLLOW])) {
1547 return self::followEntry($doc, $item, $owner, $toplevel);
1549 return self::noteEntry($doc, $item, $owner, $toplevel);
1554 * Adds a source entry to the XML document
1556 * @param DOMDocument $doc XML document
1557 * @param array $contact Array of the contact that is added
1559 * @return \DOMElement Source element
1560 * @throws \Exception
1562 private static function sourceEntry(DOMDocument $doc, array $contact)
1564 $source = $doc->createElement("source");
1565 XML::addElement($doc, $source, "id", $contact["poll"]);
1566 XML::addElement($doc, $source, "title", $contact["name"]);
1567 XML::addElement($doc, $source, "link", "", ["rel" => "alternate", "type" => "text/html", "href" => $contact["alias"]]);
1568 XML::addElement($doc, $source, "link", "", ["rel" => "self", "type" => "application/atom+xml", "href" => $contact["poll"]]);
1569 XML::addElement($doc, $source, "icon", $contact["photo"]);
1570 XML::addElement($doc, $source, "updated", DateTimeFormat::utc($contact["success_update"]."+00:00", DateTimeFormat::ATOM));
1576 * Adds an entry element with reshared content
1578 * @param DOMDocument $doc XML document
1579 * @param array $item Data of the item that is to be posted
1580 * @param array $owner Contact data of the poster
1581 * @param string $repeated_guid guid
1582 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1584 * @return bool Entry element
1585 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1586 * @throws \ImagickException
1588 private static function reshareEntry(DOMDocument $doc, array $item, array $owner, $repeated_guid, $toplevel)
1590 if (($item['gravity'] != GRAVITY_PARENT) && (Strings::normaliseLink($item["author-link"]) != Strings::normaliseLink($owner["url"]))) {
1591 Logger::log("OStatus entry is from author ".$owner["url"]." - not from ".$item["author-link"].". Quitting.", Logger::DEBUG);
1594 $entry = self::entryHeader($doc, $owner, $item, $toplevel);
1596 $condition = ['uid' => $owner["uid"], 'guid' => $repeated_guid, 'private' => [Item::PUBLIC, Item::UNLISTED],
1597 'network' => [Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS]];
1598 $repeated_item = Item::selectFirst([], $condition);
1599 if (!DBA::isResult($repeated_item)) {
1603 $contact = Contact::getByURL($repeated_item['author-link']) ?: $owner;
1605 $title = $owner["nick"]." repeated a notice by ".$contact["nick"];
1607 self::entryContent($doc, $entry, $item, $owner, $title, Activity::SHARE, false);
1609 $as_object = $doc->createElement("activity:object");
1611 XML::addElement($doc, $as_object, "activity:object-type", ActivityNamespace::ACTIVITY_SCHEMA . "activity");
1613 self::entryContent($doc, $as_object, $repeated_item, $owner, "", "", false);
1615 $author = self::addAuthor($doc, $contact, false);
1616 $as_object->appendChild($author);
1618 $as_object2 = $doc->createElement("activity:object");
1620 XML::addElement($doc, $as_object2, "activity:object-type", self::constructObjecttype($repeated_item));
1622 $title = sprintf("New comment by %s", $contact["nick"]);
1624 self::entryContent($doc, $as_object2, $repeated_item, $owner, $title);
1626 $as_object->appendChild($as_object2);
1628 self::entryFooter($doc, $as_object, $item, $owner, false);
1630 $source = self::sourceEntry($doc, $contact);
1632 $as_object->appendChild($source);
1634 $entry->appendChild($as_object);
1636 self::entryFooter($doc, $entry, $item, $owner, true);
1642 * Adds an entry element with a "like"
1644 * @param DOMDocument $doc XML document
1645 * @param array $item Data of the item that is to be posted
1646 * @param array $owner Contact data of the poster
1647 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1649 * @return \DOMElement Entry element with "like"
1650 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1651 * @throws \ImagickException
1653 private static function likeEntry(DOMDocument $doc, array $item, array $owner, $toplevel)
1655 if (($item['gravity'] != GRAVITY_PARENT) && (Strings::normaliseLink($item["author-link"]) != Strings::normaliseLink($owner["url"]))) {
1656 Logger::log("OStatus entry is from author ".$owner["url"]." - not from ".$item["author-link"].". Quitting.", Logger::DEBUG);
1659 $entry = self::entryHeader($doc, $owner, $item, $toplevel);
1661 $verb = ActivityNamespace::ACTIVITY_SCHEMA . "favorite";
1662 self::entryContent($doc, $entry, $item, $owner, "Favorite", $verb, false);
1664 $parent = Item::selectFirst([], ['uri' => $item["thr-parent"], 'uid' => $item["uid"]]);
1665 if (DBA::isResult($parent)) {
1666 $as_object = $doc->createElement("activity:object");
1668 XML::addElement($doc, $as_object, "activity:object-type", self::constructObjecttype($parent));
1670 self::entryContent($doc, $as_object, $parent, $owner, "New entry");
1672 $entry->appendChild($as_object);
1675 self::entryFooter($doc, $entry, $item, $owner);
1681 * Adds the person object element to the XML document
1683 * @param DOMDocument $doc XML document
1684 * @param array $owner Contact data of the poster
1685 * @param array $contact Contact data of the target
1687 * @return object author element
1689 private static function addPersonObject(DOMDocument $doc, array $owner, array $contact)
1691 $object = $doc->createElement("activity:object");
1692 XML::addElement($doc, $object, "activity:object-type", Activity\ObjectType::PERSON);
1694 if ($contact['network'] == Protocol::PHANTOM) {
1695 XML::addElement($doc, $object, "id", $contact['url']);
1699 XML::addElement($doc, $object, "id", $contact["alias"]);
1700 XML::addElement($doc, $object, "title", $contact["nick"]);
1702 $attributes = ["rel" => "alternate", "type" => "text/html", "href" => $contact["url"]];
1703 XML::addElement($doc, $object, "link", "", $attributes);
1707 "type" => "image/jpeg", // To-Do?
1708 "media:width" => 300,
1709 "media:height" => 300,
1710 "href" => $contact["photo"]];
1711 XML::addElement($doc, $object, "link", "", $attributes);
1713 XML::addElement($doc, $object, "poco:preferredUsername", $contact["nick"]);
1714 XML::addElement($doc, $object, "poco:displayName", $contact["name"]);
1716 if (trim($contact["location"]) != "") {
1717 $element = $doc->createElement("poco:address");
1718 XML::addElement($doc, $element, "poco:formatted", $contact["location"]);
1719 $object->appendChild($element);
1726 * Adds a follow/unfollow entry element
1728 * @param DOMDocument $doc XML document
1729 * @param array $item Data of the follow/unfollow message
1730 * @param array $owner Contact data of the poster
1731 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1733 * @return \DOMElement Entry element
1734 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1735 * @throws \ImagickException
1737 private static function followEntry(DOMDocument $doc, array $item, array $owner, $toplevel)
1739 $item["id"] = $item['parent'] = 0;
1740 $item["created"] = $item["edited"] = date("c");
1741 $item["private"] = Item::PRIVATE;
1743 $contact = Contact::getByURL($item['follow']);
1744 $item['follow'] = $contact['url'];
1746 if ($contact['alias']) {
1747 $item['follow'] = $contact['alias'];
1749 $contact['alias'] = $contact['url'];
1752 $condition = ['uid' => $owner['uid'], 'nurl' => Strings::normaliseLink($contact["url"])];
1753 $user_contact = DBA::selectFirst('contact', ['id'], $condition);
1755 if (DBA::isResult($user_contact)) {
1756 $connect_id = $user_contact['id'];
1761 if ($item['verb'] == Activity::FOLLOW) {
1762 $message = DI::l10n()->t('%s is now following %s.');
1763 $title = DI::l10n()->t('following');
1764 $action = "subscription";
1766 $message = DI::l10n()->t('%s stopped following %s.');
1767 $title = DI::l10n()->t('stopped following');
1768 $action = "unfollow";
1771 $item["uri"] = $item['parent-uri'] = $item['thr-parent']
1772 = 'tag:' . DI::baseUrl()->getHostname().
1773 ','.date('Y-m-d').':'.$action.':'.$owner['uid'].
1774 ':person:'.$connect_id.':'.$item['created'];
1776 $item["body"] = sprintf($message, $owner["nick"], $contact["nick"]);
1778 $entry = self::entryHeader($doc, $owner, $item, $toplevel);
1780 self::entryContent($doc, $entry, $item, $owner, $title);
1782 $object = self::addPersonObject($doc, $owner, $contact);
1783 $entry->appendChild($object);
1785 self::entryFooter($doc, $entry, $item, $owner);
1791 * Adds a regular entry element
1793 * @param DOMDocument $doc XML document
1794 * @param array $item Data of the item that is to be posted
1795 * @param array $owner Contact data of the poster
1796 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1798 * @return \DOMElement Entry element
1799 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1800 * @throws \ImagickException
1802 private static function noteEntry(DOMDocument $doc, array $item, array $owner, $toplevel)
1804 if (($item['gravity'] != GRAVITY_PARENT) && (Strings::normaliseLink($item["author-link"]) != Strings::normaliseLink($owner["url"]))) {
1805 Logger::log("OStatus entry is from author ".$owner["url"]." - not from ".$item["author-link"].". Quitting.", Logger::DEBUG);
1809 if (!empty($item['title'])) {
1810 $title = BBCode::convert($item['title'], false, BBCode::OSTATUS);
1812 $title = sprintf("New note by %s", $owner["nick"]);
1815 $title = sprintf("New comment by %s", $owner["nick"]);
1818 $entry = self::entryHeader($doc, $owner, $item, $toplevel);
1820 XML::addElement($doc, $entry, "activity:object-type", Activity\ObjectType::NOTE);
1822 self::entryContent($doc, $entry, $item, $owner, $title, '', true);
1824 self::entryFooter($doc, $entry, $item, $owner, true);
1830 * Adds a header element to the XML document
1832 * @param DOMDocument $doc XML document
1833 * @param array $owner Contact data of the poster
1834 * @param array $item
1835 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1837 * @return \DOMElement The entry element where the elements are added
1838 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1839 * @throws \ImagickException
1841 public static function entryHeader(DOMDocument $doc, array $owner, array $item, $toplevel)
1844 $entry = $doc->createElement("entry");
1846 if ($owner['contact-type'] == Contact::TYPE_COMMUNITY) {
1847 $contact = Contact::getByURL($item['author-link']) ?: $owner;
1848 $author = self::addAuthor($doc, $contact, false);
1849 $entry->appendChild($author);
1852 $entry = $doc->createElementNS(ActivityNamespace::ATOM1, "entry");
1854 $entry->setAttribute("xmlns:thr", ActivityNamespace::THREAD);
1855 $entry->setAttribute("xmlns:georss", ActivityNamespace::GEORSS);
1856 $entry->setAttribute("xmlns:activity", ActivityNamespace::ACTIVITY);
1857 $entry->setAttribute("xmlns:media", ActivityNamespace::MEDIA);
1858 $entry->setAttribute("xmlns:poco", ActivityNamespace::POCO);
1859 $entry->setAttribute("xmlns:ostatus", ActivityNamespace::OSTATUS);
1860 $entry->setAttribute("xmlns:statusnet", ActivityNamespace::STATUSNET);
1861 $entry->setAttribute("xmlns:mastodon", ActivityNamespace::MASTODON);
1863 $author = self::addAuthor($doc, $owner);
1864 $entry->appendChild($author);
1871 * Adds elements to the XML document
1873 * @param DOMDocument $doc XML document
1874 * @param \DOMElement $entry Entry element where the content is added
1875 * @param array $item Data of the item that is to be posted
1876 * @param array $owner Contact data of the poster
1877 * @param string $title Title for the post
1878 * @param string $verb The activity verb
1879 * @param bool $complete Add the "status_net" element?
1881 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1883 private static function entryContent(DOMDocument $doc, \DOMElement $entry, array $item, array $owner, $title, $verb = "", $complete = true)
1886 $verb = self::constructVerb($item);
1889 XML::addElement($doc, $entry, "id", $item["uri"]);
1890 XML::addElement($doc, $entry, "title", html_entity_decode($title, ENT_QUOTES, 'UTF-8'));
1892 $body = self::formatPicturePost($item['body']);
1894 if (!empty($item['title'])) {
1895 $body = "[b]".$item['title']."[/b]\n\n".$body;
1898 $body = BBCode::convert($body, false, BBCode::OSTATUS);
1900 XML::addElement($doc, $entry, "content", $body, ["type" => "html"]);
1902 XML::addElement($doc, $entry, "link", "", ["rel" => "alternate", "type" => "text/html",
1903 "href" => DI::baseUrl()."/display/".$item["guid"]]
1906 if ($complete && ($item["id"] > 0)) {
1907 XML::addElement($doc, $entry, "status_net", "", ["notice_id" => $item["id"]]);
1910 XML::addElement($doc, $entry, "activity:verb", $verb);
1912 XML::addElement($doc, $entry, "published", DateTimeFormat::utc($item["created"]."+00:00", DateTimeFormat::ATOM));
1913 XML::addElement($doc, $entry, "updated", DateTimeFormat::utc($item["edited"]."+00:00", DateTimeFormat::ATOM));
1917 * Adds the elements at the foot of an entry to the XML document
1919 * @param DOMDocument $doc XML document
1920 * @param object $entry The entry element where the elements are added
1921 * @param array $item Data of the item that is to be posted
1922 * @param array $owner Contact data of the poster
1923 * @param bool $complete default true
1925 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1927 private static function entryFooter(DOMDocument $doc, $entry, array $item, array $owner, $complete = true)
1931 if ($item['gravity'] != GRAVITY_PARENT) {
1932 $parent = Item::selectFirst(['guid', 'author-link', 'owner-link'], ['id' => $item['parent']]);
1934 $thrparent = Item::selectFirst(['guid', 'author-link', 'owner-link', 'plink'], ['uid' => $owner["uid"], 'uri' => $item['thr-parent']]);
1936 if (DBA::isResult($thrparent)) {
1937 $mentioned[$thrparent["author-link"]] = $thrparent["author-link"];
1938 $mentioned[$thrparent["owner-link"]] = $thrparent["owner-link"];
1939 $parent_plink = $thrparent["plink"];
1941 $mentioned[$parent["author-link"]] = $parent["author-link"];
1942 $mentioned[$parent["owner-link"]] = $parent["owner-link"];
1943 $parent_plink = DI::baseUrl()."/display/".$parent["guid"];
1947 "ref" => $item['thr-parent'],
1948 "href" => $parent_plink];
1949 XML::addElement($doc, $entry, "thr:in-reply-to", "", $attributes);
1953 "href" => $parent_plink];
1954 XML::addElement($doc, $entry, "link", "", $attributes);
1957 if (intval($item['parent']) > 0) {
1958 $conversation_href = $conversation_uri = str_replace('/objects/', '/context/', $item['thr-parent']);
1960 if (isset($parent_item)) {
1961 $conversation = DBA::selectFirst('conversation', ['conversation-uri', 'conversation-href'], ['item-uri' => $parent_item]);
1962 if (DBA::isResult($conversation)) {
1963 if ($conversation['conversation-uri'] != '') {
1964 $conversation_uri = $conversation['conversation-uri'];
1966 if ($conversation['conversation-href'] != '') {
1967 $conversation_href = $conversation['conversation-href'];
1972 XML::addElement($doc, $entry, "link", "", ["rel" => "ostatus:conversation", "href" => $conversation_href]);
1975 "href" => $conversation_href,
1976 "local_id" => $item['parent'],
1977 "ref" => $conversation_uri];
1979 XML::addElement($doc, $entry, "ostatus:conversation", $conversation_uri, $attributes);
1982 // uri-id isn't present for follow entry pseudo-items
1983 $tags = Tag::getByURIId($item['uri-id'] ?? 0);
1984 foreach ($tags as $tag) {
1985 $mentioned[$tag['url']] = $tag['url'];
1988 // Make sure that mentions are accepted (GNU Social has problems with mixing HTTP and HTTPS)
1990 foreach ($mentioned as $mention) {
1991 $newmentions[str_replace("http://", "https://", $mention)] = str_replace("http://", "https://", $mention);
1992 $newmentions[str_replace("https://", "http://", $mention)] = str_replace("https://", "http://", $mention);
1994 $mentioned = $newmentions;
1996 foreach ($mentioned as $mention) {
1997 $contact = Contact::getByURL($mention, false, ['contact-type']);
1998 if (!empty($contact) && ($contact['contact-type'] == Contact::TYPE_COMMUNITY)) {
1999 XML::addElement($doc, $entry, "link", "",
2001 "rel" => "mentioned",
2002 "ostatus:object-type" => Activity\ObjectType::GROUP,
2006 XML::addElement($doc, $entry, "link", "",
2008 "rel" => "mentioned",
2009 "ostatus:object-type" => Activity\ObjectType::PERSON,
2015 if ($owner['contact-type'] == Contact::TYPE_COMMUNITY) {
2016 XML::addElement($doc, $entry, "link", "", [
2017 "rel" => "mentioned",
2018 "ostatus:object-type" => "http://activitystrea.ms/schema/1.0/group",
2019 "href" => $owner['url']
2023 if ($item['private'] != Item::PRIVATE) {
2024 XML::addElement($doc, $entry, "link", "", ["rel" => "ostatus:attention",
2025 "href" => "http://activityschema.org/collection/public"]);
2026 XML::addElement($doc, $entry, "link", "", ["rel" => "mentioned",
2027 "ostatus:object-type" => "http://activitystrea.ms/schema/1.0/collection",
2028 "href" => "http://activityschema.org/collection/public"]);
2029 XML::addElement($doc, $entry, "mastodon:scope", "public");
2032 foreach ($tags as $tag) {
2033 if ($tag['type'] == Tag::HASHTAG) {
2034 XML::addElement($doc, $entry, "category", "", ["term" => $tag['name']]);
2038 self::getAttachment($doc, $entry, $item);
2040 if ($complete && ($item["id"] > 0)) {
2041 $app = $item["app"];
2046 $attributes = ["local_id" => $item["id"], "source" => $app];
2048 if (isset($parent["id"])) {
2049 $attributes["repeat_of"] = $parent["id"];
2052 if ($item["coord"] != "") {
2053 XML::addElement($doc, $entry, "georss:point", $item["coord"]);
2056 XML::addElement($doc, $entry, "statusnet:notice_info", "", $attributes);
2061 * Creates the XML feed for a given nickname
2063 * Supported filters:
2064 * - activity (default): all the public posts
2065 * - posts: all the public top-level posts
2066 * - comments: all the public replies
2068 * Updates the provided last_update parameter if the result comes from the
2069 * cache or it is empty
2071 * @param string $owner_nick Nickname of the feed owner
2072 * @param string $last_update Date of the last update
2073 * @param integer $max_items Number of maximum items to fetch
2074 * @param string $filter Feed items filter (activity, posts or comments)
2075 * @param boolean $nocache Wether to bypass caching
2077 * @return string XML feed
2078 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2079 * @throws \ImagickException
2081 public static function feed($owner_nick, &$last_update, $max_items = 300, $filter = 'activity', $nocache = false)
2083 $stamp = microtime(true);
2085 $owner = User::getOwnerDataByNick($owner_nick);
2090 $cachekey = "ostatus:feed:" . $owner_nick . ":" . $filter . ":" . $last_update;
2092 $previous_created = $last_update;
2094 // Don't cache when the last item was posted less then 15 minutes ago (Cache duration)
2095 if ((time() - strtotime($owner['last-item'])) < 15*60) {
2096 $result = DI::cache()->get($cachekey);
2097 if (!$nocache && !is_null($result)) {
2098 Logger::log('Feed duration: ' . number_format(microtime(true) - $stamp, 3) . ' - ' . $owner_nick . ' - ' . $filter . ' - ' . $previous_created . ' (cached)', Logger::DEBUG);
2099 $last_update = $result['last_update'];
2100 return $result['feed'];
2104 if (!strlen($last_update)) {
2105 $last_update = 'now -30 days';
2108 $check_date = DateTimeFormat::utc($last_update);
2109 $authorid = Contact::getIdForURL($owner["url"]);
2111 $condition = ["`uid` = ? AND `received` > ? AND NOT `deleted`
2112 AND `private` != ? AND `visible` AND `wall` AND `parent-network` IN (?, ?)",
2113 $owner["uid"], $check_date, Item::PRIVATE, Protocol::OSTATUS, Protocol::DFRN];
2115 if ($filter === 'comments') {
2116 $condition[0] .= " AND `object-type` = ? ";
2117 $condition[] = Activity\ObjectType::COMMENT;
2120 if ($owner['contact-type'] != Contact::TYPE_COMMUNITY) {
2121 $condition[0] .= " AND `contact-id` = ? AND `author-id` = ?";
2122 $condition[] = $owner["id"];
2123 $condition[] = $authorid;
2126 $params = ['order' => ['received' => true], 'limit' => $max_items];
2128 if ($filter === 'posts') {
2129 $ret = Item::selectThread([], $condition, $params);
2131 $ret = Item::select([], $condition, $params);
2134 $items = Item::inArray($ret);
2136 $doc = new DOMDocument('1.0', 'utf-8');
2137 $doc->formatOutput = true;
2139 $root = self::addHeader($doc, $owner, $filter);
2141 foreach ($items as $item) {
2142 if (DI::config()->get('system', 'ostatus_debug')) {
2143 $item['body'] .= '🍼';
2146 if (in_array($item["verb"], [Activity::FOLLOW, Activity::O_UNFOLLOW, Activity::LIKE])) {
2150 $entry = self::entry($doc, $item, $owner, false);
2151 $root->appendChild($entry);
2153 if ($last_update < $item['created']) {
2154 $last_update = $item['created'];
2158 $feeddata = trim($doc->saveXML());
2160 $msg = ['feed' => $feeddata, 'last_update' => $last_update];
2161 DI::cache()->set($cachekey, $msg, Duration::QUARTER_HOUR);
2163 Logger::log('Feed duration: ' . number_format(microtime(true) - $stamp, 3) . ' - ' . $owner_nick . ' - ' . $filter . ' - ' . $previous_created, Logger::DEBUG);
2169 * Creates the XML for a salmon message
2171 * @param array $item Data of the item that is to be posted
2172 * @param array $owner Contact data of the poster
2174 * @return string XML for the salmon
2175 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2176 * @throws \ImagickException
2178 public static function salmon(array $item, array $owner)
2180 $doc = new DOMDocument('1.0', 'utf-8');
2181 $doc->formatOutput = true;
2183 if (DI::config()->get('system', 'ostatus_debug')) {
2184 $item['body'] .= '🐟';
2187 $entry = self::entry($doc, $item, $owner, true);
2189 $doc->appendChild($entry);
2191 return trim($doc->saveXML());
2195 * Checks if the given contact url does support OStatus
2197 * @param string $url profile url
2199 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2200 * @throws \ImagickException
2202 public static function isSupportedByContactUrl($url)
2204 $probe = Probe::uri($url, Protocol::OSTATUS);
2205 return $probe['network'] == Protocol::OSTATUS;