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' => $self, 'protocol' => [Conversation::PARCEL_DFRN,
879 Conversation::PARCEL_DIASPORA_DFRN, Conversation::PARCEL_LEGACY_DFRN,
880 Conversation::PARCEL_LOCAL_DFRN, Conversation::PARCEL_DIRECT, Conversation::PARCEL_SALMON]];
881 if (DBA::exists('conversation', $condition)) {
882 Logger::log('Conversation '.$item['uri'].' is already stored.', Logger::DEBUG);
886 $curlResult = DI::httpRequest()->get($self);
888 if (!$curlResult->isSuccess()) {
892 // We reformat the XML to make it better readable
893 $doc = new DOMDocument();
894 $doc->loadXML($curlResult->getBody());
895 $doc->preserveWhiteSpace = false;
896 $doc->formatOutput = true;
897 $xml = $doc->saveXML();
899 $item["protocol"] = Conversation::PARCEL_SALMON;
900 $item["source"] = $xml;
902 Logger::log('Conversation '.$item['uri'].' is now fetched.', Logger::DEBUG);
906 * Fetch related posts and processes them
908 * @param string $related The link to the related item
909 * @param string $related_uri The related item in "uri" format
910 * @param array $importer user record of the importing user
912 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
913 * @throws \ImagickException
915 private static function fetchRelated($related, $related_uri, $importer)
917 $condition = ['item-uri' => $related_uri, 'protocol' => [Conversation::PARCEL_DFRN,
918 Conversation::PARCEL_DIASPORA_DFRN, Conversation::PARCEL_LEGACY_DFRN,
919 Conversation::PARCEL_LOCAL_DFRN, Conversation::PARCEL_DIRECT, Conversation::PARCEL_SALMON]];
920 if (DBA::exists('conversation', $condition)) {
921 $conversation = DBA::selectFirst('conversation', ['source', 'protocol'], $condition);
922 if (DBA::isResult($conversation)) {
924 $xml = $conversation['source'];
925 if (self::process($xml, $importer, $contact, $hub, $stored, false)) {
926 Logger::log('Got valid cached XML for URI '.$related_uri, Logger::DEBUG);
929 if ($conversation['protocol'] == Conversation::PARCEL_SALMON) {
930 Logger::log('Delete invalid cached XML for URI '.$related_uri, Logger::DEBUG);
931 DBA::delete('conversation', ['item-uri' => $related_uri]);
936 $curlResult = DI::httpRequest()->get($related, ['accept_content' => 'application/atom+xml, text/html']);
938 if (!$curlResult->isSuccess()) {
944 if (stristr($curlResult->getHeader(), 'Content-Type: application/atom+xml')) {
945 Logger::log('Directly fetched XML for URI ' . $related_uri, Logger::DEBUG);
946 $xml = $curlResult->getBody();
950 $doc = new DOMDocument();
951 if (!@$doc->loadHTML($curlResult->getBody())) {
954 $xpath = new DOMXPath($doc);
958 $links = $xpath->query('//link');
960 foreach ($links as $link) {
961 $attribute = self::readAttributes($link);
962 if (($attribute['rel'] == 'alternate') && ($attribute['type'] == 'application/atom+xml')) {
963 $atom_file = $attribute['href'];
966 if ($atom_file != '') {
967 $curlResult = DI::httpRequest()->get($atom_file);
969 if ($curlResult->isSuccess()) {
970 Logger::log('Fetched XML for URI ' . $related_uri, Logger::DEBUG);
971 $xml = $curlResult->getBody();
977 // Workaround for older GNU Social servers
978 if (($xml == '') && strstr($related, '/notice/')) {
979 $curlResult = DI::httpRequest()->get(str_replace('/notice/', '/api/statuses/show/', $related) . '.atom');
981 if ($curlResult->isSuccess()) {
982 Logger::log('GNU Social workaround to fetch XML for URI ' . $related_uri, Logger::DEBUG);
983 $xml = $curlResult->getBody();
987 // Even more worse workaround for GNU Social ;-)
989 $related_guess = self::convertHref($related_uri);
990 $curlResult = DI::httpRequest()->get(str_replace('/notice/', '/api/statuses/show/', $related_guess) . '.atom');
992 if ($curlResult->isSuccess()) {
993 Logger::log('GNU Social workaround 2 to fetch XML for URI ' . $related_uri, Logger::DEBUG);
994 $xml = $curlResult->getBody();
998 // Finally we take the data that we fetched from "ostatus:conversation"
1000 $condition = ['item-uri' => $related_uri, 'protocol' => Conversation::PARCEL_SPLIT_CONVERSATION];
1001 $conversation = DBA::selectFirst('conversation', ['source'], $condition);
1002 if (DBA::isResult($conversation)) {
1004 Logger::log('Got cached XML from conversation for URI '.$related_uri, Logger::DEBUG);
1005 $xml = $conversation['source'];
1010 self::process($xml, $importer, $contact, $hub, $stored, false);
1012 Logger::log("XML couldn't be fetched for URI: ".$related_uri." - href: ".$related, Logger::DEBUG);
1018 * Processes the XML for a repeated post
1020 * @param DOMXPath $xpath The xpath object
1021 * @param object $entry The xml entry that is processed
1022 * @param array $item The item array
1023 * @param array $importer user record of the importing user
1025 * @return array with data from links
1026 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1027 * @throws \ImagickException
1029 private static function processRepeatedItem(DOMXPath $xpath, $entry, array &$item, array $importer)
1031 $activityobject = $xpath->query('activity:object', $entry)->item(0);
1033 if (!is_object($activityobject)) {
1039 $orig_uri = XML::getFirstNodeValue($xpath, 'atom:id/text()', $activityobject);
1041 $links = $xpath->query("atom:link", $activityobject);
1043 $link_data = self::processLinks($links, $item);
1046 $orig_body = XML::getFirstNodeValue($xpath, 'atom:content/text()', $activityobject);
1047 $orig_created = XML::getFirstNodeValue($xpath, 'atom:published/text()', $activityobject);
1048 $orig_edited = XML::getFirstNodeValue($xpath, 'atom:updated/text()', $activityobject);
1050 $orig_author = self::fetchAuthor($xpath, $activityobject, $importer, $dummy, false);
1052 $item["author-name"] = $orig_author["author-name"];
1053 $item["author-link"] = $orig_author["author-link"];
1054 $item["author-id"] = $orig_author["author-id"];
1056 $item["body"] = HTML::toBBCode($orig_body);
1057 $item["created"] = $orig_created;
1058 $item["edited"] = $orig_edited;
1060 $item["uri"] = $orig_uri;
1062 $item["verb"] = XML::getFirstNodeValue($xpath, 'activity:verb/text()', $activityobject);
1064 $item["object-type"] = XML::getFirstNodeValue($xpath, 'activity:object-type/text()', $activityobject);
1066 // Mastodon Content Warning
1067 if (($item["verb"] == Activity::POST) && $xpath->evaluate('boolean(atom:summary)', $activityobject)) {
1068 $clear_text = XML::getFirstNodeValue($xpath, 'atom:summary/text()', $activityobject);
1069 if (!empty($clear_text)) {
1070 $item['content-warning'] = HTML::toBBCode($clear_text);
1074 $inreplyto = $xpath->query('thr:in-reply-to', $activityobject);
1075 if (is_object($inreplyto->item(0))) {
1076 foreach ($inreplyto->item(0)->attributes as $attributes) {
1077 if ($attributes->name == "ref") {
1078 $item["thr-parent"] = $attributes->textContent;
1087 * Processes links in the XML
1089 * @param object $links The xml data that contain links
1090 * @param array $item The item array
1092 * @return array with data from the links
1094 private static function processLinks($links, array &$item)
1096 $link_data = ['add_body' => '', 'self' => ''];
1098 foreach ($links as $link) {
1099 $attribute = self::readAttributes($link);
1101 if (!empty($attribute['rel']) && !empty($attribute['href'])) {
1102 switch ($attribute['rel']) {
1104 $item["plink"] = $attribute['href'];
1105 if (($item["object-type"] == Activity\ObjectType::QUESTION)
1106 || ($item["object-type"] == Activity\ObjectType::EVENT)
1108 $item["body"] .= "\n" . PageInfo::getFooterFromUrl($attribute['href']);
1111 case "ostatus:conversation":
1112 $link_data['conversation'] = $attribute['href'];
1113 $item['conversation-href'] = $link_data['conversation'];
1114 if (!isset($item['conversation-uri'])) {
1115 $item['conversation-uri'] = $item['conversation-href'];
1119 $filetype = strtolower(substr($attribute['type'], 0, strpos($attribute['type'], '/')));
1120 if ($filetype == 'image') {
1121 $link_data['add_body'] .= "\n[img]".$attribute['href'].'[/img]';
1123 Post\Media::insert(['uri-id' => $item['uri-id'], 'type' => Post\Media::DOCUMENT,
1124 'url' => $attribute['href'], 'mimetype' => $attribute['type'],
1125 'size' => $attribute['length'] ?? null, 'description' => $attribute['title'] ?? null]);
1129 if ($item["object-type"] != Activity\ObjectType::BOOKMARK) {
1130 if (!isset($item["thr-parent"])) {
1131 $item["thr-parent"] = $attribute['href'];
1133 $link_data['related'] = $attribute['href'];
1135 $item["body"] .= "\n" . PageInfo::getFooterFromUrl($attribute['href']);
1139 if (empty($item["plink"])) {
1140 $item["plink"] = $attribute['href'];
1142 $link_data['self'] = $attribute['href'];
1151 * Create an url out of an uri
1153 * @param string $href URI in the format "parameter1:parameter1:..."
1155 * @return string URL in the format http(s)://....
1157 private static function convertHref($href)
1159 $elements = explode(":", $href);
1161 if ((count($elements) <= 2) || ($elements[0] != "tag")) {
1165 $server = explode(",", $elements[1]);
1166 $conversation = explode("=", $elements[2]);
1168 if ((count($elements) == 4) && ($elements[2] == "post")) {
1169 return "http://".$server[0]."/notice/".$elements[3];
1172 if ((count($conversation) != 2) || ($conversation[1] =="")) {
1175 if ($elements[3] == "objectType=thread") {
1176 return "http://".$server[0]."/conversation/".$conversation[1];
1178 return "http://".$server[0]."/notice/".$conversation[1];
1183 * Checks if the current post is a reshare
1185 * @param array $item The item array of thw post
1187 * @return string The guid if the post is a reshare
1189 public static function getResharedGuid(array $item)
1191 $reshared = Item::getShareArray($item);
1192 if (empty($reshared['guid']) || !empty($reshared['comment'])) {
1196 return $reshared['guid'];
1200 * Cleans the body of a post if it contains picture links
1202 * @param string $body The body
1204 * @return string The cleaned body
1205 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1207 public static function formatPicturePost($body)
1209 $siteinfo = BBCode::getAttachedData($body);
1211 if (($siteinfo["type"] == "photo") && (!empty($siteinfo["preview"]) || !empty($siteinfo["image"]))) {
1212 if (isset($siteinfo["preview"])) {
1213 $preview = $siteinfo["preview"];
1215 $preview = $siteinfo["image"];
1218 // Is it a remote picture? Then make a smaller preview here
1219 $preview = ProxyUtils::proxifyUrl($preview, false, ProxyUtils::SIZE_SMALL);
1221 // Is it a local picture? Then make it smaller here
1222 $preview = str_replace(["-0.jpg", "-0.png"], ["-2.jpg", "-2.png"], $preview);
1223 $preview = str_replace(["-1.jpg", "-1.png"], ["-2.jpg", "-2.png"], $preview);
1225 if (isset($siteinfo["url"])) {
1226 $url = $siteinfo["url"];
1228 $url = $siteinfo["image"];
1231 $body = trim($siteinfo["text"])." [url]".$url."[/url]\n[img]".$preview."[/img]";
1238 * Adds the header elements to the XML document
1240 * @param DOMDocument $doc XML document
1241 * @param array $owner Contact data of the poster
1242 * @param string $filter The related feed filter (activity, posts or comments)
1244 * @return object header root element
1245 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1247 private static function addHeader(DOMDocument $doc, array $owner, $filter)
1249 $root = $doc->createElementNS(ActivityNamespace::ATOM1, 'feed');
1250 $doc->appendChild($root);
1252 $root->setAttribute("xmlns:thr", ActivityNamespace::THREAD);
1253 $root->setAttribute("xmlns:georss", ActivityNamespace::GEORSS);
1254 $root->setAttribute("xmlns:activity", ActivityNamespace::ACTIVITY);
1255 $root->setAttribute("xmlns:media", ActivityNamespace::MEDIA);
1256 $root->setAttribute("xmlns:poco", ActivityNamespace::POCO);
1257 $root->setAttribute("xmlns:ostatus", ActivityNamespace::OSTATUS);
1258 $root->setAttribute("xmlns:statusnet", ActivityNamespace::STATUSNET);
1259 $root->setAttribute("xmlns:mastodon", ActivityNamespace::MASTODON);
1262 $selfUri = '/feed/' . $owner["nick"] . '/';
1265 $title = DI::l10n()->t('%s\'s timeline', $owner['name']);
1266 $selfUri .= $filter;
1269 $title = DI::l10n()->t('%s\'s posts', $owner['name']);
1272 $title = DI::l10n()->t('%s\'s comments', $owner['name']);
1273 $selfUri .= $filter;
1277 $selfUri = "/dfrn_poll/" . $owner["nick"];
1279 $attributes = ["uri" => "https://friendi.ca", "version" => FRIENDICA_VERSION . "-" . DB_UPDATE_VERSION];
1280 XML::addElement($doc, $root, "generator", FRIENDICA_PLATFORM, $attributes);
1281 XML::addElement($doc, $root, "id", DI::baseUrl() . "/profile/" . $owner["nick"]);
1282 XML::addElement($doc, $root, "title", $title);
1283 XML::addElement($doc, $root, "subtitle", sprintf("Updates from %s on %s", $owner["name"], DI::config()->get('config', 'sitename')));
1284 XML::addElement($doc, $root, "logo", $owner["photo"]);
1285 XML::addElement($doc, $root, "updated", DateTimeFormat::utcNow(DateTimeFormat::ATOM));
1287 $author = self::addAuthor($doc, $owner, true);
1288 $root->appendChild($author);
1290 $attributes = ["href" => $owner["url"], "rel" => "alternate", "type" => "text/html"];
1291 XML::addElement($doc, $root, "link", "", $attributes);
1293 /// @TODO We have to find out what this is
1294 /// $attributes = array("href" => DI::baseUrl()."/sup",
1295 /// "rel" => "http://api.friendfeed.com/2008/03#sup",
1296 /// "type" => "application/json");
1297 /// XML::addElement($doc, $root, "link", "", $attributes);
1299 self::hublinks($doc, $root, $owner["nick"]);
1301 $attributes = ["href" => DI::baseUrl() . "/salmon/" . $owner["nick"], "rel" => "salmon"];
1302 XML::addElement($doc, $root, "link", "", $attributes);
1304 $attributes = ["href" => DI::baseUrl() . "/salmon/" . $owner["nick"], "rel" => "http://salmon-protocol.org/ns/salmon-replies"];
1305 XML::addElement($doc, $root, "link", "", $attributes);
1307 $attributes = ["href" => DI::baseUrl() . "/salmon/" . $owner["nick"], "rel" => "http://salmon-protocol.org/ns/salmon-mention"];
1308 XML::addElement($doc, $root, "link", "", $attributes);
1310 $attributes = ["href" => DI::baseUrl() . $selfUri, "rel" => "self", "type" => "application/atom+xml"];
1311 XML::addElement($doc, $root, "link", "", $attributes);
1313 if ($owner['contact-type'] == Contact::TYPE_COMMUNITY) {
1314 $condition = ['uid' => $owner['uid'], 'self' => false, 'pending' => false,
1315 'archive' => false, 'hidden' => false, 'blocked' => false];
1316 $members = DBA::count('contact', $condition);
1317 XML::addElement($doc, $root, "statusnet:group_info", "", ["member_count" => $members]);
1324 * Add the link to the push hubs to the XML document
1326 * @param DOMDocument $doc XML document
1327 * @param object $root XML root element where the hub links are added
1328 * @param object $nick nick
1330 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1332 public static function hublinks(DOMDocument $doc, $root, $nick)
1334 $h = DI::baseUrl() . '/pubsubhubbub/'.$nick;
1335 XML::addElement($doc, $root, "link", "", ["href" => $h, "rel" => "hub"]);
1339 * Adds attachment data to the XML document
1341 * @param DOMDocument $doc XML document
1342 * @param object $root XML root element where the hub links are added
1343 * @param array $item Data of the item that is to be posted
1345 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1347 public static function getAttachment(DOMDocument $doc, $root, $item)
1349 $siteinfo = BBCode::getAttachedData($item["body"]);
1351 switch ($siteinfo["type"]) {
1353 if (!empty($siteinfo["image"])) {
1354 $imgdata = Images::getInfoFromURLCached($siteinfo["image"]);
1356 $attributes = ["rel" => "enclosure",
1357 "href" => $siteinfo["image"],
1358 "type" => $imgdata["mime"],
1359 "length" => intval($imgdata["size"])];
1360 XML::addElement($doc, $root, "link", "", $attributes);
1365 $attributes = ["rel" => "enclosure",
1366 "href" => $siteinfo["url"],
1367 "type" => "text/html; charset=UTF-8",
1369 "title" => ($siteinfo["title"] ?? '') ?: $siteinfo["url"],
1371 XML::addElement($doc, $root, "link", "", $attributes);
1377 if (!DI::config()->get('system', 'ostatus_not_attach_preview') && ($siteinfo["type"] != "photo") && isset($siteinfo["image"])) {
1378 $imgdata = Images::getInfoFromURLCached($siteinfo["image"]);
1380 $attributes = ["rel" => "enclosure",
1381 "href" => $siteinfo["image"],
1382 "type" => $imgdata["mime"],
1383 "length" => intval($imgdata["size"])];
1385 XML::addElement($doc, $root, "link", "", $attributes);
1389 foreach (Post\Media::getByURIId($item['uri-id'], [Post\Media::DOCUMENT, Post\Media::TORRENT, Post\Media::UNKNOWN]) as $attachment) {
1390 $attributes = ['rel' => 'enclosure',
1391 'href' => $attachment['url'],
1392 'type' => $attachment['mimetype']];
1394 if (!empty($attachment['size'])) {
1395 $attributes['length'] = intval($attachment['size']);
1397 if (!empty($attachment['description'])) {
1398 $attributes['title'] = $attachment['description'];
1401 XML::addElement($doc, $root, 'link', '', $attributes);
1406 * Adds the author element to the XML document
1408 * @param DOMDocument $doc XML document
1409 * @param array $owner Contact data of the poster
1410 * @param bool $show_profile Whether to show profile
1412 * @return \DOMElement author element
1413 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1415 private static function addAuthor(DOMDocument $doc, array $owner, $show_profile = true)
1417 $profile = DBA::selectFirst('profile', ['homepage', 'publish'], ['uid' => $owner['uid']]);
1418 $author = $doc->createElement("author");
1419 XML::addElement($doc, $author, "id", $owner["url"]);
1420 if ($owner['contact-type'] == Contact::TYPE_COMMUNITY) {
1421 XML::addElement($doc, $author, "activity:object-type", Activity\ObjectType::GROUP);
1423 XML::addElement($doc, $author, "activity:object-type", Activity\ObjectType::PERSON);
1426 XML::addElement($doc, $author, "uri", $owner["url"]);
1427 XML::addElement($doc, $author, "name", $owner["nick"]);
1428 XML::addElement($doc, $author, "email", $owner["addr"]);
1429 if ($show_profile) {
1430 XML::addElement($doc, $author, "summary", BBCode::convert($owner["about"], false, BBCode::OSTATUS));
1433 $attributes = ["rel" => "alternate", "type" => "text/html", "href" => $owner["url"]];
1434 XML::addElement($doc, $author, "link", "", $attributes);
1438 "type" => "image/jpeg", // To-Do?
1439 "media:width" => 300,
1440 "media:height" => 300,
1441 "href" => $owner["photo"]];
1442 XML::addElement($doc, $author, "link", "", $attributes);
1444 if (isset($owner["thumb"])) {
1447 "type" => "image/jpeg", // To-Do?
1448 "media:width" => 80,
1449 "media:height" => 80,
1450 "href" => $owner["thumb"]];
1451 XML::addElement($doc, $author, "link", "", $attributes);
1454 XML::addElement($doc, $author, "poco:preferredUsername", $owner["nick"]);
1455 XML::addElement($doc, $author, "poco:displayName", $owner["name"]);
1456 if ($show_profile) {
1457 XML::addElement($doc, $author, "poco:note", BBCode::convert($owner["about"], false, BBCode::OSTATUS));
1459 if (trim($owner["location"]) != "") {
1460 $element = $doc->createElement("poco:address");
1461 XML::addElement($doc, $element, "poco:formatted", $owner["location"]);
1462 $author->appendChild($element);
1466 if (DBA::isResult($profile) && !$show_profile) {
1467 if (trim($profile["homepage"]) != "") {
1468 $urls = $doc->createElement("poco:urls");
1469 XML::addElement($doc, $urls, "poco:type", "homepage");
1470 XML::addElement($doc, $urls, "poco:value", $profile["homepage"]);
1471 XML::addElement($doc, $urls, "poco:primary", "true");
1472 $author->appendChild($urls);
1475 XML::addElement($doc, $author, "followers", "", ["url" => DI::baseUrl() . "/profile/" . $owner["nick"] . "/contacts/followers"]);
1476 XML::addElement($doc, $author, "statusnet:profile_info", "", ["local_id" => $owner["uid"]]);
1478 if ($profile["publish"]) {
1479 XML::addElement($doc, $author, "mastodon:scope", "public");
1487 * @TODO Picture attachments should look like this:
1488 * <a href="https://status.pirati.ca/attachment/572819" title="https://status.pirati.ca/file/heluecht-20151202T222602-rd3u49p.gif"
1489 * class="attachment thumbnail" id="attachment-572819" rel="nofollow external">https://status.pirati.ca/attachment/572819</a>
1493 * Returns the given activity if present - otherwise returns the "post" activity
1495 * @param array $item Data of the item that is to be posted
1497 * @return string activity
1499 public static function constructVerb(array $item)
1501 if (!empty($item['verb'])) {
1502 return $item['verb'];
1505 return Activity::POST;
1509 * Returns the given object type if present - otherwise returns the "note" object type
1511 * @param array $item Data of the item that is to be posted
1513 * @return string Object type
1515 private static function constructObjecttype(array $item)
1517 if (!empty($item['object-type']) && in_array($item['object-type'], [Activity\ObjectType::NOTE, Activity\ObjectType::COMMENT])) {
1518 return $item['object-type'];
1521 return Activity\ObjectType::NOTE;
1525 * Adds an entry element to the XML document
1527 * @param DOMDocument $doc XML document
1528 * @param array $item Data of the item that is to be posted
1529 * @param array $owner Contact data of the poster
1530 * @param bool $toplevel optional default false
1532 * @return \DOMElement Entry element
1533 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1534 * @throws \ImagickException
1536 private static function entry(DOMDocument $doc, array $item, array $owner, $toplevel = false)
1540 $repeated_guid = self::getResharedGuid($item);
1541 if ($repeated_guid != "") {
1542 $xml = self::reshareEntry($doc, $item, $owner, $repeated_guid, $toplevel);
1549 if ($item["verb"] == Activity::LIKE) {
1550 return self::likeEntry($doc, $item, $owner, $toplevel);
1551 } elseif (in_array($item["verb"], [Activity::FOLLOW, Activity::O_UNFOLLOW])) {
1552 return self::followEntry($doc, $item, $owner, $toplevel);
1554 return self::noteEntry($doc, $item, $owner, $toplevel);
1559 * Adds a source entry to the XML document
1561 * @param DOMDocument $doc XML document
1562 * @param array $contact Array of the contact that is added
1564 * @return \DOMElement Source element
1565 * @throws \Exception
1567 private static function sourceEntry(DOMDocument $doc, array $contact)
1569 $source = $doc->createElement("source");
1570 XML::addElement($doc, $source, "id", $contact["poll"]);
1571 XML::addElement($doc, $source, "title", $contact["name"]);
1572 XML::addElement($doc, $source, "link", "", ["rel" => "alternate", "type" => "text/html", "href" => $contact["alias"]]);
1573 XML::addElement($doc, $source, "link", "", ["rel" => "self", "type" => "application/atom+xml", "href" => $contact["poll"]]);
1574 XML::addElement($doc, $source, "icon", $contact["photo"]);
1575 XML::addElement($doc, $source, "updated", DateTimeFormat::utc($contact["success_update"]."+00:00", DateTimeFormat::ATOM));
1581 * Adds an entry element with reshared content
1583 * @param DOMDocument $doc XML document
1584 * @param array $item Data of the item that is to be posted
1585 * @param array $owner Contact data of the poster
1586 * @param string $repeated_guid guid
1587 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1589 * @return bool Entry element
1590 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1591 * @throws \ImagickException
1593 private static function reshareEntry(DOMDocument $doc, array $item, array $owner, $repeated_guid, $toplevel)
1595 if (($item['gravity'] != GRAVITY_PARENT) && (Strings::normaliseLink($item["author-link"]) != Strings::normaliseLink($owner["url"]))) {
1596 Logger::log("OStatus entry is from author ".$owner["url"]." - not from ".$item["author-link"].". Quitting.", Logger::DEBUG);
1599 $entry = self::entryHeader($doc, $owner, $item, $toplevel);
1601 $condition = ['uid' => $owner["uid"], 'guid' => $repeated_guid, 'private' => [Item::PUBLIC, Item::UNLISTED],
1602 'network' => [Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS]];
1603 $repeated_item = Item::selectFirst([], $condition);
1604 if (!DBA::isResult($repeated_item)) {
1608 $contact = Contact::getByURL($repeated_item['author-link']) ?: $owner;
1610 $title = $owner["nick"]." repeated a notice by ".$contact["nick"];
1612 self::entryContent($doc, $entry, $item, $owner, $title, Activity::SHARE, false);
1614 $as_object = $doc->createElement("activity:object");
1616 XML::addElement($doc, $as_object, "activity:object-type", ActivityNamespace::ACTIVITY_SCHEMA . "activity");
1618 self::entryContent($doc, $as_object, $repeated_item, $owner, "", "", false);
1620 $author = self::addAuthor($doc, $contact, false);
1621 $as_object->appendChild($author);
1623 $as_object2 = $doc->createElement("activity:object");
1625 XML::addElement($doc, $as_object2, "activity:object-type", self::constructObjecttype($repeated_item));
1627 $title = sprintf("New comment by %s", $contact["nick"]);
1629 self::entryContent($doc, $as_object2, $repeated_item, $owner, $title);
1631 $as_object->appendChild($as_object2);
1633 self::entryFooter($doc, $as_object, $item, $owner, false);
1635 $source = self::sourceEntry($doc, $contact);
1637 $as_object->appendChild($source);
1639 $entry->appendChild($as_object);
1641 self::entryFooter($doc, $entry, $item, $owner, true);
1647 * Adds an entry element with a "like"
1649 * @param DOMDocument $doc XML document
1650 * @param array $item Data of the item that is to be posted
1651 * @param array $owner Contact data of the poster
1652 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1654 * @return \DOMElement Entry element with "like"
1655 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1656 * @throws \ImagickException
1658 private static function likeEntry(DOMDocument $doc, array $item, array $owner, $toplevel)
1660 if (($item['gravity'] != GRAVITY_PARENT) && (Strings::normaliseLink($item["author-link"]) != Strings::normaliseLink($owner["url"]))) {
1661 Logger::log("OStatus entry is from author ".$owner["url"]." - not from ".$item["author-link"].". Quitting.", Logger::DEBUG);
1664 $entry = self::entryHeader($doc, $owner, $item, $toplevel);
1666 $verb = ActivityNamespace::ACTIVITY_SCHEMA . "favorite";
1667 self::entryContent($doc, $entry, $item, $owner, "Favorite", $verb, false);
1669 $parent = Item::selectFirst([], ['uri' => $item["thr-parent"], 'uid' => $item["uid"]]);
1670 if (DBA::isResult($parent)) {
1671 $as_object = $doc->createElement("activity:object");
1673 XML::addElement($doc, $as_object, "activity:object-type", self::constructObjecttype($parent));
1675 self::entryContent($doc, $as_object, $parent, $owner, "New entry");
1677 $entry->appendChild($as_object);
1680 self::entryFooter($doc, $entry, $item, $owner);
1686 * Adds the person object element to the XML document
1688 * @param DOMDocument $doc XML document
1689 * @param array $owner Contact data of the poster
1690 * @param array $contact Contact data of the target
1692 * @return object author element
1694 private static function addPersonObject(DOMDocument $doc, array $owner, array $contact)
1696 $object = $doc->createElement("activity:object");
1697 XML::addElement($doc, $object, "activity:object-type", Activity\ObjectType::PERSON);
1699 if ($contact['network'] == Protocol::PHANTOM) {
1700 XML::addElement($doc, $object, "id", $contact['url']);
1704 XML::addElement($doc, $object, "id", $contact["alias"]);
1705 XML::addElement($doc, $object, "title", $contact["nick"]);
1707 $attributes = ["rel" => "alternate", "type" => "text/html", "href" => $contact["url"]];
1708 XML::addElement($doc, $object, "link", "", $attributes);
1712 "type" => "image/jpeg", // To-Do?
1713 "media:width" => 300,
1714 "media:height" => 300,
1715 "href" => $contact["photo"]];
1716 XML::addElement($doc, $object, "link", "", $attributes);
1718 XML::addElement($doc, $object, "poco:preferredUsername", $contact["nick"]);
1719 XML::addElement($doc, $object, "poco:displayName", $contact["name"]);
1721 if (trim($contact["location"]) != "") {
1722 $element = $doc->createElement("poco:address");
1723 XML::addElement($doc, $element, "poco:formatted", $contact["location"]);
1724 $object->appendChild($element);
1731 * Adds a follow/unfollow entry element
1733 * @param DOMDocument $doc XML document
1734 * @param array $item Data of the follow/unfollow message
1735 * @param array $owner Contact data of the poster
1736 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1738 * @return \DOMElement Entry element
1739 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1740 * @throws \ImagickException
1742 private static function followEntry(DOMDocument $doc, array $item, array $owner, $toplevel)
1744 $item["id"] = $item['parent'] = 0;
1745 $item["created"] = $item["edited"] = date("c");
1746 $item["private"] = Item::PRIVATE;
1748 $contact = Contact::getByURL($item['follow']);
1749 $item['follow'] = $contact['url'];
1751 if ($contact['alias']) {
1752 $item['follow'] = $contact['alias'];
1754 $contact['alias'] = $contact['url'];
1757 $condition = ['uid' => $owner['uid'], 'nurl' => Strings::normaliseLink($contact["url"])];
1758 $user_contact = DBA::selectFirst('contact', ['id'], $condition);
1760 if (DBA::isResult($user_contact)) {
1761 $connect_id = $user_contact['id'];
1766 if ($item['verb'] == Activity::FOLLOW) {
1767 $message = DI::l10n()->t('%s is now following %s.');
1768 $title = DI::l10n()->t('following');
1769 $action = "subscription";
1771 $message = DI::l10n()->t('%s stopped following %s.');
1772 $title = DI::l10n()->t('stopped following');
1773 $action = "unfollow";
1776 $item["uri"] = $item['parent-uri'] = $item['thr-parent']
1777 = 'tag:' . DI::baseUrl()->getHostname().
1778 ','.date('Y-m-d').':'.$action.':'.$owner['uid'].
1779 ':person:'.$connect_id.':'.$item['created'];
1781 $item["body"] = sprintf($message, $owner["nick"], $contact["nick"]);
1783 $entry = self::entryHeader($doc, $owner, $item, $toplevel);
1785 self::entryContent($doc, $entry, $item, $owner, $title);
1787 $object = self::addPersonObject($doc, $owner, $contact);
1788 $entry->appendChild($object);
1790 self::entryFooter($doc, $entry, $item, $owner);
1796 * Adds a regular entry element
1798 * @param DOMDocument $doc XML document
1799 * @param array $item Data of the item that is to be posted
1800 * @param array $owner Contact data of the poster
1801 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1803 * @return \DOMElement Entry element
1804 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1805 * @throws \ImagickException
1807 private static function noteEntry(DOMDocument $doc, array $item, array $owner, $toplevel)
1809 if (($item['gravity'] != GRAVITY_PARENT) && (Strings::normaliseLink($item["author-link"]) != Strings::normaliseLink($owner["url"]))) {
1810 Logger::log("OStatus entry is from author ".$owner["url"]." - not from ".$item["author-link"].". Quitting.", Logger::DEBUG);
1814 if (!empty($item['title'])) {
1815 $title = BBCode::convert($item['title'], false, BBCode::OSTATUS);
1817 $title = sprintf("New note by %s", $owner["nick"]);
1820 $title = sprintf("New comment by %s", $owner["nick"]);
1823 $entry = self::entryHeader($doc, $owner, $item, $toplevel);
1825 XML::addElement($doc, $entry, "activity:object-type", Activity\ObjectType::NOTE);
1827 self::entryContent($doc, $entry, $item, $owner, $title, '', true);
1829 self::entryFooter($doc, $entry, $item, $owner, true);
1835 * Adds a header element to the XML document
1837 * @param DOMDocument $doc XML document
1838 * @param array $owner Contact data of the poster
1839 * @param array $item
1840 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1842 * @return \DOMElement The entry element where the elements are added
1843 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1844 * @throws \ImagickException
1846 public static function entryHeader(DOMDocument $doc, array $owner, array $item, $toplevel)
1849 $entry = $doc->createElement("entry");
1851 if ($owner['contact-type'] == Contact::TYPE_COMMUNITY) {
1852 $contact = Contact::getByURL($item['author-link']) ?: $owner;
1853 $author = self::addAuthor($doc, $contact, false);
1854 $entry->appendChild($author);
1857 $entry = $doc->createElementNS(ActivityNamespace::ATOM1, "entry");
1859 $entry->setAttribute("xmlns:thr", ActivityNamespace::THREAD);
1860 $entry->setAttribute("xmlns:georss", ActivityNamespace::GEORSS);
1861 $entry->setAttribute("xmlns:activity", ActivityNamespace::ACTIVITY);
1862 $entry->setAttribute("xmlns:media", ActivityNamespace::MEDIA);
1863 $entry->setAttribute("xmlns:poco", ActivityNamespace::POCO);
1864 $entry->setAttribute("xmlns:ostatus", ActivityNamespace::OSTATUS);
1865 $entry->setAttribute("xmlns:statusnet", ActivityNamespace::STATUSNET);
1866 $entry->setAttribute("xmlns:mastodon", ActivityNamespace::MASTODON);
1868 $author = self::addAuthor($doc, $owner);
1869 $entry->appendChild($author);
1876 * Adds elements to the XML document
1878 * @param DOMDocument $doc XML document
1879 * @param \DOMElement $entry Entry element where the content is added
1880 * @param array $item Data of the item that is to be posted
1881 * @param array $owner Contact data of the poster
1882 * @param string $title Title for the post
1883 * @param string $verb The activity verb
1884 * @param bool $complete Add the "status_net" element?
1886 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1888 private static function entryContent(DOMDocument $doc, \DOMElement $entry, array $item, array $owner, $title, $verb = "", $complete = true)
1891 $verb = self::constructVerb($item);
1894 XML::addElement($doc, $entry, "id", $item["uri"]);
1895 XML::addElement($doc, $entry, "title", html_entity_decode($title, ENT_QUOTES, 'UTF-8'));
1897 $body = self::formatPicturePost($item['body']);
1899 if (!empty($item['title'])) {
1900 $body = "[b]".$item['title']."[/b]\n\n".$body;
1903 $body = BBCode::convert($body, false, BBCode::OSTATUS);
1905 XML::addElement($doc, $entry, "content", $body, ["type" => "html"]);
1907 XML::addElement($doc, $entry, "link", "", ["rel" => "alternate", "type" => "text/html",
1908 "href" => DI::baseUrl()."/display/".$item["guid"]]
1911 if ($complete && ($item["id"] > 0)) {
1912 XML::addElement($doc, $entry, "status_net", "", ["notice_id" => $item["id"]]);
1915 XML::addElement($doc, $entry, "activity:verb", $verb);
1917 XML::addElement($doc, $entry, "published", DateTimeFormat::utc($item["created"]."+00:00", DateTimeFormat::ATOM));
1918 XML::addElement($doc, $entry, "updated", DateTimeFormat::utc($item["edited"]."+00:00", DateTimeFormat::ATOM));
1922 * Adds the elements at the foot of an entry to the XML document
1924 * @param DOMDocument $doc XML document
1925 * @param object $entry The entry element where the elements are added
1926 * @param array $item Data of the item that is to be posted
1927 * @param array $owner Contact data of the poster
1928 * @param bool $complete default true
1930 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1932 private static function entryFooter(DOMDocument $doc, $entry, array $item, array $owner, $complete = true)
1936 if ($item['gravity'] != GRAVITY_PARENT) {
1937 $parent = Item::selectFirst(['guid', 'author-link', 'owner-link'], ['id' => $item['parent']]);
1939 $thrparent = Item::selectFirst(['guid', 'author-link', 'owner-link', 'plink'], ['uid' => $owner["uid"], 'uri' => $item['thr-parent']]);
1941 if (DBA::isResult($thrparent)) {
1942 $mentioned[$thrparent["author-link"]] = $thrparent["author-link"];
1943 $mentioned[$thrparent["owner-link"]] = $thrparent["owner-link"];
1944 $parent_plink = $thrparent["plink"];
1946 $mentioned[$parent["author-link"]] = $parent["author-link"];
1947 $mentioned[$parent["owner-link"]] = $parent["owner-link"];
1948 $parent_plink = DI::baseUrl()."/display/".$parent["guid"];
1952 "ref" => $item['thr-parent'],
1953 "href" => $parent_plink];
1954 XML::addElement($doc, $entry, "thr:in-reply-to", "", $attributes);
1958 "href" => $parent_plink];
1959 XML::addElement($doc, $entry, "link", "", $attributes);
1962 if (intval($item['parent']) > 0) {
1963 $conversation_href = $conversation_uri = str_replace('/objects/', '/context/', $item['thr-parent']);
1965 if (isset($parent_item)) {
1966 $conversation = DBA::selectFirst('conversation', ['conversation-uri', 'conversation-href'], ['item-uri' => $parent_item]);
1967 if (DBA::isResult($conversation)) {
1968 if ($conversation['conversation-uri'] != '') {
1969 $conversation_uri = $conversation['conversation-uri'];
1971 if ($conversation['conversation-href'] != '') {
1972 $conversation_href = $conversation['conversation-href'];
1977 XML::addElement($doc, $entry, "link", "", ["rel" => "ostatus:conversation", "href" => $conversation_href]);
1980 "href" => $conversation_href,
1981 "local_id" => $item['parent'],
1982 "ref" => $conversation_uri];
1984 XML::addElement($doc, $entry, "ostatus:conversation", $conversation_uri, $attributes);
1987 // uri-id isn't present for follow entry pseudo-items
1988 $tags = Tag::getByURIId($item['uri-id'] ?? 0);
1989 foreach ($tags as $tag) {
1990 $mentioned[$tag['url']] = $tag['url'];
1993 // Make sure that mentions are accepted (GNU Social has problems with mixing HTTP and HTTPS)
1995 foreach ($mentioned as $mention) {
1996 $newmentions[str_replace("http://", "https://", $mention)] = str_replace("http://", "https://", $mention);
1997 $newmentions[str_replace("https://", "http://", $mention)] = str_replace("https://", "http://", $mention);
1999 $mentioned = $newmentions;
2001 foreach ($mentioned as $mention) {
2002 $contact = Contact::getByURL($mention, false, ['contact-type']);
2003 if (!empty($contact) && ($contact['contact-type'] == Contact::TYPE_COMMUNITY)) {
2004 XML::addElement($doc, $entry, "link", "",
2006 "rel" => "mentioned",
2007 "ostatus:object-type" => Activity\ObjectType::GROUP,
2011 XML::addElement($doc, $entry, "link", "",
2013 "rel" => "mentioned",
2014 "ostatus:object-type" => Activity\ObjectType::PERSON,
2020 if ($owner['contact-type'] == Contact::TYPE_COMMUNITY) {
2021 XML::addElement($doc, $entry, "link", "", [
2022 "rel" => "mentioned",
2023 "ostatus:object-type" => "http://activitystrea.ms/schema/1.0/group",
2024 "href" => $owner['url']
2028 if ($item['private'] != Item::PRIVATE) {
2029 XML::addElement($doc, $entry, "link", "", ["rel" => "ostatus:attention",
2030 "href" => "http://activityschema.org/collection/public"]);
2031 XML::addElement($doc, $entry, "link", "", ["rel" => "mentioned",
2032 "ostatus:object-type" => "http://activitystrea.ms/schema/1.0/collection",
2033 "href" => "http://activityschema.org/collection/public"]);
2034 XML::addElement($doc, $entry, "mastodon:scope", "public");
2037 foreach ($tags as $tag) {
2038 if ($tag['type'] == Tag::HASHTAG) {
2039 XML::addElement($doc, $entry, "category", "", ["term" => $tag['name']]);
2043 self::getAttachment($doc, $entry, $item);
2045 if ($complete && ($item["id"] > 0)) {
2046 $app = $item["app"];
2051 $attributes = ["local_id" => $item["id"], "source" => $app];
2053 if (isset($parent["id"])) {
2054 $attributes["repeat_of"] = $parent["id"];
2057 if ($item["coord"] != "") {
2058 XML::addElement($doc, $entry, "georss:point", $item["coord"]);
2061 XML::addElement($doc, $entry, "statusnet:notice_info", "", $attributes);
2066 * Creates the XML feed for a given nickname
2068 * Supported filters:
2069 * - activity (default): all the public posts
2070 * - posts: all the public top-level posts
2071 * - comments: all the public replies
2073 * Updates the provided last_update parameter if the result comes from the
2074 * cache or it is empty
2076 * @param string $owner_nick Nickname of the feed owner
2077 * @param string $last_update Date of the last update
2078 * @param integer $max_items Number of maximum items to fetch
2079 * @param string $filter Feed items filter (activity, posts or comments)
2080 * @param boolean $nocache Wether to bypass caching
2082 * @return string XML feed
2083 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2084 * @throws \ImagickException
2086 public static function feed($owner_nick, &$last_update, $max_items = 300, $filter = 'activity', $nocache = false)
2088 $stamp = microtime(true);
2090 $owner = User::getOwnerDataByNick($owner_nick);
2095 $cachekey = "ostatus:feed:" . $owner_nick . ":" . $filter . ":" . $last_update;
2097 $previous_created = $last_update;
2099 // Don't cache when the last item was posted less then 15 minutes ago (Cache duration)
2100 if ((time() - strtotime($owner['last-item'])) < 15*60) {
2101 $result = DI::cache()->get($cachekey);
2102 if (!$nocache && !is_null($result)) {
2103 Logger::log('Feed duration: ' . number_format(microtime(true) - $stamp, 3) . ' - ' . $owner_nick . ' - ' . $filter . ' - ' . $previous_created . ' (cached)', Logger::DEBUG);
2104 $last_update = $result['last_update'];
2105 return $result['feed'];
2109 if (!strlen($last_update)) {
2110 $last_update = 'now -30 days';
2113 $check_date = DateTimeFormat::utc($last_update);
2114 $authorid = Contact::getIdForURL($owner["url"]);
2116 $condition = ["`uid` = ? AND `received` > ? AND NOT `deleted`
2117 AND `private` != ? AND `visible` AND `wall` AND `parent-network` IN (?, ?)",
2118 $owner["uid"], $check_date, Item::PRIVATE, Protocol::OSTATUS, Protocol::DFRN];
2120 if ($filter === 'comments') {
2121 $condition[0] .= " AND `object-type` = ? ";
2122 $condition[] = Activity\ObjectType::COMMENT;
2125 if ($owner['contact-type'] != Contact::TYPE_COMMUNITY) {
2126 $condition[0] .= " AND `contact-id` = ? AND `author-id` = ?";
2127 $condition[] = $owner["id"];
2128 $condition[] = $authorid;
2131 $params = ['order' => ['received' => true], 'limit' => $max_items];
2133 if ($filter === 'posts') {
2134 $ret = Item::selectThread([], $condition, $params);
2136 $ret = Item::select([], $condition, $params);
2139 $items = Item::inArray($ret);
2141 $doc = new DOMDocument('1.0', 'utf-8');
2142 $doc->formatOutput = true;
2144 $root = self::addHeader($doc, $owner, $filter);
2146 foreach ($items as $item) {
2147 if (DI::config()->get('system', 'ostatus_debug')) {
2148 $item['body'] .= '🍼';
2151 if (in_array($item["verb"], [Activity::FOLLOW, Activity::O_UNFOLLOW, Activity::LIKE])) {
2155 $entry = self::entry($doc, $item, $owner, false);
2156 $root->appendChild($entry);
2158 if ($last_update < $item['created']) {
2159 $last_update = $item['created'];
2163 $feeddata = trim($doc->saveXML());
2165 $msg = ['feed' => $feeddata, 'last_update' => $last_update];
2166 DI::cache()->set($cachekey, $msg, Duration::QUARTER_HOUR);
2168 Logger::log('Feed duration: ' . number_format(microtime(true) - $stamp, 3) . ' - ' . $owner_nick . ' - ' . $filter . ' - ' . $previous_created, Logger::DEBUG);
2174 * Creates the XML for a salmon message
2176 * @param array $item Data of the item that is to be posted
2177 * @param array $owner Contact data of the poster
2179 * @return string XML for the salmon
2180 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2181 * @throws \ImagickException
2183 public static function salmon(array $item, array $owner)
2185 $doc = new DOMDocument('1.0', 'utf-8');
2186 $doc->formatOutput = true;
2188 if (DI::config()->get('system', 'ostatus_debug')) {
2189 $item['body'] .= '🐟';
2192 $entry = self::entry($doc, $item, $owner, true);
2194 $doc->appendChild($entry);
2196 return trim($doc->saveXML());
2200 * Checks if the given contact url does support OStatus
2202 * @param string $url profile url
2204 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2205 * @throws \ImagickException
2207 public static function isSupportedByContactUrl($url)
2209 $probe = Probe::uri($url, Protocol::OSTATUS);
2210 return $probe['network'] == Protocol::OSTATUS;