3 * @file src/Protocol/OStatus.php
5 namespace Friendica\Protocol;
9 use Friendica\Content\Text\BBCode;
10 use Friendica\Content\Text\HTML;
11 use Friendica\Core\Cache\Cache;
12 use Friendica\Core\Config;
13 use Friendica\Core\L10n;
14 use Friendica\Core\Lock;
15 use Friendica\Core\Logger;
16 use Friendica\Core\PConfig;
17 use Friendica\Core\Protocol;
18 use Friendica\Database\DBA;
20 use Friendica\Model\APContact;
21 use Friendica\Model\Contact;
22 use Friendica\Model\Conversation;
23 use Friendica\Model\GContact;
24 use Friendica\Model\Item;
25 use Friendica\Model\User;
26 use Friendica\Network\Probe;
27 use Friendica\Util\DateTimeFormat;
28 use Friendica\Util\Images;
29 use Friendica\Util\Network;
30 use Friendica\Util\Proxy as ProxyUtils;
31 use Friendica\Util\Strings;
32 use Friendica\Util\XML;
34 require_once 'mod/share.php';
35 require_once 'include/api.php';
38 * @brief This class contain functions for the OStatus protocol
42 private static $itemlist;
43 private static $conv_list = [];
46 * @brief Fetches author data
48 * @param DOMXPath $xpath The xpath object
49 * @param object $context The xml context of the author details
50 * @param array $importer user record of the importing user
51 * @param array $contact Called by reference, will contain the fetched contact
52 * @param bool $onlyfetch Only fetch the header without updating the contact entries
54 * @return array Array of author related entries for the item
55 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
56 * @throws \ImagickException
58 private static function fetchAuthor(DOMXPath $xpath, $context, array $importer, array &$contact = null, $onlyfetch)
61 $author["author-link"] = XML::getFirstNodeValue($xpath, 'atom:author/atom:uri/text()', $context);
62 $author["author-name"] = XML::getFirstNodeValue($xpath, 'atom:author/atom:name/text()', $context);
63 $addr = XML::getFirstNodeValue($xpath, 'atom:author/atom:email/text()', $context);
65 $aliaslink = $author["author-link"];
67 $alternate_item = $xpath->query("atom:author/atom:link[@rel='alternate']", $context)->item(0);
68 if (is_object($alternate_item)) {
69 foreach ($alternate_item->attributes as $attributes) {
70 if (($attributes->name == "href") && ($attributes->textContent != "")) {
71 $author["author-link"] = $attributes->textContent;
75 $author["author-id"] = Contact::getIdForURL($author["author-link"]);
77 $author['contact-id'] = ($contact['id'] ?? 0) ?: $author['author-id'];
82 This here would be better, but we would get problems with contacts from the statusnet addon
83 This is kept here as a reminder for the future
85 $cid = Contact::getIdForURL($author["author-link"], $importer["uid"]);
87 $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
90 if ($aliaslink != '') {
91 $condition = ["`uid` = ? AND `alias` = ? AND `network` != ? AND `rel` IN (?, ?)",
92 $importer["uid"], $aliaslink, Protocol::STATUSNET,
93 Contact::SHARING, Contact::FRIEND];
94 $contact = DBA::selectFirst('contact', [], $condition);
97 if (!DBA::isResult($contact) && $author["author-link"] != '') {
98 if ($aliaslink == "") {
99 $aliaslink = $author["author-link"];
102 $condition = ["`uid` = ? AND `nurl` IN (?, ?) AND `network` != ? AND `rel` IN (?, ?)",
103 $importer["uid"], Strings::normaliseLink($author["author-link"]), Strings::normaliseLink($aliaslink),
104 Protocol::STATUSNET, Contact::SHARING, Contact::FRIEND];
105 $contact = DBA::selectFirst('contact', [], $condition);
108 if (!DBA::isResult($contact) && ($addr != '')) {
109 $condition = ["`uid` = ? AND `addr` = ? AND `network` != ? AND `rel` IN (?, ?)",
110 $importer["uid"], $addr, Protocol::STATUSNET,
111 Contact::SHARING, Contact::FRIEND];
112 $contact = DBA::selectFirst('contact', [], $condition);
115 if (DBA::isResult($contact)) {
116 if ($contact['blocked']) {
118 } elseif (!empty(APContact::getByURL($contact['url'], false))) {
119 ActivityPub\Receiver::switchContact($contact['id'], $importer['uid'], $contact['url']);
121 $author["contact-id"] = $contact["id"];
125 $avatars = $xpath->query("atom:author/atom:link[@rel='avatar']", $context);
126 foreach ($avatars as $avatar) {
129 foreach ($avatar->attributes as $attributes) {
130 if ($attributes->name == "href") {
131 $href = $attributes->textContent;
133 if ($attributes->name == "width") {
134 $width = $attributes->textContent;
138 $avatarlist[$width] = $href;
141 if (count($avatarlist) > 0) {
143 $author["author-avatar"] = Probe::fixAvatar(current($avatarlist), $author["author-link"]);
146 $displayname = XML::getFirstNodeValue($xpath, 'atom:author/poco:displayName/text()', $context);
147 if ($displayname != "") {
148 $author["author-name"] = $displayname;
151 $author["owner-id"] = $author["author-id"];
153 // Only update the contacts if it is an OStatus contact
154 if (DBA::isResult($contact) && ($contact['id'] > 0) && !$onlyfetch && ($contact["network"] == Protocol::OSTATUS)) {
156 // Update contact data
158 unset($current['name-date']);
160 // This query doesn't seem to work
161 // $value = $xpath->query("atom:link[@rel='salmon']", $context)->item(0)->nodeValue;
163 // $contact["notify"] = $value;
165 // This query doesn't seem to work as well - I hate these queries
166 // $value = $xpath->query("atom:link[@rel='self' and @type='application/atom+xml']", $context)->item(0)->nodeValue;
168 // $contact["poll"] = $value;
170 $contact['url'] = $author["author-link"];
171 $contact['nurl'] = Strings::normaliseLink($contact['url']);
173 $value = XML::getFirstNodeValue($xpath, 'atom:author/atom:uri/text()', $context);
175 $contact["alias"] = $value;
178 $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:displayName/text()', $context);
180 $contact["name"] = $value;
183 $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:preferredUsername/text()', $context);
185 $contact["nick"] = $value;
188 $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:note/text()', $context);
190 $contact["about"] = HTML::toBBCode($value);
193 $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:address/poco:formatted/text()', $context);
195 $contact["location"] = $value;
198 $contact['name-date'] = DateTimeFormat::utcNow();
200 DBA::update('contact', $contact, ['id' => $contact["id"]], $current);
202 if (!empty($author["author-avatar"]) && ($author["author-avatar"] != $current['avatar'])) {
203 Logger::log("Update profile picture for contact ".$contact["id"], Logger::DEBUG);
204 Contact::updateAvatar($author["author-avatar"], $importer["uid"], $contact["id"]);
207 // Ensure that we are having this contact (with uid=0)
208 $cid = Contact::getIdForURL($aliaslink, 0, true);
211 $fields = ['url', 'nurl', 'name', 'nick', 'alias', 'about', 'location'];
212 $old_contact = DBA::selectFirst('contact', $fields, ['id' => $cid]);
214 // Update it with the current values
215 $fields = ['url' => $author["author-link"], 'name' => $contact["name"],
216 'nurl' => Strings::normaliseLink($author["author-link"]),
217 'nick' => $contact["nick"], 'alias' => $contact["alias"],
218 'about' => $contact["about"], 'location' => $contact["location"],
219 'success_update' => DateTimeFormat::utcNow(), 'last-update' => DateTimeFormat::utcNow()];
221 DBA::update('contact', $fields, ['id' => $cid], $old_contact);
224 if (!empty($author["author-avatar"])) {
225 Contact::updateAvatar($author["author-avatar"], 0, $cid);
229 $contact["generation"] = 2;
230 $contact["hide"] = false; // OStatus contacts are never hidden
231 if (!empty($author["author-avatar"])) {
232 $contact["photo"] = $author["author-avatar"];
234 $gcid = GContact::update($contact);
236 GContact::link($gcid, $contact["uid"], $contact["id"]);
237 } elseif ($contact["network"] != Protocol::DFRN) {
245 * @brief Fetches author data from a given XML string
247 * @param string $xml The XML
248 * @param array $importer user record of the importing user
250 * @return array Array of author related entries for the item
251 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
252 * @throws \ImagickException
254 public static function salmonAuthor($xml, array $importer)
260 $doc = new DOMDocument();
261 @$doc->loadXML($xml);
263 $xpath = new DOMXPath($doc);
264 $xpath->registerNamespace('atom', ActivityNamespace::ATOM1);
265 $xpath->registerNamespace('thr', ActivityNamespace::THREAD);
266 $xpath->registerNamespace('georss', ActivityNamespace::GEORSS);
267 $xpath->registerNamespace('activity', ActivityNamespace::ACTIVITY);
268 $xpath->registerNamespace('media', ActivityNamespace::MEDIA);
269 $xpath->registerNamespace('poco', ActivityNamespace::POCO);
270 $xpath->registerNamespace('ostatus', ActivityNamespace::OSTATUS);
271 $xpath->registerNamespace('statusnet', ActivityNamespace::STATUSNET);
273 $contact = ["id" => 0];
275 // Fetch the first author
276 $authordata = $xpath->query('//author')->item(0);
277 $author = self::fetchAuthor($xpath, $authordata, $importer, $contact, true);
282 * @brief Read attributes from element
284 * @param object $element Element object
286 * @return array attributes
288 private static function readAttributes($element)
292 foreach ($element->attributes as $attributes) {
293 $attribute[$attributes->name] = $attributes->textContent;
300 * @brief Imports an XML string containing OStatus elements
302 * @param string $xml The XML
303 * @param array $importer user record of the importing user
304 * @param array $contact contact
305 * @param string $hub Called by reference, returns the fetched hub data
307 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
308 * @throws \ImagickException
310 public static function import($xml, array $importer, array &$contact, &$hub)
312 self::process($xml, $importer, $contact, $hub);
316 * @brief Internal feed processing
318 * @param string $xml The XML
319 * @param array $importer user record of the importing user
320 * @param array $contact contact
321 * @param string $hub Called by reference, returns the fetched hub data
322 * @param boolean $stored Is the post fresh imported or from the database?
323 * @param boolean $initialize Is it the leading post so that data has to be initialized?
325 * @return boolean Could the XML be processed?
326 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
327 * @throws \ImagickException
329 private static function process($xml, array $importer, array &$contact = null, &$hub, $stored = false, $initialize = true)
332 self::$itemlist = [];
333 self::$conv_list = [];
336 Logger::log('Import OStatus message for user ' . $importer['uid'], Logger::DEBUG);
341 $doc = new DOMDocument();
342 @$doc->loadXML($xml);
344 $xpath = new DOMXPath($doc);
345 $xpath->registerNamespace('atom', ActivityNamespace::ATOM1);
346 $xpath->registerNamespace('thr', ActivityNamespace::THREAD);
347 $xpath->registerNamespace('georss', ActivityNamespace::GEORSS);
348 $xpath->registerNamespace('activity', ActivityNamespace::ACTIVITY);
349 $xpath->registerNamespace('media', ActivityNamespace::MEDIA);
350 $xpath->registerNamespace('poco', ActivityNamespace::POCO);
351 $xpath->registerNamespace('ostatus', ActivityNamespace::OSTATUS);
352 $xpath->registerNamespace('statusnet', ActivityNamespace::STATUSNET);
355 $hub_items = $xpath->query("/atom:feed/atom:link[@rel='hub']")->item(0);
356 if (is_object($hub_items)) {
357 $hub_attributes = $hub_items->attributes;
358 if (is_object($hub_attributes)) {
359 foreach ($hub_attributes as $hub_attribute) {
360 if ($hub_attribute->name == "href") {
361 $hub = $hub_attribute->textContent;
362 Logger::log("Found hub ".$hub, Logger::DEBUG);
369 $header["uid"] = $importer["uid"];
370 $header["network"] = Protocol::OSTATUS;
372 $header["origin"] = 0;
373 $header["gravity"] = GRAVITY_COMMENT;
375 if (!is_object($doc->firstChild) || empty($doc->firstChild->tagName)) {
379 $first_child = $doc->firstChild->tagName;
381 if ($first_child == "feed") {
382 $entries = $xpath->query('/atom:feed/atom:entry');
384 $entries = $xpath->query('/atom:entry');
387 if ($entries->length == 1) {
388 // We reformat the XML to make it better readable
389 $doc2 = new DOMDocument();
390 $doc2->loadXML($xml);
391 $doc2->preserveWhiteSpace = false;
392 $doc2->formatOutput = true;
393 $xml2 = $doc2->saveXML();
395 $header["protocol"] = Conversation::PARCEL_SALMON;
396 $header["source"] = $xml2;
397 } elseif (!$initialize) {
401 // Fetch the first author
402 $authordata = $xpath->query('//author')->item(0);
403 $author = self::fetchAuthor($xpath, $authordata, $importer, $contact, $stored);
405 // Reverse the order of the entries
408 foreach ($entries as $entry) {
409 $entrylist[] = $entry;
412 foreach (array_reverse($entrylist) as $entry) {
414 $authorelement = $xpath->query('/atom:entry/atom:author', $entry);
416 if ($authorelement->length == 0) {
417 $authorelement = $xpath->query('atom:author', $entry);
420 if ($authorelement->length > 0) {
421 $author = self::fetchAuthor($xpath, $entry, $importer, $contact, $stored);
424 $item = array_merge($header, $author);
426 $item["uri"] = XML::getFirstNodeValue($xpath, 'atom:id/text()', $entry);
428 $item["verb"] = XML::getFirstNodeValue($xpath, 'activity:verb/text()', $entry);
431 if (in_array($item["verb"], ['qvitter-delete-notice', Activity::DELETE, 'delete'])) {
432 self::deleteNotice($item);
436 if (in_array($item["verb"], [Activity::O_UNFAVOURITE, Activity::UNFAVORITE])) {
437 // Ignore "Unfavorite" message
438 Logger::log("Ignore unfavorite message ".print_r($item, true), Logger::DEBUG);
442 // Deletions come with the same uri, so we check for duplicates after processing deletions
443 if (Item::exists(['uid' => $importer["uid"], 'uri' => $item["uri"]])) {
444 Logger::log('Post with URI '.$item["uri"].' already existed for user '.$importer["uid"].'.', Logger::DEBUG);
447 Logger::log('Processing post with URI '.$item["uri"].' for user '.$importer["uid"].'.', Logger::DEBUG);
450 if ($item["verb"] == Activity::JOIN) {
451 // ignore "Join" messages
452 Logger::log("Ignore join message ".print_r($item, true), Logger::DEBUG);
456 if ($item["verb"] == "http://mastodon.social/schema/1.0/block") {
457 // ignore mastodon "block" messages
458 Logger::log("Ignore block message ".print_r($item, true), Logger::DEBUG);
462 if ($item["verb"] == Activity::FOLLOW) {
463 Contact::addRelationship($importer, $contact, $item);
467 if ($item["verb"] == Activity::O_UNFOLLOW) {
469 Contact::removeFollower($importer, $contact, $item, $dummy);
473 if ($item["verb"] == Activity::FAVORITE) {
474 $orig_uri = $xpath->query("activity:object/atom:id", $entry)->item(0)->nodeValue;
475 Logger::log("Favorite ".$orig_uri." ".print_r($item, true));
477 $item["verb"] = Activity::LIKE;
478 $item["parent-uri"] = $orig_uri;
479 $item["gravity"] = GRAVITY_ACTIVITY;
480 $item["object-type"] = Activity\ObjectType::NOTE;
483 // http://activitystrea.ms/schema/1.0/rsvp-yes
484 if (!in_array($item["verb"], [Activity::POST, Activity::LIKE, Activity::SHARE])) {
485 Logger::log("Unhandled verb ".$item["verb"]." ".print_r($item, true), Logger::DEBUG);
488 self::processPost($xpath, $entry, $item, $importer);
490 if ($initialize && (count(self::$itemlist) > 0)) {
491 if (self::$itemlist[0]['uri'] == self::$itemlist[0]['parent-uri']) {
492 // We will import it everytime, when it is started by our contacts
493 $valid = Contact::isSharingByURL(self::$itemlist[0]['author-link'], self::$itemlist[0]['uid']);
496 // If not, then it depends on this setting
497 $valid = ((self::$itemlist[0]['uid'] == 0) || !PConfig::get(self::$itemlist[0]['uid'], 'system', 'accept_only_sharer', false));
499 Logger::log("Item with uri ".self::$itemlist[0]['uri']." will be imported due to the system settings.", Logger::DEBUG);
502 Logger::log("Item with uri ".self::$itemlist[0]['uri']." belongs to a contact (".self::$itemlist[0]['contact-id']."). It will be imported.", Logger::DEBUG);
505 // Never post a thread when the only interaction by our contact was a like
507 $verbs = [Activity::POST, Activity::SHARE];
508 foreach (self::$itemlist as $item) {
509 if (in_array($item['verb'], $verbs) && Contact::isSharingByURL($item['author-link'], $item['uid'])) {
514 Logger::log("Item with uri ".self::$itemlist[0]['uri']." will be imported since the thread contains posts or shares.", Logger::DEBUG);
518 // But we will only import complete threads
519 $valid = Item::exists(['uid' => $importer["uid"], 'uri' => self::$itemlist[0]['parent-uri']]);
521 Logger::log("Item with uri ".self::$itemlist[0]["uri"]." belongs to parent ".self::$itemlist[0]['parent-uri']." of user ".$importer["uid"].". It will be imported.", Logger::DEBUG);
526 $default_contact = 0;
527 for ($key = count(self::$itemlist) - 1; $key >= 0; $key--) {
528 if (empty(self::$itemlist[$key]['contact-id'])) {
529 self::$itemlist[$key]['contact-id'] = $default_contact;
531 $default_contact = $item['contact-id'];
534 foreach (self::$itemlist as $item) {
535 $found = Item::exists(['uid' => $importer["uid"], 'uri' => $item["uri"]]);
537 Logger::log("Item with uri ".$item["uri"]." for user ".$importer["uid"]." already exists.", Logger::DEBUG);
538 } elseif ($item['contact-id'] < 0) {
539 Logger::log("Item with uri ".$item["uri"]." is from a blocked contact.", Logger::DEBUG);
541 // We are having duplicated entries. Hopefully this solves it.
542 if (DI::lock()->acquire('ostatus_process_item_insert')) {
543 $ret = Item::insert($item);
544 DI::lock()->release('ostatus_process_item_insert');
545 Logger::log("Item with uri ".$item["uri"]." for user ".$importer["uid"].' stored. Return value: '.$ret);
547 $ret = Item::insert($item);
548 Logger::log("We couldn't lock - but tried to store the item anyway. Return value is ".$ret);
553 self::$itemlist = [];
555 Logger::log('Processing done for post with URI '.$item["uri"].' for user '.$importer["uid"].'.', Logger::DEBUG);
561 * Removes notice item from database
563 * @param array $item item
567 private static function deleteNotice(array $item)
569 $condition = ['uid' => $item['uid'], 'author-id' => $item['author-id'], 'uri' => $item['uri']];
570 if (!Item::exists($condition)) {
571 Logger::log('Item from '.$item['author-link'].' with uri '.$item['uri'].' for user '.$item['uid']." wasn't found. We don't delete it.");
575 Item::delete($condition);
577 Logger::log('Deleted item with uri '.$item['uri'].' for user '.$item['uid']);
581 * @brief Processes the XML for a post
583 * @param DOMXPath $xpath The xpath object
584 * @param object $entry The xml entry that is processed
585 * @param array $item The item array
586 * @param array $importer user record of the importing user
588 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
589 * @throws \ImagickException
591 private static function processPost(DOMXPath $xpath, $entry, array &$item, array $importer)
593 $item["body"] = HTML::toBBCode(XML::getFirstNodeValue($xpath, 'atom:content/text()', $entry));
594 $item["object-type"] = XML::getFirstNodeValue($xpath, 'activity:object-type/text()', $entry);
595 if (($item["object-type"] == Activity\ObjectType::BOOKMARK) || ($item["object-type"] == Activity\ObjectType::EVENT)) {
596 $item["title"] = XML::getFirstNodeValue($xpath, 'atom:title/text()', $entry);
597 $item["body"] = XML::getFirstNodeValue($xpath, 'atom:summary/text()', $entry);
598 } elseif ($item["object-type"] == Activity\ObjectType::QUESTION) {
599 $item["title"] = XML::getFirstNodeValue($xpath, 'atom:title/text()', $entry);
602 $item["created"] = XML::getFirstNodeValue($xpath, 'atom:published/text()', $entry);
603 $item["edited"] = XML::getFirstNodeValue($xpath, 'atom:updated/text()', $entry);
604 $item['conversation-uri'] = XML::getFirstNodeValue($xpath, 'ostatus:conversation/text()', $entry);
606 $conv = $xpath->query('ostatus:conversation', $entry);
607 if (is_object($conv->item(0))) {
608 foreach ($conv->item(0)->attributes as $attributes) {
609 if ($attributes->name == "ref") {
610 $item['conversation-uri'] = $attributes->textContent;
612 if ($attributes->name == "href") {
613 $item['conversation-href'] = $attributes->textContent;
620 $inreplyto = $xpath->query('thr:in-reply-to', $entry);
621 if (is_object($inreplyto->item(0))) {
622 foreach ($inreplyto->item(0)->attributes as $attributes) {
623 if ($attributes->name == "ref") {
624 $item["parent-uri"] = $attributes->textContent;
626 if ($attributes->name == "href") {
627 $related = $attributes->textContent;
632 $georsspoint = $xpath->query('georss:point', $entry);
633 if (!empty($georsspoint) && ($georsspoint->length > 0)) {
634 $item["coord"] = $georsspoint->item(0)->nodeValue;
637 $categories = $xpath->query('atom:category', $entry);
639 foreach ($categories as $category) {
640 foreach ($category->attributes as $attributes) {
641 if ($attributes->name == 'term') {
642 $term = $attributes->textContent;
643 if (!empty($item['tag'])) {
649 $item['tag'] .= '#[url=' . DI::baseUrl() . '/search?tag=' . $term . ']' . $term . '[/url]';
658 $links = $xpath->query('atom:link', $entry);
660 $link_data = self::processLinks($links, $item);
661 $self = $link_data['self'];
662 $add_body = $link_data['add_body'];
667 $notice_info = $xpath->query('statusnet:notice_info', $entry);
668 if ($notice_info && ($notice_info->length > 0)) {
669 foreach ($notice_info->item(0)->attributes as $attributes) {
670 if ($attributes->name == "source") {
671 $item["app"] = strip_tags($attributes->textContent);
673 if ($attributes->name == "repeat_of") {
674 $repeat_of = $attributes->textContent;
678 // Is it a repeated post?
679 if (($repeat_of != "") || ($item["verb"] == Activity::SHARE)) {
680 $link_data = self::processRepeatedItem($xpath, $entry, $item, $importer);
681 if (!empty($link_data['add_body'])) {
682 $add_body .= $link_data['add_body'];
686 $item["body"] .= $add_body;
688 // Only add additional data when there is no picture in the post
689 if (!strstr($item["body"], '[/img]')) {
690 $item["body"] = add_page_info_to_body($item["body"]);
693 // Mastodon Content Warning
694 if (($item["verb"] == Activity::POST) && $xpath->evaluate('boolean(atom:summary)', $entry)) {
695 $clear_text = XML::getFirstNodeValue($xpath, 'atom:summary/text()', $entry);
696 if (!empty($clear_text)) {
697 $item['content-warning'] = HTML::toBBCode($clear_text);
701 if (($self != '') && empty($item['protocol'])) {
702 self::fetchSelf($self, $item);
705 if (!empty($item["conversation-href"])) {
706 self::fetchConversation($item['conversation-href'], $item['conversation-uri']);
709 if (isset($item["parent-uri"])) {
710 if (!Item::exists(['uid' => $importer["uid"], 'uri' => $item['parent-uri']])) {
711 if ($related != '') {
712 self::fetchRelated($related, $item["parent-uri"], $importer);
715 Logger::log('Reply with URI '.$item["uri"].' already existed for user '.$importer["uid"].'.', Logger::DEBUG);
718 $item["parent-uri"] = $item["uri"];
719 $item["gravity"] = GRAVITY_PARENT;
722 if (($item['author-link'] != '') && !empty($item['protocol'])) {
723 $item = Conversation::insert($item);
726 self::$itemlist[] = $item;
730 * @brief Fetch the conversation for posts
732 * @param string $conversation The link to the conversation
733 * @param string $conversation_uri The conversation in "uri" format
735 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
737 private static function fetchConversation($conversation, $conversation_uri)
739 // Ensure that we only store a conversation once in a process
740 if (isset(self::$conv_list[$conversation])) {
744 self::$conv_list[$conversation] = true;
746 $curlResult = Network::curl($conversation, false, ['accept_content' => 'application/atom+xml, text/html']);
748 if (!$curlResult->isSuccess()) {
754 if (stristr($curlResult->getHeader(), 'Content-Type: application/atom+xml')) {
755 $xml = $curlResult->getBody();
759 $doc = new DOMDocument();
760 if (!@$doc->loadHTML($curlResult->getBody())) {
763 $xpath = new DOMXPath($doc);
765 $links = $xpath->query('//link');
768 foreach ($links as $link) {
769 $attribute = self::readAttributes($link);
770 if (($attribute['rel'] == 'alternate') && ($attribute['type'] == 'application/atom+xml')) {
771 $file = $attribute['href'];
775 $conversation_atom = Network::curl($attribute['href']);
777 if ($conversation_atom->isSuccess()) {
778 $xml = $conversation_atom->getBody();
788 self::storeConversation($xml, $conversation, $conversation_uri);
792 * @brief Store a feed in several conversation entries
794 * @param string $xml The feed
795 * @param string $conversation conversation
796 * @param string $conversation_uri conversation uri
800 private static function storeConversation($xml, $conversation = '', $conversation_uri = '')
802 $doc = new DOMDocument();
803 @$doc->loadXML($xml);
805 $xpath = new DOMXPath($doc);
806 $xpath->registerNamespace('atom', ActivityNamespace::ATOM1);
807 $xpath->registerNamespace('thr', ActivityNamespace::THREAD);
808 $xpath->registerNamespace('ostatus', ActivityNamespace::OSTATUS);
810 $entries = $xpath->query('/atom:feed/atom:entry');
812 // Now store the entries
813 foreach ($entries as $entry) {
814 $doc2 = new DOMDocument();
815 $doc2->preserveWhiteSpace = false;
816 $doc2->formatOutput = true;
820 $conv_data['protocol'] = Conversation::PARCEL_SPLIT_CONVERSATION;
821 $conv_data['network'] = Protocol::OSTATUS;
822 $conv_data['uri'] = XML::getFirstNodeValue($xpath, 'atom:id/text()', $entry);
824 $inreplyto = $xpath->query('thr:in-reply-to', $entry);
825 if (is_object($inreplyto->item(0))) {
826 foreach ($inreplyto->item(0)->attributes as $attributes) {
827 if ($attributes->name == "ref") {
828 $conv_data['reply-to-uri'] = $attributes->textContent;
833 $conv_data['conversation-uri'] = XML::getFirstNodeValue($xpath, 'ostatus:conversation/text()', $entry);
835 $conv = $xpath->query('ostatus:conversation', $entry);
836 if (is_object($conv->item(0))) {
837 foreach ($conv->item(0)->attributes as $attributes) {
838 if ($attributes->name == "ref") {
839 $conv_data['conversation-uri'] = $attributes->textContent;
841 if ($attributes->name == "href") {
842 $conv_data['conversation-href'] = $attributes->textContent;
847 if ($conversation != '') {
848 $conv_data['conversation-uri'] = $conversation;
851 if ($conversation_uri != '') {
852 $conv_data['conversation-uri'] = $conversation_uri;
855 $entry = $doc2->importNode($entry, true);
857 $doc2->appendChild($entry);
859 $conv_data['source'] = $doc2->saveXML();
861 $condition = ['item-uri' => $conv_data['uri'],'protocol' => Conversation::PARCEL_FEED];
862 if (DBA::exists('conversation', $condition)) {
863 Logger::log('Delete deprecated entry for URI '.$conv_data['uri'], Logger::DEBUG);
864 DBA::delete('conversation', ['item-uri' => $conv_data['uri']]);
867 Logger::log('Store conversation data for uri '.$conv_data['uri'], Logger::DEBUG);
868 Conversation::insert($conv_data);
873 * @brief Fetch the own post so that it can be stored later
875 * We want to store the original data for later processing.
876 * This function is meant for cases where we process a feed with multiple entries.
877 * In that case we need to fetch the single posts here.
879 * @param string $self The link to the self item
880 * @param array $item The item array
882 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
884 private static function fetchSelf($self, array &$item)
886 $condition = ['`item-uri` = ? AND `protocol` IN (?, ?)', $self, Conversation::PARCEL_DFRN, Conversation::PARCEL_SALMON];
887 if (DBA::exists('conversation', $condition)) {
888 Logger::log('Conversation '.$item['uri'].' is already stored.', Logger::DEBUG);
892 $curlResult = Network::curl($self);
894 if (!$curlResult->isSuccess()) {
898 // We reformat the XML to make it better readable
899 $doc = new DOMDocument();
900 $doc->loadXML($curlResult->getBody());
901 $doc->preserveWhiteSpace = false;
902 $doc->formatOutput = true;
903 $xml = $doc->saveXML();
905 $item["protocol"] = Conversation::PARCEL_SALMON;
906 $item["source"] = $xml;
908 Logger::log('Conversation '.$item['uri'].' is now fetched.', Logger::DEBUG);
912 * @brief Fetch related posts and processes them
914 * @param string $related The link to the related item
915 * @param string $related_uri The related item in "uri" format
916 * @param array $importer user record of the importing user
918 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
919 * @throws \ImagickException
921 private static function fetchRelated($related, $related_uri, $importer)
923 $condition = ['`item-uri` = ? AND `protocol` IN (?, ?)', $related_uri, Conversation::PARCEL_DFRN, Conversation::PARCEL_SALMON];
924 $conversation = DBA::selectFirst('conversation', ['source', 'protocol'], $condition);
925 if (DBA::isResult($conversation)) {
927 $xml = $conversation['source'];
928 if (self::process($xml, $importer, $contact, $hub, $stored, false)) {
929 Logger::log('Got valid cached XML for URI '.$related_uri, Logger::DEBUG);
932 if ($conversation['protocol'] == Conversation::PARCEL_SALMON) {
933 Logger::log('Delete invalid cached XML for URI '.$related_uri, Logger::DEBUG);
934 DBA::delete('conversation', ['item-uri' => $related_uri]);
939 $curlResult = Network::curl($related, false, ['accept_content' => 'application/atom+xml, text/html']);
941 if (!$curlResult->isSuccess()) {
947 if (stristr($curlResult->getHeader(), 'Content-Type: application/atom+xml')) {
948 Logger::log('Directly fetched XML for URI ' . $related_uri, Logger::DEBUG);
949 $xml = $curlResult->getBody();
953 $doc = new DOMDocument();
954 if (!@$doc->loadHTML($curlResult->getBody())) {
957 $xpath = new DOMXPath($doc);
961 $links = $xpath->query('//link');
963 foreach ($links as $link) {
964 $attribute = self::readAttributes($link);
965 if (($attribute['rel'] == 'alternate') && ($attribute['type'] == 'application/atom+xml')) {
966 $atom_file = $attribute['href'];
969 if ($atom_file != '') {
970 $curlResult = Network::curl($atom_file);
972 if ($curlResult->isSuccess()) {
973 Logger::log('Fetched XML for URI ' . $related_uri, Logger::DEBUG);
974 $xml = $curlResult->getBody();
980 // Workaround for older GNU Social servers
981 if (($xml == '') && strstr($related, '/notice/')) {
982 $curlResult = Network::curl(str_replace('/notice/', '/api/statuses/show/', $related).'.atom');
984 if ($curlResult->isSuccess()) {
985 Logger::log('GNU Social workaround to fetch XML for URI ' . $related_uri, Logger::DEBUG);
986 $xml = $curlResult->getBody();
990 // Even more worse workaround for GNU Social ;-)
992 $related_guess = OStatus::convertHref($related_uri);
993 $curlResult = Network::curl(str_replace('/notice/', '/api/statuses/show/', $related_guess).'.atom');
995 if ($curlResult->isSuccess()) {
996 Logger::log('GNU Social workaround 2 to fetch XML for URI ' . $related_uri, Logger::DEBUG);
997 $xml = $curlResult->getBody();
1001 // Finally we take the data that we fetched from "ostatus:conversation"
1003 $condition = ['item-uri' => $related_uri, 'protocol' => Conversation::PARCEL_SPLIT_CONVERSATION];
1004 $conversation = DBA::selectFirst('conversation', ['source'], $condition);
1005 if (DBA::isResult($conversation)) {
1007 Logger::log('Got cached XML from conversation for URI '.$related_uri, Logger::DEBUG);
1008 $xml = $conversation['source'];
1013 self::process($xml, $importer, $contact, $hub, $stored, false);
1015 Logger::log("XML couldn't be fetched for URI: ".$related_uri." - href: ".$related, Logger::DEBUG);
1021 * @brief Processes the XML for a repeated post
1023 * @param DOMXPath $xpath The xpath object
1024 * @param object $entry The xml entry that is processed
1025 * @param array $item The item array
1026 * @param array $importer user record of the importing user
1028 * @return array with data from links
1029 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1030 * @throws \ImagickException
1032 private static function processRepeatedItem(DOMXPath $xpath, $entry, array &$item, array $importer)
1034 $activityobject = $xpath->query('activity:object', $entry)->item(0);
1036 if (!is_object($activityobject)) {
1042 $orig_uri = XML::getFirstNodeValue($xpath, 'atom:id/text()', $activityobject);
1044 $links = $xpath->query("atom:link", $activityobject);
1046 $link_data = self::processLinks($links, $item);
1049 $orig_body = XML::getFirstNodeValue($xpath, 'atom:content/text()', $activityobject);
1050 $orig_created = XML::getFirstNodeValue($xpath, 'atom:published/text()', $activityobject);
1051 $orig_edited = XML::getFirstNodeValue($xpath, 'atom:updated/text()', $activityobject);
1053 $orig_author = self::fetchAuthor($xpath, $activityobject, $importer, $dummy, false);
1055 $item["author-name"] = $orig_author["author-name"];
1056 $item["author-link"] = $orig_author["author-link"];
1057 $item["author-id"] = $orig_author["author-id"];
1059 $item["body"] = HTML::toBBCode($orig_body);
1060 $item["created"] = $orig_created;
1061 $item["edited"] = $orig_edited;
1063 $item["uri"] = $orig_uri;
1065 $item["verb"] = XML::getFirstNodeValue($xpath, 'activity:verb/text()', $activityobject);
1067 $item["object-type"] = XML::getFirstNodeValue($xpath, 'activity:object-type/text()', $activityobject);
1069 // Mastodon Content Warning
1070 if (($item["verb"] == Activity::POST) && $xpath->evaluate('boolean(atom:summary)', $activityobject)) {
1071 $clear_text = XML::getFirstNodeValue($xpath, 'atom:summary/text()', $activityobject);
1072 if (!empty($clear_text)) {
1073 $item['content-warning'] = HTML::toBBCode($clear_text);
1077 $inreplyto = $xpath->query('thr:in-reply-to', $activityobject);
1078 if (is_object($inreplyto->item(0))) {
1079 foreach ($inreplyto->item(0)->attributes as $attributes) {
1080 if ($attributes->name == "ref") {
1081 $item["parent-uri"] = $attributes->textContent;
1090 * @brief Processes links in the XML
1092 * @param object $links The xml data that contain links
1093 * @param array $item The item array
1095 * @return array with data from the links
1097 private static function processLinks($links, array &$item)
1099 $link_data = ['add_body' => '', 'self' => ''];
1101 foreach ($links as $link) {
1102 $attribute = self::readAttributes($link);
1104 if (!empty($attribute['rel']) && !empty($attribute['href'])) {
1105 switch ($attribute['rel']) {
1107 $item["plink"] = $attribute['href'];
1108 if (($item["object-type"] == Activity\ObjectType::QUESTION)
1109 || ($item["object-type"] == Activity\ObjectType::EVENT)
1111 $item["body"] .= add_page_info($attribute['href']);
1114 case "ostatus:conversation":
1115 $link_data['conversation'] = $attribute['href'];
1116 $item['conversation-href'] = $link_data['conversation'];
1117 if (!isset($item['conversation-uri'])) {
1118 $item['conversation-uri'] = $item['conversation-href'];
1122 $filetype = strtolower(substr($attribute['type'], 0, strpos($attribute['type'], '/')));
1123 if ($filetype == 'image') {
1124 $link_data['add_body'] .= "\n[img]".$attribute['href'].'[/img]';
1126 if (!empty($item["attach"])) {
1127 $item["attach"] .= ',';
1129 $item["attach"] = '';
1131 if (!isset($attribute['length'])) {
1132 $attribute['length'] = "0";
1134 $item["attach"] .= '[attach]href="'.$attribute['href'].'" length="'.$attribute['length'].'" type="'.$attribute['type'].'" title="'.($attribute['title'] ?? '') .'"[/attach]';
1138 if ($item["object-type"] != Activity\ObjectType::BOOKMARK) {
1139 if (!isset($item["parent-uri"])) {
1140 $item["parent-uri"] = $attribute['href'];
1142 $link_data['related'] = $attribute['href'];
1144 $item["body"] .= add_page_info($attribute['href']);
1148 if (empty($item["plink"])) {
1149 $item["plink"] = $attribute['href'];
1151 $link_data['self'] = $attribute['href'];
1160 * @brief Create an url out of an uri
1162 * @param string $href URI in the format "parameter1:parameter1:..."
1164 * @return string URL in the format http(s)://....
1166 public static function convertHref($href)
1168 $elements = explode(":", $href);
1170 if ((count($elements) <= 2) || ($elements[0] != "tag")) {
1174 $server = explode(",", $elements[1]);
1175 $conversation = explode("=", $elements[2]);
1177 if ((count($elements) == 4) && ($elements[2] == "post")) {
1178 return "http://".$server[0]."/notice/".$elements[3];
1181 if ((count($conversation) != 2) || ($conversation[1] =="")) {
1184 if ($elements[3] == "objectType=thread") {
1185 return "http://".$server[0]."/conversation/".$conversation[1];
1187 return "http://".$server[0]."/notice/".$conversation[1];
1192 * @brief Checks if the current post is a reshare
1194 * @param array $item The item array of thw post
1196 * @return string The guid if the post is a reshare
1198 private static function getResharedGuid(array $item)
1200 $reshared = Item::getShareArray($item);
1201 if (empty($reshared['guid']) || !empty($reshared['comment'])) {
1205 return $reshared['guid'];
1209 * @brief Cleans the body of a post if it contains picture links
1211 * @param string $body The body
1213 * @return string The cleaned body
1214 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1216 private static function formatPicturePost($body)
1218 $siteinfo = BBCode::getAttachedData($body);
1220 if (($siteinfo["type"] == "photo") && (!empty($siteinfo["preview"]) || !empty($siteinfo["image"]))) {
1221 if (isset($siteinfo["preview"])) {
1222 $preview = $siteinfo["preview"];
1224 $preview = $siteinfo["image"];
1227 // Is it a remote picture? Then make a smaller preview here
1228 $preview = ProxyUtils::proxifyUrl($preview, false, ProxyUtils::SIZE_SMALL);
1230 // Is it a local picture? Then make it smaller here
1231 $preview = str_replace(["-0.jpg", "-0.png"], ["-2.jpg", "-2.png"], $preview);
1232 $preview = str_replace(["-1.jpg", "-1.png"], ["-2.jpg", "-2.png"], $preview);
1234 if (isset($siteinfo["url"])) {
1235 $url = $siteinfo["url"];
1237 $url = $siteinfo["image"];
1240 $body = trim($siteinfo["text"])." [url]".$url."[/url]\n[img]".$preview."[/img]";
1247 * @brief Adds the header elements to the XML document
1249 * @param DOMDocument $doc XML document
1250 * @param array $owner Contact data of the poster
1251 * @param string $filter The related feed filter (activity, posts or comments)
1252 * @param bool $feed_mode Behave like a regular feed for users if true
1254 * @return object header root element
1255 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1257 private static function addHeader(DOMDocument $doc, array $owner, $filter, $feed_mode = false)
1259 $root = $doc->createElementNS(ActivityNamespace::ATOM1, 'feed');
1260 $doc->appendChild($root);
1262 $root->setAttribute("xmlns:thr", ActivityNamespace::THREAD);
1263 $root->setAttribute("xmlns:georss", ActivityNamespace::GEORSS);
1264 $root->setAttribute("xmlns:activity", ActivityNamespace::ACTIVITY);
1265 $root->setAttribute("xmlns:media", ActivityNamespace::MEDIA);
1266 $root->setAttribute("xmlns:poco", ActivityNamespace::POCO);
1267 $root->setAttribute("xmlns:ostatus", ActivityNamespace::OSTATUS);
1268 $root->setAttribute("xmlns:statusnet", ActivityNamespace::STATUSNET);
1269 $root->setAttribute("xmlns:mastodon", ActivityNamespace::MASTODON);
1272 $selfUri = '/feed/' . $owner["nick"] . '/';
1275 $title = L10n::t('%s\'s timeline', $owner['name']);
1276 $selfUri .= $filter;
1279 $title = L10n::t('%s\'s posts', $owner['name']);
1282 $title = L10n::t('%s\'s comments', $owner['name']);
1283 $selfUri .= $filter;
1288 $selfUri = "/dfrn_poll/" . $owner["nick"];
1291 $attributes = ["uri" => "https://friendi.ca", "version" => FRIENDICA_VERSION . "-" . DB_UPDATE_VERSION];
1292 XML::addElement($doc, $root, "generator", FRIENDICA_PLATFORM, $attributes);
1293 XML::addElement($doc, $root, "id", DI::baseUrl() . "/profile/" . $owner["nick"]);
1294 XML::addElement($doc, $root, "title", $title);
1295 XML::addElement($doc, $root, "subtitle", sprintf("Updates from %s on %s", $owner["name"], Config::get('config', 'sitename')));
1296 XML::addElement($doc, $root, "logo", $owner["photo"]);
1297 XML::addElement($doc, $root, "updated", DateTimeFormat::utcNow(DateTimeFormat::ATOM));
1299 $author = self::addAuthor($doc, $owner);
1300 $root->appendChild($author);
1302 $attributes = ["href" => $owner["url"], "rel" => "alternate", "type" => "text/html"];
1303 XML::addElement($doc, $root, "link", "", $attributes);
1305 /// @TODO We have to find out what this is
1306 /// $attributes = array("href" => DI::baseUrl()."/sup",
1307 /// "rel" => "http://api.friendfeed.com/2008/03#sup",
1308 /// "type" => "application/json");
1309 /// XML::addElement($doc, $root, "link", "", $attributes);
1311 self::hublinks($doc, $root, $owner["nick"]);
1313 $attributes = ["href" => DI::baseUrl() . "/salmon/" . $owner["nick"], "rel" => "salmon"];
1314 XML::addElement($doc, $root, "link", "", $attributes);
1316 $attributes = ["href" => DI::baseUrl() . "/salmon/" . $owner["nick"], "rel" => "http://salmon-protocol.org/ns/salmon-replies"];
1317 XML::addElement($doc, $root, "link", "", $attributes);
1319 $attributes = ["href" => DI::baseUrl() . "/salmon/" . $owner["nick"], "rel" => "http://salmon-protocol.org/ns/salmon-mention"];
1320 XML::addElement($doc, $root, "link", "", $attributes);
1322 $attributes = ["href" => DI::baseUrl() . $selfUri, "rel" => "self", "type" => "application/atom+xml"];
1323 XML::addElement($doc, $root, "link", "", $attributes);
1325 if ($owner['account-type'] == Contact::TYPE_COMMUNITY) {
1326 $condition = ['uid' => $owner['uid'], 'self' => false, 'pending' => false,
1327 'archive' => false, 'hidden' => false, 'blocked' => false];
1328 $members = DBA::count('contact', $condition);
1329 XML::addElement($doc, $root, "statusnet:group_info", "", ["member_count" => $members]);
1336 * @brief Add the link to the push hubs to the XML document
1338 * @param DOMDocument $doc XML document
1339 * @param object $root XML root element where the hub links are added
1340 * @param object $nick nick
1342 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1344 public static function hublinks(DOMDocument $doc, $root, $nick)
1346 $h = DI::baseUrl() . '/pubsubhubbub/'.$nick;
1347 XML::addElement($doc, $root, "link", "", ["href" => $h, "rel" => "hub"]);
1351 * @brief Adds attachment data to the XML document
1353 * @param DOMDocument $doc XML document
1354 * @param object $root XML root element where the hub links are added
1355 * @param array $item Data of the item that is to be posted
1357 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1359 private static function getAttachment(DOMDocument $doc, $root, $item)
1361 $siteinfo = BBCode::getAttachedData($item["body"]);
1363 switch ($siteinfo["type"]) {
1365 if (!empty($siteinfo["image"])) {
1366 $imgdata = Images::getInfoFromURLCached($siteinfo["image"]);
1368 $attributes = ["rel" => "enclosure",
1369 "href" => $siteinfo["image"],
1370 "type" => $imgdata["mime"],
1371 "length" => intval($imgdata["size"])];
1372 XML::addElement($doc, $root, "link", "", $attributes);
1377 $attributes = ["rel" => "enclosure",
1378 "href" => $siteinfo["url"],
1379 "type" => "text/html; charset=UTF-8",
1381 "title" => ($siteinfo["title"] ?? '') ?: $siteinfo["url"],
1383 XML::addElement($doc, $root, "link", "", $attributes);
1389 if (!Config::get('system', 'ostatus_not_attach_preview') && ($siteinfo["type"] != "photo") && isset($siteinfo["image"])) {
1390 $imgdata = Images::getInfoFromURLCached($siteinfo["image"]);
1392 $attributes = ["rel" => "enclosure",
1393 "href" => $siteinfo["image"],
1394 "type" => $imgdata["mime"],
1395 "length" => intval($imgdata["size"])];
1397 XML::addElement($doc, $root, "link", "", $attributes);
1401 $arr = explode('[/attach],', $item['attach']);
1403 foreach ($arr as $r) {
1405 $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"|', $r, $matches);
1407 $attributes = ["rel" => "enclosure",
1408 "href" => $matches[1],
1409 "type" => $matches[3]];
1411 if (intval($matches[2])) {
1412 $attributes["length"] = intval($matches[2]);
1414 if (trim($matches[4]) != "") {
1415 $attributes["title"] = trim($matches[4]);
1417 XML::addElement($doc, $root, "link", "", $attributes);
1424 * @brief Adds the author element to the XML document
1426 * @param DOMDocument $doc XML document
1427 * @param array $owner Contact data of the poster
1428 * @param bool $show_profile Whether to show profile
1430 * @return \DOMElement author element
1431 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1433 private static function addAuthor(DOMDocument $doc, array $owner, $show_profile = true)
1435 $profile = DBA::selectFirst('profile', ['homepage', 'publish'], ['uid' => $owner['uid'], 'is-default' => true]);
1436 $author = $doc->createElement("author");
1437 XML::addElement($doc, $author, "id", $owner["url"]);
1438 if ($owner['account-type'] == User::ACCOUNT_TYPE_COMMUNITY) {
1439 XML::addElement($doc, $author, "activity:object-type", Activity\ObjectType::GROUP);
1441 XML::addElement($doc, $author, "activity:object-type", Activity\ObjectType::PERSON);
1443 XML::addElement($doc, $author, "uri", $owner["url"]);
1444 XML::addElement($doc, $author, "name", $owner["nick"]);
1445 XML::addElement($doc, $author, "email", $owner["addr"]);
1446 if ($show_profile) {
1447 XML::addElement($doc, $author, "summary", BBCode::convert($owner["about"], false, 7));
1450 $attributes = ["rel" => "alternate", "type" => "text/html", "href" => $owner["url"]];
1451 XML::addElement($doc, $author, "link", "", $attributes);
1455 "type" => "image/jpeg", // To-Do?
1456 "media:width" => 300,
1457 "media:height" => 300,
1458 "href" => $owner["photo"]];
1459 XML::addElement($doc, $author, "link", "", $attributes);
1461 if (isset($owner["thumb"])) {
1464 "type" => "image/jpeg", // To-Do?
1465 "media:width" => 80,
1466 "media:height" => 80,
1467 "href" => $owner["thumb"]];
1468 XML::addElement($doc, $author, "link", "", $attributes);
1471 XML::addElement($doc, $author, "poco:preferredUsername", $owner["nick"]);
1472 XML::addElement($doc, $author, "poco:displayName", $owner["name"]);
1473 if ($show_profile) {
1474 XML::addElement($doc, $author, "poco:note", BBCode::convert($owner["about"], false, 7));
1476 if (trim($owner["location"]) != "") {
1477 $element = $doc->createElement("poco:address");
1478 XML::addElement($doc, $element, "poco:formatted", $owner["location"]);
1479 $author->appendChild($element);
1483 if (DBA::isResult($profile) && !$show_profile) {
1484 if (trim($profile["homepage"]) != "") {
1485 $urls = $doc->createElement("poco:urls");
1486 XML::addElement($doc, $urls, "poco:type", "homepage");
1487 XML::addElement($doc, $urls, "poco:value", $profile["homepage"]);
1488 XML::addElement($doc, $urls, "poco:primary", "true");
1489 $author->appendChild($urls);
1492 XML::addElement($doc, $author, "followers", "", ["url" => DI::baseUrl() . "/profile/" . $owner["nick"] . "/contacts/followers"]);
1493 XML::addElement($doc, $author, "statusnet:profile_info", "", ["local_id" => $owner["uid"]]);
1495 if ($profile["publish"]) {
1496 XML::addElement($doc, $author, "mastodon:scope", "public");
1504 * @TODO Picture attachments should look like this:
1505 * <a href="https://status.pirati.ca/attachment/572819" title="https://status.pirati.ca/file/heluecht-20151202T222602-rd3u49p.gif"
1506 * class="attachment thumbnail" id="attachment-572819" rel="nofollow external">https://status.pirati.ca/attachment/572819</a>
1510 * @brief Returns the given activity if present - otherwise returns the "post" activity
1512 * @param array $item Data of the item that is to be posted
1514 * @return string activity
1516 private static function constructVerb(array $item)
1518 if (!empty($item['verb'])) {
1519 return $item['verb'];
1522 return Activity::POST;
1526 * @brief Returns the given object type if present - otherwise returns the "note" object type
1528 * @param array $item Data of the item that is to be posted
1530 * @return string Object type
1532 private static function constructObjecttype(array $item)
1534 if (!empty($item['object-type']) && in_array($item['object-type'], [Activity\ObjectType::NOTE, Activity\ObjectType::COMMENT])) {
1535 return $item['object-type'];
1538 return Activity\ObjectType::NOTE;
1542 * @brief Adds an entry element to the XML document
1544 * @param DOMDocument $doc XML document
1545 * @param array $item Data of the item that is to be posted
1546 * @param array $owner Contact data of the poster
1547 * @param bool $toplevel optional default false
1548 * @param bool $feed_mode Behave like a regular feed for users if true
1550 * @return \DOMElement Entry element
1551 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1552 * @throws \ImagickException
1554 private static function entry(DOMDocument $doc, array $item, array $owner, $toplevel = false, $feed_mode = false)
1558 $repeated_guid = self::getResharedGuid($item);
1559 if ($repeated_guid != "") {
1560 $xml = self::reshareEntry($doc, $item, $owner, $repeated_guid, $toplevel);
1567 if ($item["verb"] == Activity::LIKE) {
1568 return self::likeEntry($doc, $item, $owner, $toplevel);
1569 } elseif (in_array($item["verb"], [Activity::FOLLOW, Activity::O_UNFOLLOW])) {
1570 return self::followEntry($doc, $item, $owner, $toplevel);
1572 return self::noteEntry($doc, $item, $owner, $toplevel, $feed_mode);
1577 * @brief Adds a source entry to the XML document
1579 * @param DOMDocument $doc XML document
1580 * @param array $contact Array of the contact that is added
1582 * @return \DOMElement Source element
1583 * @throws \Exception
1585 private static function sourceEntry(DOMDocument $doc, array $contact)
1587 $source = $doc->createElement("source");
1588 XML::addElement($doc, $source, "id", $contact["poll"]);
1589 XML::addElement($doc, $source, "title", $contact["name"]);
1590 XML::addElement($doc, $source, "link", "", ["rel" => "alternate", "type" => "text/html", "href" => $contact["alias"]]);
1591 XML::addElement($doc, $source, "link", "", ["rel" => "self", "type" => "application/atom+xml", "href" => $contact["poll"]]);
1592 XML::addElement($doc, $source, "icon", $contact["photo"]);
1593 XML::addElement($doc, $source, "updated", DateTimeFormat::utc($contact["success_update"]."+00:00", DateTimeFormat::ATOM));
1599 * @brief Fetches contact data from the contact or the gcontact table
1601 * @param string $url URL of the contact
1602 * @param array $owner Contact data of the poster
1604 * @return array Contact array
1605 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1606 * @throws \ImagickException
1608 private static function contactEntry($url, array $owner)
1611 "SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` IN (0, %d) ORDER BY `uid` DESC LIMIT 1",
1612 DBA::escape(Strings::normaliseLink($url)),
1613 intval($owner["uid"])
1615 if (DBA::isResult($r)) {
1617 $contact["uid"] = -1;
1620 if (!DBA::isResult($r)) {
1621 $gcontact = DBA::selectFirst('gcontact', [], ['nurl' => Strings::normaliseLink($url)]);
1622 if (DBA::isResult($r)) {
1623 $contact = $gcontact;
1624 $contact["uid"] = -1;
1625 $contact["success_update"] = $contact["updated"];
1629 if (!DBA::isResult($r)) {
1633 if (!isset($contact["poll"])) {
1634 $data = Probe::uri($url);
1635 $contact["poll"] = $data["poll"];
1637 if (!$contact["alias"]) {
1638 $contact["alias"] = $data["alias"];
1642 if (!isset($contact["alias"])) {
1643 $contact["alias"] = $contact["url"];
1646 $contact['account-type'] = $owner['account-type'];
1652 * @brief Adds an entry element with reshared content
1654 * @param DOMDocument $doc XML document
1655 * @param array $item Data of the item that is to be posted
1656 * @param array $owner Contact data of the poster
1657 * @param string $repeated_guid guid
1658 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1660 * @return bool Entry element
1661 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1662 * @throws \ImagickException
1664 private static function reshareEntry(DOMDocument $doc, array $item, array $owner, $repeated_guid, $toplevel)
1666 if (($item["id"] != $item["parent"]) && (Strings::normaliseLink($item["author-link"]) != Strings::normaliseLink($owner["url"]))) {
1667 Logger::log("OStatus entry is from author ".$owner["url"]." - not from ".$item["author-link"].". Quitting.", Logger::DEBUG);
1670 $entry = self::entryHeader($doc, $owner, $item, $toplevel);
1672 $condition = ['uid' => $owner["uid"], 'guid' => $repeated_guid, 'private' => false,
1673 'network' => [Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS]];
1674 $repeated_item = Item::selectFirst([], $condition);
1675 if (!DBA::isResult($repeated_item)) {
1679 $contact = self::contactEntry($repeated_item['author-link'], $owner);
1681 $title = $owner["nick"]." repeated a notice by ".$contact["nick"];
1683 self::entryContent($doc, $entry, $item, $owner, $title, Activity::SHARE, false);
1685 $as_object = $doc->createElement("activity:object");
1687 XML::addElement($doc, $as_object, "activity:object-type", ActivityNamespace::ACTIVITY_SCHEMA . "activity");
1689 self::entryContent($doc, $as_object, $repeated_item, $owner, "", "", false);
1691 $author = self::addAuthor($doc, $contact, false);
1692 $as_object->appendChild($author);
1694 $as_object2 = $doc->createElement("activity:object");
1696 XML::addElement($doc, $as_object2, "activity:object-type", self::constructObjecttype($repeated_item));
1698 $title = sprintf("New comment by %s", $contact["nick"]);
1700 self::entryContent($doc, $as_object2, $repeated_item, $owner, $title);
1702 $as_object->appendChild($as_object2);
1704 self::entryFooter($doc, $as_object, $item, $owner, false);
1706 $source = self::sourceEntry($doc, $contact);
1708 $as_object->appendChild($source);
1710 $entry->appendChild($as_object);
1712 self::entryFooter($doc, $entry, $item, $owner);
1718 * @brief Adds an entry element with a "like"
1720 * @param DOMDocument $doc XML document
1721 * @param array $item Data of the item that is to be posted
1722 * @param array $owner Contact data of the poster
1723 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1725 * @return \DOMElement Entry element with "like"
1726 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1727 * @throws \ImagickException
1729 private static function likeEntry(DOMDocument $doc, array $item, array $owner, $toplevel)
1731 if (($item["id"] != $item["parent"]) && (Strings::normaliseLink($item["author-link"]) != Strings::normaliseLink($owner["url"]))) {
1732 Logger::log("OStatus entry is from author ".$owner["url"]." - not from ".$item["author-link"].". Quitting.", Logger::DEBUG);
1735 $entry = self::entryHeader($doc, $owner, $item, $toplevel);
1737 $verb = ActivityNamespace::ACTIVITY_SCHEMA . "favorite";
1738 self::entryContent($doc, $entry, $item, $owner, "Favorite", $verb, false);
1740 $parent = Item::selectFirst([], ['uri' => $item["thr-parent"], 'uid' => $item["uid"]]);
1741 if (DBA::isResult($parent)) {
1742 $as_object = $doc->createElement("activity:object");
1744 XML::addElement($doc, $as_object, "activity:object-type", self::constructObjecttype($parent));
1746 self::entryContent($doc, $as_object, $parent, $owner, "New entry");
1748 $entry->appendChild($as_object);
1751 self::entryFooter($doc, $entry, $item, $owner);
1757 * @brief Adds the person object element to the XML document
1759 * @param DOMDocument $doc XML document
1760 * @param array $owner Contact data of the poster
1761 * @param array $contact Contact data of the target
1763 * @return object author element
1765 private static function addPersonObject(DOMDocument $doc, array $owner, array $contact)
1767 $object = $doc->createElement("activity:object");
1768 XML::addElement($doc, $object, "activity:object-type", Activity\ObjectType::PERSON);
1770 if ($contact['network'] == Protocol::PHANTOM) {
1771 XML::addElement($doc, $object, "id", $contact['url']);
1775 XML::addElement($doc, $object, "id", $contact["alias"]);
1776 XML::addElement($doc, $object, "title", $contact["nick"]);
1778 $attributes = ["rel" => "alternate", "type" => "text/html", "href" => $contact["url"]];
1779 XML::addElement($doc, $object, "link", "", $attributes);
1783 "type" => "image/jpeg", // To-Do?
1784 "media:width" => 300,
1785 "media:height" => 300,
1786 "href" => $contact["photo"]];
1787 XML::addElement($doc, $object, "link", "", $attributes);
1789 XML::addElement($doc, $object, "poco:preferredUsername", $contact["nick"]);
1790 XML::addElement($doc, $object, "poco:displayName", $contact["name"]);
1792 if (trim($contact["location"]) != "") {
1793 $element = $doc->createElement("poco:address");
1794 XML::addElement($doc, $element, "poco:formatted", $contact["location"]);
1795 $object->appendChild($element);
1802 * @brief Adds a follow/unfollow entry element
1804 * @param DOMDocument $doc XML document
1805 * @param array $item Data of the follow/unfollow message
1806 * @param array $owner Contact data of the poster
1807 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1809 * @return \DOMElement Entry element
1810 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1811 * @throws \ImagickException
1813 private static function followEntry(DOMDocument $doc, array $item, array $owner, $toplevel)
1815 $item["id"] = $item["parent"] = 0;
1816 $item["created"] = $item["edited"] = date("c");
1817 $item["private"] = true;
1819 $contact = Probe::uri($item['follow']);
1821 if ($contact['alias'] == '') {
1822 $contact['alias'] = $contact["url"];
1824 $item['follow'] = $contact['alias'];
1827 $condition = ['uid' => $owner['uid'], 'nurl' => Strings::normaliseLink($contact["url"])];
1828 $user_contact = DBA::selectFirst('contact', ['id'], $condition);
1830 if (DBA::isResult($user_contact)) {
1831 $connect_id = $user_contact['id'];
1836 if ($item['verb'] == Activity::FOLLOW) {
1837 $message = L10n::t('%s is now following %s.');
1838 $title = L10n::t('following');
1839 $action = "subscription";
1841 $message = L10n::t('%s stopped following %s.');
1842 $title = L10n::t('stopped following');
1843 $action = "unfollow";
1846 $item["uri"] = $item['parent-uri'] = $item['thr-parent']
1847 = 'tag:' . DI::baseUrl()->getHostname().
1848 ','.date('Y-m-d').':'.$action.':'.$owner['uid'].
1849 ':person:'.$connect_id.':'.$item['created'];
1851 $item["body"] = sprintf($message, $owner["nick"], $contact["nick"]);
1853 $entry = self::entryHeader($doc, $owner, $item, $toplevel);
1855 self::entryContent($doc, $entry, $item, $owner, $title);
1857 $object = self::addPersonObject($doc, $owner, $contact);
1858 $entry->appendChild($object);
1860 self::entryFooter($doc, $entry, $item, $owner);
1866 * @brief Adds a regular entry element
1868 * @param DOMDocument $doc XML document
1869 * @param array $item Data of the item that is to be posted
1870 * @param array $owner Contact data of the poster
1871 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1872 * @param bool $feed_mode Behave like a regular feed for users if true
1874 * @return \DOMElement Entry element
1875 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1876 * @throws \ImagickException
1878 private static function noteEntry(DOMDocument $doc, array $item, array $owner, $toplevel, $feed_mode)
1880 if (($item["id"] != $item["parent"]) && (Strings::normaliseLink($item["author-link"]) != Strings::normaliseLink($owner["url"]))) {
1881 Logger::log("OStatus entry is from author ".$owner["url"]." - not from ".$item["author-link"].". Quitting.", Logger::DEBUG);
1885 if (!empty($item['title'])) {
1886 $title = BBCode::convert($item['title'], false, 7);
1888 $title = sprintf("New note by %s", $owner["nick"]);
1891 $title = sprintf("New comment by %s", $owner["nick"]);
1894 $entry = self::entryHeader($doc, $owner, $item, $toplevel);
1896 XML::addElement($doc, $entry, "activity:object-type", Activity\ObjectType::NOTE);
1898 self::entryContent($doc, $entry, $item, $owner, $title, '', true, $feed_mode);
1900 self::entryFooter($doc, $entry, $item, $owner, !$feed_mode, $feed_mode);
1906 * @brief Adds a header element to the XML document
1908 * @param DOMDocument $doc XML document
1909 * @param array $owner Contact data of the poster
1910 * @param array $item
1911 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1913 * @return \DOMElement The entry element where the elements are added
1914 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1915 * @throws \ImagickException
1917 private static function entryHeader(DOMDocument $doc, array $owner, array $item, $toplevel)
1920 $entry = $doc->createElement("entry");
1922 if ($owner['account-type'] == User::ACCOUNT_TYPE_COMMUNITY) {
1923 $contact = self::contactEntry($item['author-link'], $owner);
1924 $author = self::addAuthor($doc, $contact, false);
1925 $entry->appendChild($author);
1928 $entry = $doc->createElementNS(ActivityNamespace::ATOM1, "entry");
1930 $entry->setAttribute("xmlns:thr", ActivityNamespace::THREAD);
1931 $entry->setAttribute("xmlns:georss", ActivityNamespace::GEORSS);
1932 $entry->setAttribute("xmlns:activity", ActivityNamespace::ACTIVITY);
1933 $entry->setAttribute("xmlns:media", ActivityNamespace::MEDIA);
1934 $entry->setAttribute("xmlns:poco", ActivityNamespace::POCO);
1935 $entry->setAttribute("xmlns:ostatus", ActivityNamespace::OSTATUS);
1936 $entry->setAttribute("xmlns:statusnet", ActivityNamespace::STATUSNET);
1937 $entry->setAttribute("xmlns:mastodon", ActivityNamespace::MASTODON);
1939 $author = self::addAuthor($doc, $owner);
1940 $entry->appendChild($author);
1947 * @brief Adds elements to the XML document
1949 * @param DOMDocument $doc XML document
1950 * @param \DOMElement $entry Entry element where the content is added
1951 * @param array $item Data of the item that is to be posted
1952 * @param array $owner Contact data of the poster
1953 * @param string $title Title for the post
1954 * @param string $verb The activity verb
1955 * @param bool $complete Add the "status_net" element?
1956 * @param bool $feed_mode Behave like a regular feed for users if true
1958 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1960 private static function entryContent(DOMDocument $doc, \DOMElement $entry, array $item, array $owner, $title, $verb = "", $complete = true, $feed_mode = false)
1963 $verb = self::constructVerb($item);
1966 XML::addElement($doc, $entry, "id", $item["uri"]);
1967 XML::addElement($doc, $entry, "title", html_entity_decode($title, ENT_QUOTES, 'UTF-8'));
1969 $body = self::formatPicturePost($item['body']);
1971 if (!empty($item['title']) && !$feed_mode) {
1972 $body = "[b]".$item['title']."[/b]\n\n".$body;
1975 $body = BBCode::convert($body, false, 7);
1977 XML::addElement($doc, $entry, "content", $body, ["type" => "html"]);
1979 XML::addElement($doc, $entry, "link", "", ["rel" => "alternate", "type" => "text/html",
1980 "href" => DI::baseUrl()."/display/".$item["guid"]]
1983 if (!$feed_mode && $complete && ($item["id"] > 0)) {
1984 XML::addElement($doc, $entry, "status_net", "", ["notice_id" => $item["id"]]);
1988 XML::addElement($doc, $entry, "activity:verb", $verb);
1991 XML::addElement($doc, $entry, "published", DateTimeFormat::utc($item["created"]."+00:00", DateTimeFormat::ATOM));
1992 XML::addElement($doc, $entry, "updated", DateTimeFormat::utc($item["edited"]."+00:00", DateTimeFormat::ATOM));
1996 * @brief Adds the elements at the foot of an entry to the XML document
1998 * @param DOMDocument $doc XML document
1999 * @param object $entry The entry element where the elements are added
2000 * @param array $item Data of the item that is to be posted
2001 * @param array $owner Contact data of the poster
2002 * @param bool $complete default true
2003 * @param bool $feed_mode Behave like a regular feed for users if true
2005 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2007 private static function entryFooter(DOMDocument $doc, $entry, array $item, array $owner, $complete = true, $feed_mode = false)
2011 if (($item['parent'] != $item['id']) || ($item['parent-uri'] !== $item['uri']) || (($item['thr-parent'] !== '') && ($item['thr-parent'] !== $item['uri']))) {
2012 $parent = Item::selectFirst(['guid', 'author-link', 'owner-link'], ['id' => $item["parent"]]);
2013 $parent_item = (($item['thr-parent']) ? $item['thr-parent'] : $item['parent-uri']);
2015 $thrparent = Item::selectFirst(['guid', 'author-link', 'owner-link', 'plink'], ['uid' => $owner["uid"], 'uri' => $parent_item]);
2017 if (DBA::isResult($thrparent)) {
2018 $mentioned[$thrparent["author-link"]] = $thrparent["author-link"];
2019 $mentioned[$thrparent["owner-link"]] = $thrparent["owner-link"];
2020 $parent_plink = $thrparent["plink"];
2022 $mentioned[$parent["author-link"]] = $parent["author-link"];
2023 $mentioned[$parent["owner-link"]] = $parent["owner-link"];
2024 $parent_plink = DI::baseUrl()."/display/".$parent["guid"];
2028 "ref" => $parent_item,
2029 "href" => $parent_plink];
2030 XML::addElement($doc, $entry, "thr:in-reply-to", "", $attributes);
2034 "href" => $parent_plink];
2035 XML::addElement($doc, $entry, "link", "", $attributes);
2038 if (!$feed_mode && (intval($item["parent"]) > 0)) {
2039 $conversation_href = $conversation_uri = str_replace('/objects/', '/context/', $item['parent-uri']);
2041 if (isset($parent_item)) {
2042 $conversation = DBA::selectFirst('conversation', ['conversation-uri', 'conversation-href'], ['item-uri' => $parent_item]);
2043 if (DBA::isResult($conversation)) {
2044 if ($conversation['conversation-uri'] != '') {
2045 $conversation_uri = $conversation['conversation-uri'];
2047 if ($conversation['conversation-href'] != '') {
2048 $conversation_href = $conversation['conversation-href'];
2053 XML::addElement($doc, $entry, "link", "", ["rel" => "ostatus:conversation", "href" => $conversation_href]);
2056 "href" => $conversation_href,
2057 "local_id" => $item["parent"],
2058 "ref" => $conversation_uri];
2060 XML::addElement($doc, $entry, "ostatus:conversation", $conversation_uri, $attributes);
2063 $tags = item::getFeedTags($item);
2066 foreach ($tags as $t) {
2068 $mentioned[$t[1]] = $t[1];
2073 // Make sure that mentions are accepted (GNU Social has problems with mixing HTTP and HTTPS)
2075 foreach ($mentioned as $mention) {
2076 $newmentions[str_replace("http://", "https://", $mention)] = str_replace("http://", "https://", $mention);
2077 $newmentions[str_replace("https://", "http://", $mention)] = str_replace("https://", "http://", $mention);
2079 $mentioned = $newmentions;
2081 foreach ($mentioned as $mention) {
2082 $condition = ['uid' => $owner['uid'], 'nurl' => Strings::normaliseLink($mention)];
2083 $contact = DBA::selectFirst('contact', ['forum', 'prv', 'self', 'contact-type'], $condition);
2084 if ($contact["forum"] || $contact["prv"] || ($owner['contact-type'] == Contact::TYPE_COMMUNITY) ||
2085 ($contact['self'] && ($owner['account-type'] == User::ACCOUNT_TYPE_COMMUNITY))) {
2086 XML::addElement($doc, $entry, "link", "",
2088 "rel" => "mentioned",
2089 "ostatus:object-type" => Activity\ObjectType::GROUP,
2093 XML::addElement($doc, $entry, "link", "",
2095 "rel" => "mentioned",
2096 "ostatus:object-type" => Activity\ObjectType::PERSON,
2102 if ($owner['account-type'] == User::ACCOUNT_TYPE_COMMUNITY) {
2103 XML::addElement($doc, $entry, "link", "", [
2104 "rel" => "mentioned",
2105 "ostatus:object-type" => "http://activitystrea.ms/schema/1.0/group",
2106 "href" => $owner['url']
2110 if (!$item["private"] && !$feed_mode) {
2111 XML::addElement($doc, $entry, "link", "", ["rel" => "ostatus:attention",
2112 "href" => "http://activityschema.org/collection/public"]);
2113 XML::addElement($doc, $entry, "link", "", ["rel" => "mentioned",
2114 "ostatus:object-type" => "http://activitystrea.ms/schema/1.0/collection",
2115 "href" => "http://activityschema.org/collection/public"]);
2116 XML::addElement($doc, $entry, "mastodon:scope", "public");
2120 foreach ($tags as $t) {
2122 XML::addElement($doc, $entry, "category", "", ["term" => $t[2]]);
2127 self::getAttachment($doc, $entry, $item);
2129 if ($complete && ($item["id"] > 0)) {
2130 $app = $item["app"];
2135 $attributes = ["local_id" => $item["id"], "source" => $app];
2137 if (isset($parent["id"])) {
2138 $attributes["repeat_of"] = $parent["id"];
2141 if ($item["coord"] != "") {
2142 XML::addElement($doc, $entry, "georss:point", $item["coord"]);
2145 XML::addElement($doc, $entry, "statusnet:notice_info", "", $attributes);
2150 * Creates the XML feed for a given nickname
2152 * Supported filters:
2153 * - activity (default): all the public posts
2154 * - posts: all the public top-level posts
2155 * - comments: all the public replies
2157 * Updates the provided last_update parameter if the result comes from the
2158 * cache or it is empty
2160 * @brief Creates the XML feed for a given nickname
2162 * @param string $owner_nick Nickname of the feed owner
2163 * @param string $last_update Date of the last update
2164 * @param integer $max_items Number of maximum items to fetch
2165 * @param string $filter Feed items filter (activity, posts or comments)
2166 * @param boolean $nocache Wether to bypass caching
2167 * @param boolean $feed_mode Behave like a regular feed for users if true
2169 * @return string XML feed
2170 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2171 * @throws \ImagickException
2173 public static function feed($owner_nick, &$last_update, $max_items = 300, $filter = 'activity', $nocache = false, $feed_mode = false)
2175 $stamp = microtime(true);
2177 $owner = User::getOwnerDataByNick($owner_nick);
2182 $cachekey = "ostatus:feed:" . $owner_nick . ":" . $filter . ":" . $last_update;
2184 $previous_created = $last_update;
2186 // Don't cache when the last item was posted less then 15 minutes ago (Cache duration)
2187 if ((time() - strtotime($owner['last-item'])) < 15*60) {
2188 $result = DI::cache()->get($cachekey);
2189 if (!$nocache && !is_null($result)) {
2190 Logger::log('Feed duration: ' . number_format(microtime(true) - $stamp, 3) . ' - ' . $owner_nick . ' - ' . $filter . ' - ' . $previous_created . ' (cached)', Logger::DEBUG);
2191 $last_update = $result['last_update'];
2192 return $result['feed'];
2196 if (!strlen($last_update)) {
2197 $last_update = 'now -30 days';
2200 $check_date = DateTimeFormat::utc($last_update);
2201 $authorid = Contact::getIdForURL($owner["url"], 0, true);
2203 $condition = ["`uid` = ? AND `received` > ? AND NOT `deleted`
2204 AND NOT `private` AND `visible` AND `wall` AND `parent-network` IN (?, ?)",
2205 $owner["uid"], $check_date, Protocol::OSTATUS, Protocol::DFRN];
2207 if ($filter === 'comments') {
2208 $condition[0] .= " AND `object-type` = ? ";
2209 $condition[] = Activity\ObjectType::COMMENT;
2212 if ($owner['account-type'] != User::ACCOUNT_TYPE_COMMUNITY) {
2213 $condition[0] .= " AND `contact-id` = ? AND `author-id` = ?";
2214 $condition[] = $owner["id"];
2215 $condition[] = $authorid;
2218 $params = ['order' => ['received' => true], 'limit' => $max_items];
2220 if ($filter === 'posts') {
2221 $ret = Item::selectThread([], $condition, $params);
2223 $ret = Item::select([], $condition, $params);
2226 $items = Item::inArray($ret);
2228 $doc = new DOMDocument('1.0', 'utf-8');
2229 $doc->formatOutput = true;
2231 $root = self::addHeader($doc, $owner, $filter, $feed_mode);
2233 foreach ($items as $item) {
2234 if (Config::get('system', 'ostatus_debug')) {
2235 $item['body'] .= '🍼';
2238 $entry = self::entry($doc, $item, $owner, false, $feed_mode);
2239 $root->appendChild($entry);
2241 if ($last_update < $item['created']) {
2242 $last_update = $item['created'];
2246 $feeddata = trim($doc->saveXML());
2248 $msg = ['feed' => $feeddata, 'last_update' => $last_update];
2249 DI::cache()->set($cachekey, $msg, Cache::QUARTER_HOUR);
2251 Logger::log('Feed duration: ' . number_format(microtime(true) - $stamp, 3) . ' - ' . $owner_nick . ' - ' . $filter . ' - ' . $previous_created, Logger::DEBUG);
2257 * @brief Creates the XML for a salmon message
2259 * @param array $item Data of the item that is to be posted
2260 * @param array $owner Contact data of the poster
2262 * @return string XML for the salmon
2263 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2264 * @throws \ImagickException
2266 public static function salmon(array $item, array $owner)
2268 $doc = new DOMDocument('1.0', 'utf-8');
2269 $doc->formatOutput = true;
2271 if (Config::get('system', 'ostatus_debug')) {
2272 $item['body'] .= '🐟';
2275 $entry = self::entry($doc, $item, $owner, true);
2277 $doc->appendChild($entry);
2279 return trim($doc->saveXML());
2283 * Checks if the given contact url does support OStatus
2285 * @param string $url profile url
2286 * @param boolean $update Update the profile
2288 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2289 * @throws \ImagickException
2291 public static function isSupportedByContactUrl($url, $update = false)
2293 $probe = Probe::uri($url, Protocol::OSTATUS, 0, !$update);
2294 return $probe['network'] == Protocol::OSTATUS;