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;
12 use Friendica\Core\Config;
13 use Friendica\Core\L10n;
14 use Friendica\Core\Logger;
15 use Friendica\Core\Lock;
16 use Friendica\Core\Protocol;
17 use Friendica\Core\System;
18 use Friendica\Database\DBA;
19 use Friendica\Model\Contact;
20 use Friendica\Model\Conversation;
21 use Friendica\Model\GContact;
22 use Friendica\Model\Item;
23 use Friendica\Model\User;
24 use Friendica\Network\Probe;
25 use Friendica\Object\Image;
26 use Friendica\Util\DateTimeFormat;
27 use Friendica\Util\Network;
28 use Friendica\Util\Proxy as ProxyUtils;
29 use Friendica\Util\Strings;
30 use Friendica\Util\XML;
32 require_once 'include/dba.php';
33 require_once 'include/items.php';
34 require_once 'mod/share.php';
35 require_once 'include/enotify.php';
36 require_once 'include/api.php';
39 * @brief This class contain functions for the OStatus protocol
43 private static $itemlist;
44 private static $conv_list = [];
47 * @brief Fetches author data
49 * @param object $xpath The xpath object
50 * @param object $context The xml context of the author details
51 * @param array $importer user record of the importing user
52 * @param array $contact Called by reference, will contain the fetched contact
53 * @param bool $onlyfetch Only fetch the header without updating the contact entries
55 * @return array Array of author related entries for the item
57 private static function fetchAuthor(DOMXPath $xpath, $context, array $importer, array &$contact = null, $onlyfetch)
60 $author["author-link"] = XML::getFirstNodeValue($xpath, 'atom:author/atom:uri/text()', $context);
61 $author["author-name"] = XML::getFirstNodeValue($xpath, 'atom:author/atom:name/text()', $context);
62 $addr = XML::getFirstNodeValue($xpath, 'atom:author/atom:email/text()', $context);
64 $aliaslink = $author["author-link"];
66 $alternate_item = $xpath->query("atom:author/atom:link[@rel='alternate']", $context)->item(0);
67 if (is_object($alternate_item)) {
68 foreach ($alternate_item->attributes as $attributes) {
69 if (($attributes->name == "href") && ($attributes->textContent != "")) {
70 $author["author-link"] = $attributes->textContent;
74 $author["author-id"] = Contact::getIdForURL($author["author-link"]);
76 $author["contact-id"] = $contact["id"];
81 This here would be better, but we would get problems with contacts from the statusnet addon
82 This is kept here as a reminder for the future
84 $cid = Contact::getIdForURL($author["author-link"], $importer["uid"]);
86 $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
89 if ($aliaslink != '') {
90 $condition = ["`uid` = ? AND `alias` = ? AND `network` != ? AND `rel` IN (?, ?)",
91 $importer["uid"], $aliaslink, Protocol::STATUSNET,
92 Contact::SHARING, Contact::FRIEND];
93 $contact = DBA::selectFirst('contact', [], $condition);
96 if (!DBA::isResult($contact) && $author["author-link"] != '') {
97 if ($aliaslink == "") {
98 $aliaslink = $author["author-link"];
101 $condition = ["`uid` = ? AND `nurl` IN (?, ?) AND `network` != ? AND `rel` IN (?, ?)",
102 $importer["uid"], Strings::normaliseLink($author["author-link"]), Strings::normaliseLink($aliaslink),
103 Protocol::STATUSNET, Contact::SHARING, Contact::FRIEND];
104 $contact = DBA::selectFirst('contact', [], $condition);
107 if (!DBA::isResult($contact) && ($addr != '')) {
108 $condition = ["`uid` = ? AND `addr` = ? AND `network` != ? AND `rel` IN (?, ?)",
109 $importer["uid"], $addr, Protocol::STATUSNET,
110 Contact::SHARING, Contact::FRIEND];
111 $contact = DBA::selectFirst('contact', [], $condition);
114 if (DBA::isResult($contact)) {
115 if ($contact['blocked']) {
118 $author["contact-id"] = $contact["id"];
122 $avatars = $xpath->query("atom:author/atom:link[@rel='avatar']", $context);
123 foreach ($avatars as $avatar) {
126 foreach ($avatar->attributes as $attributes) {
127 if ($attributes->name == "href") {
128 $href = $attributes->textContent;
130 if ($attributes->name == "width") {
131 $width = $attributes->textContent;
135 $avatarlist[$width] = $href;
138 if (count($avatarlist) > 0) {
140 $author["author-avatar"] = Probe::fixAvatar(current($avatarlist), $author["author-link"]);
143 $displayname = XML::getFirstNodeValue($xpath, 'atom:author/poco:displayName/text()', $context);
144 if ($displayname != "") {
145 $author["author-name"] = $displayname;
148 $author["owner-id"] = $author["author-id"];
150 // Only update the contacts if it is an OStatus contact
151 if (DBA::isResult($contact) && ($contact['id'] > 0) && !$onlyfetch && ($contact["network"] == Protocol::OSTATUS)) {
153 // Update contact data
155 unset($current['name-date']);
157 // This query doesn't seem to work
158 // $value = $xpath->query("atom:link[@rel='salmon']", $context)->item(0)->nodeValue;
160 // $contact["notify"] = $value;
162 // This query doesn't seem to work as well - I hate these queries
163 // $value = $xpath->query("atom:link[@rel='self' and @type='application/atom+xml']", $context)->item(0)->nodeValue;
165 // $contact["poll"] = $value;
167 $contact['url'] = $author["author-link"];
168 $contact['nurl'] = Strings::normaliseLink($contact['url']);
170 $value = XML::getFirstNodeValue($xpath, 'atom:author/atom:uri/text()', $context);
172 $contact["alias"] = $value;
175 $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:displayName/text()', $context);
177 $contact["name"] = $value;
180 $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:preferredUsername/text()', $context);
182 $contact["nick"] = $value;
185 $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:note/text()', $context);
187 $contact["about"] = HTML::toBBCode($value);
190 $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:address/poco:formatted/text()', $context);
192 $contact["location"] = $value;
195 $contact['name-date'] = DateTimeFormat::utcNow();
197 DBA::update('contact', $contact, ['id' => $contact["id"]], $current);
199 if (!empty($author["author-avatar"]) && ($author["author-avatar"] != $current['avatar'])) {
200 Logger::log("Update profile picture for contact ".$contact["id"], Logger::DEBUG);
201 Contact::updateAvatar($author["author-avatar"], $importer["uid"], $contact["id"]);
204 // Ensure that we are having this contact (with uid=0)
205 $cid = Contact::getIdForURL($aliaslink, 0, true);
208 $fields = ['url', 'nurl', 'name', 'nick', 'alias', 'about', 'location'];
209 $old_contact = DBA::selectFirst('contact', $fields, ['id' => $cid]);
211 // Update it with the current values
212 $fields = ['url' => $author["author-link"], 'name' => $contact["name"],
213 'nurl' => Strings::normaliseLink($author["author-link"]),
214 'nick' => $contact["nick"], 'alias' => $contact["alias"],
215 'about' => $contact["about"], 'location' => $contact["location"],
216 'success_update' => DateTimeFormat::utcNow(), 'last-update' => DateTimeFormat::utcNow()];
218 DBA::update('contact', $fields, ['id' => $cid], $old_contact);
221 if (!empty($author["author-avatar"])) {
222 Contact::updateAvatar($author["author-avatar"], 0, $cid);
226 $contact["generation"] = 2;
227 $contact["hide"] = false; // OStatus contacts are never hidden
228 if (!empty($author["author-avatar"])) {
229 $contact["photo"] = $author["author-avatar"];
231 $gcid = GContact::update($contact);
233 GContact::link($gcid, $contact["uid"], $contact["id"]);
234 } elseif ($contact["network"] != Protocol::DFRN) {
242 * @brief Fetches author data from a given XML string
244 * @param string $xml The XML
245 * @param array $importer user record of the importing user
247 * @return array Array of author related entries for the item
249 public static function salmonAuthor($xml, array $importer)
255 $doc = new DOMDocument();
256 @$doc->loadXML($xml);
258 $xpath = new DOMXPath($doc);
259 $xpath->registerNamespace('atom', NAMESPACE_ATOM1);
260 $xpath->registerNamespace('thr', NAMESPACE_THREAD);
261 $xpath->registerNamespace('georss', NAMESPACE_GEORSS);
262 $xpath->registerNamespace('activity', NAMESPACE_ACTIVITY);
263 $xpath->registerNamespace('media', NAMESPACE_MEDIA);
264 $xpath->registerNamespace('poco', NAMESPACE_POCO);
265 $xpath->registerNamespace('ostatus', NAMESPACE_OSTATUS);
266 $xpath->registerNamespace('statusnet', NAMESPACE_STATUSNET);
268 $contact = ["id" => 0];
270 // Fetch the first author
271 $authordata = $xpath->query('//author')->item(0);
272 $author = self::fetchAuthor($xpath, $authordata, $importer, $contact, true);
277 * @brief Read attributes from element
279 * @param object $element Element object
281 * @return array attributes
283 private static function readAttributes($element)
287 foreach ($element->attributes as $attributes) {
288 $attribute[$attributes->name] = $attributes->textContent;
295 * @brief Imports an XML string containing OStatus elements
297 * @param string $xml The XML
298 * @param array $importer user record of the importing user
299 * @param array $contact contact
300 * @param string $hub Called by reference, returns the fetched hub data
303 public static function import($xml, array $importer, array &$contact = null, &$hub)
305 self::process($xml, $importer, $contact, $hub);
309 * @brief Internal feed processing
311 * @param string $xml The XML
312 * @param array $importer user record of the importing user
313 * @param array $contact contact
314 * @param string $hub Called by reference, returns the fetched hub data
315 * @param boolean $stored Is the post fresh imported or from the database?
316 * @param boolean $initialize Is it the leading post so that data has to be initialized?
318 * @return boolean Could the XML be processed?
320 private static function process($xml, array $importer, array &$contact = null, &$hub, $stored = false, $initialize = true)
323 self::$itemlist = [];
324 self::$conv_list = [];
327 Logger::log('Import OStatus message for user ' . $importer['uid'], Logger::DEBUG);
332 $doc = new DOMDocument();
333 @$doc->loadXML($xml);
335 $xpath = new DOMXPath($doc);
336 $xpath->registerNamespace('atom', NAMESPACE_ATOM1);
337 $xpath->registerNamespace('thr', NAMESPACE_THREAD);
338 $xpath->registerNamespace('georss', NAMESPACE_GEORSS);
339 $xpath->registerNamespace('activity', NAMESPACE_ACTIVITY);
340 $xpath->registerNamespace('media', NAMESPACE_MEDIA);
341 $xpath->registerNamespace('poco', NAMESPACE_POCO);
342 $xpath->registerNamespace('ostatus', NAMESPACE_OSTATUS);
343 $xpath->registerNamespace('statusnet', NAMESPACE_STATUSNET);
346 $hub_items = $xpath->query("/atom:feed/atom:link[@rel='hub']")->item(0);
347 if (is_object($hub_items)) {
348 $hub_attributes = $hub_items->attributes;
349 if (is_object($hub_attributes)) {
350 foreach ($hub_attributes as $hub_attribute) {
351 if ($hub_attribute->name == "href") {
352 $hub = $hub_attribute->textContent;
353 Logger::log("Found hub ".$hub, Logger::DEBUG);
360 $header["uid"] = $importer["uid"];
361 $header["network"] = Protocol::OSTATUS;
363 $header["origin"] = 0;
364 $header["gravity"] = GRAVITY_COMMENT;
366 if (!is_object($doc->firstChild) || empty($doc->firstChild->tagName)) {
370 $first_child = $doc->firstChild->tagName;
372 if ($first_child == "feed") {
373 $entries = $xpath->query('/atom:feed/atom:entry');
375 $entries = $xpath->query('/atom:entry');
378 if ($entries->length == 1) {
379 // We reformat the XML to make it better readable
380 $doc2 = new DOMDocument();
381 $doc2->loadXML($xml);
382 $doc2->preserveWhiteSpace = false;
383 $doc2->formatOutput = true;
384 $xml2 = $doc2->saveXML();
386 $header["protocol"] = Conversation::PARCEL_SALMON;
387 $header["source"] = $xml2;
388 } elseif (!$initialize) {
392 // Fetch the first author
393 $authordata = $xpath->query('//author')->item(0);
394 $author = self::fetchAuthor($xpath, $authordata, $importer, $contact, $stored);
396 $entry = $xpath->query('/atom:entry');
398 // Reverse the order of the entries
401 foreach ($entries as $entry) {
402 $entrylist[] = $entry;
405 foreach (array_reverse($entrylist) as $entry) {
407 $authorelement = $xpath->query('/atom:entry/atom:author', $entry);
409 if ($authorelement->length == 0) {
410 $authorelement = $xpath->query('atom:author', $entry);
413 if ($authorelement->length > 0) {
414 $author = self::fetchAuthor($xpath, $entry, $importer, $contact, $stored);
417 $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:preferredUsername/text()', $entry);
421 $nickname = $author["author-name"];
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"], [NAMESPACE_OSTATUS."/unfavorite", 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, $nickname);
467 if ($item["verb"] == NAMESPACE_OSTATUS."/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_OBJ_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 = !empty(self::$itemlist[0]['contact-id']);
495 // If not, then it depends on this setting
496 $valid = !Config::get('system', 'ostatus_full_threads');
498 Logger::log("Item with uri ".self::$itemlist[0]['uri']." will be imported due to the system settings.", Logger::DEBUG);
501 Logger::log("Item with uri ".self::$itemlist[0]['uri']." belongs to a contact (".self::$itemlist[0]['contact-id']."). It will be imported.", Logger::DEBUG);
504 // Never post a thread when the only interaction by our contact was a like
506 $verbs = [ACTIVITY_POST, ACTIVITY_SHARE];
507 foreach (self::$itemlist as $item) {
508 if (!empty($item['contact-id']) && in_array($item['verb'], $verbs)) {
513 Logger::log("Item with uri ".self::$itemlist[0]['uri']." will be imported since the thread contains posts or shares.", Logger::DEBUG);
517 // But we will only import complete threads
518 $valid = Item::exists(['uid' => $importer["uid"], 'uri' => self::$itemlist[0]['parent-uri']]);
520 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);
525 $default_contact = 0;
526 $key = count(self::$itemlist);
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 (Lock::acquire('ostatus_process_item_insert')) {
543 $ret = Item::insert($item);
544 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
562 * @param array $item item
565 private static function deleteNotice(array $item)
567 $condition = ['uid' => $item['uid'], 'author-id' => $item['author-id'], 'uri' => $item['uri']];
568 if (!Item::exists($condition)) {
569 Logger::log('Item from '.$item['author-link'].' with uri '.$item['uri'].' for user '.$item['uid']." wasn't found. We don't delete it.");
573 Item::delete($condition);
575 Logger::log('Deleted item with uri '.$item['uri'].' for user '.$item['uid']);
579 * @brief Processes the XML for a post
581 * @param object $xpath The xpath object
582 * @param object $entry The xml entry that is processed
583 * @param array $item The item array
584 * @param array $importer user record of the importing user
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_OBJ_BOOKMARK) || ($item["object-type"] == ACTIVITY_OBJ_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_OBJ_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["parent-uri"] = $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") {
638 $term = $attributes->textContent;
639 if (!empty($item["tag"])) {
645 $item["tag"] .= "#[url=".System::baseUrl()."/search?tag=".$term."]".$term."[/url]";
654 $links = $xpath->query('atom:link', $entry);
656 $link_data = self::processLinks($links, $item);
657 $self = $link_data['self'];
658 $add_body = $link_data['add_body'];
663 $notice_info = $xpath->query('statusnet:notice_info', $entry);
664 if ($notice_info && ($notice_info->length > 0)) {
665 foreach ($notice_info->item(0)->attributes as $attributes) {
666 if ($attributes->name == "source") {
667 $item["app"] = strip_tags($attributes->textContent);
669 if ($attributes->name == "repeat_of") {
670 $repeat_of = $attributes->textContent;
674 // Is it a repeated post?
675 if (($repeat_of != "") || ($item["verb"] == ACTIVITY_SHARE)) {
676 $link_data = self::processRepeatedItem($xpath, $entry, $item, $importer);
677 if (!empty($link_data['add_body'])) {
678 $add_body .= $link_data['add_body'];
682 $item["body"] .= $add_body;
684 // Only add additional data when there is no picture in the post
685 if (!strstr($item["body"], '[/img]')) {
686 $item["body"] = add_page_info_to_body($item["body"]);
689 // Mastodon Content Warning
690 if (($item["verb"] == ACTIVITY_POST) && $xpath->evaluate('boolean(atom:summary)', $entry)) {
691 $clear_text = XML::getFirstNodeValue($xpath, 'atom:summary/text()', $entry);
692 if (!empty($clear_text)) {
693 $item['content-warning'] = HTML::toBBCode($clear_text);
697 if (($self != '') && empty($item['protocol'])) {
698 self::fetchSelf($self, $item);
701 if (!empty($item["conversation-href"])) {
702 self::fetchConversation($item['conversation-href'], $item['conversation-uri']);
705 if (isset($item["parent-uri"])) {
706 if (!Item::exists(['uid' => $importer["uid"], 'uri' => $item['parent-uri']])) {
707 if ($related != '') {
708 self::fetchRelated($related, $item["parent-uri"], $importer);
711 Logger::log('Reply with URI '.$item["uri"].' already existed for user '.$importer["uid"].'.', Logger::DEBUG);
714 $item["parent-uri"] = $item["uri"];
715 $item["gravity"] = GRAVITY_PARENT;
718 if (($item['author-link'] != '') && !empty($item['protocol'])) {
719 $item = Conversation::insert($item);
722 self::$itemlist[] = $item;
726 * @brief Fetch the conversation for posts
728 * @param string $conversation The link to the conversation
729 * @param string $conversation_uri The conversation in "uri" format
732 private static function fetchConversation($conversation, $conversation_uri)
734 // Ensure that we only store a conversation once in a process
735 if (isset(self::$conv_list[$conversation])) {
739 self::$conv_list[$conversation] = true;
741 $curlResult = Network::curl($conversation, false, $redirects, ['accept_content' => 'application/atom+xml, text/html']);
743 if (!$curlResult->isSuccess()) {
749 if (stristr($curlResult->getHeader(), 'Content-Type: application/atom+xml')) {
750 $xml = $curlResult->getBody();
754 $doc = new DOMDocument();
755 if (!@$doc->loadHTML($curlResult->getBody())) {
758 $xpath = new DOMXPath($doc);
760 $links = $xpath->query('//link');
763 foreach ($links as $link) {
764 $attribute = self::readAttributes($link);
765 if (($attribute['rel'] == 'alternate') && ($attribute['type'] == 'application/atom+xml')) {
766 $file = $attribute['href'];
770 $conversation_atom = Network::curl($attribute['href']);
772 if ($conversation_atom->isSuccess()) {
773 $xml = $conversation_atom->getBody();
783 self::storeConversation($xml, $conversation, $conversation_uri);
787 * @brief Store a feed in several conversation entries
789 * @param string $xml The feed
790 * @param string $conversation conversation
791 * @param string $conversation_uri conversation uri
794 private static function storeConversation($xml, $conversation = '', $conversation_uri = '')
796 $doc = new DOMDocument();
797 @$doc->loadXML($xml);
799 $xpath = new DOMXPath($doc);
800 $xpath->registerNamespace('atom', NAMESPACE_ATOM1);
801 $xpath->registerNamespace('thr', NAMESPACE_THREAD);
802 $xpath->registerNamespace('ostatus', NAMESPACE_OSTATUS);
804 $entries = $xpath->query('/atom:feed/atom:entry');
806 // Now store the entries
807 foreach ($entries as $entry) {
808 $doc2 = new DOMDocument();
809 $doc2->preserveWhiteSpace = false;
810 $doc2->formatOutput = true;
814 $conv_data['protocol'] = Conversation::PARCEL_SPLIT_CONVERSATION;
815 $conv_data['network'] = Protocol::OSTATUS;
816 $conv_data['uri'] = XML::getFirstNodeValue($xpath, 'atom:id/text()', $entry);
818 $inreplyto = $xpath->query('thr:in-reply-to', $entry);
819 if (is_object($inreplyto->item(0))) {
820 foreach ($inreplyto->item(0)->attributes as $attributes) {
821 if ($attributes->name == "ref") {
822 $conv_data['reply-to-uri'] = $attributes->textContent;
827 $conv_data['conversation-uri'] = XML::getFirstNodeValue($xpath, 'ostatus:conversation/text()', $entry);
829 $conv = $xpath->query('ostatus:conversation', $entry);
830 if (is_object($conv->item(0))) {
831 foreach ($conv->item(0)->attributes as $attributes) {
832 if ($attributes->name == "ref") {
833 $conv_data['conversation-uri'] = $attributes->textContent;
835 if ($attributes->name == "href") {
836 $conv_data['conversation-href'] = $attributes->textContent;
841 if ($conversation != '') {
842 $conv_data['conversation-uri'] = $conversation;
845 if ($conversation_uri != '') {
846 $conv_data['conversation-uri'] = $conversation_uri;
849 $entry = $doc2->importNode($entry, true);
851 $doc2->appendChild($entry);
853 $conv_data['source'] = $doc2->saveXML();
855 $condition = ['item-uri' => $conv_data['uri'],'protocol' => Conversation::PARCEL_FEED];
856 if (DBA::exists('conversation', $condition)) {
857 Logger::log('Delete deprecated entry for URI '.$conv_data['uri'], Logger::DEBUG);
858 DBA::delete('conversation', ['item-uri' => $conv_data['uri']]);
861 Logger::log('Store conversation data for uri '.$conv_data['uri'], Logger::DEBUG);
862 Conversation::insert($conv_data);
867 * @brief Fetch the own post so that it can be stored later
869 * We want to store the original data for later processing.
870 * This function is meant for cases where we process a feed with multiple entries.
871 * In that case we need to fetch the single posts here.
873 * @param string $self The link to the self item
874 * @param array $item The item array
877 private static function fetchSelf($self, array &$item)
879 $condition = ['`item-uri` = ? AND `protocol` IN (?, ?)', $self, Conversation::PARCEL_DFRN, Conversation::PARCEL_SALMON];
880 if (DBA::exists('conversation', $condition)) {
881 Logger::log('Conversation '.$item['uri'].' is already stored.', Logger::DEBUG);
885 $curlResult = Network::curl($self);
887 if (!$curlResult->isSuccess()) {
891 // We reformat the XML to make it better readable
892 $doc = new DOMDocument();
893 $doc->loadXML($curlResult->getBody());
894 $doc->preserveWhiteSpace = false;
895 $doc->formatOutput = true;
896 $xml = $doc->saveXML();
898 $item["protocol"] = Conversation::PARCEL_SALMON;
899 $item["source"] = $xml;
901 Logger::log('Conversation '.$item['uri'].' is now fetched.', Logger::DEBUG);
905 * @brief Fetch related posts and processes them
907 * @param string $related The link to the related item
908 * @param string $related_uri The related item in "uri" format
909 * @param array $importer user record of the importing user
912 private static function fetchRelated($related, $related_uri, $importer)
914 $condition = ['`item-uri` = ? AND `protocol` IN (?, ?)', $related_uri, Conversation::PARCEL_DFRN, Conversation::PARCEL_SALMON];
915 $conversation = DBA::selectFirst('conversation', ['source', 'protocol'], $condition);
916 if (DBA::isResult($conversation)) {
918 $xml = $conversation['source'];
919 if (self::process($xml, $importer, $contact, $hub, $stored, false)) {
920 Logger::log('Got valid cached XML for URI '.$related_uri, Logger::DEBUG);
923 if ($conversation['protocol'] == Conversation::PARCEL_SALMON) {
924 Logger::log('Delete invalid cached XML for URI '.$related_uri, Logger::DEBUG);
925 DBA::delete('conversation', ['item-uri' => $related_uri]);
930 $curlResult = Network::curl($related, false, $redirects, ['accept_content' => 'application/atom+xml, text/html']);
932 if (!$curlResult->isSuccess()) {
938 if (stristr($curlResult->getHeader(), 'Content-Type: application/atom+xml')) {
939 Logger::log('Directly fetched XML for URI ' . $related_uri, Logger::DEBUG);
940 $xml = $curlResult->getBody();
944 $doc = new DOMDocument();
945 if (!@$doc->loadHTML($curlResult->getBody())) {
948 $xpath = new DOMXPath($doc);
952 $links = $xpath->query('//link');
954 foreach ($links as $link) {
955 $attribute = self::readAttributes($link);
956 if (($attribute['rel'] == 'alternate') && ($attribute['type'] == 'application/atom+xml')) {
957 $atom_file = $attribute['href'];
960 if ($atom_file != '') {
961 $curlResult = Network::curl($atom_file);
963 if ($curlResult->isSuccess()) {
964 Logger::log('Fetched XML for URI ' . $related_uri, Logger::DEBUG);
965 $xml = $curlResult->getBody();
971 // Workaround for older GNU Social servers
972 if (($xml == '') && strstr($related, '/notice/')) {
973 $curlResult = Network::curl(str_replace('/notice/', '/api/statuses/show/', $related).'.atom');
975 if ($curlResult->isSuccess()) {
976 Logger::log('GNU Social workaround to fetch XML for URI ' . $related_uri, Logger::DEBUG);
977 $xml = $curlResult->getBody();
981 // Even more worse workaround for GNU Social ;-)
983 $related_guess = OStatus::convertHref($related_uri);
984 $curlResult = Network::curl(str_replace('/notice/', '/api/statuses/show/', $related_guess).'.atom');
986 if ($curlResult->isSuccess()) {
987 Logger::log('GNU Social workaround 2 to fetch XML for URI ' . $related_uri, Logger::DEBUG);
988 $xml = $curlResult->getBody();
992 // Finally we take the data that we fetched from "ostatus:conversation"
994 $condition = ['item-uri' => $related_uri, 'protocol' => Conversation::PARCEL_SPLIT_CONVERSATION];
995 $conversation = DBA::selectFirst('conversation', ['source'], $condition);
996 if (DBA::isResult($conversation)) {
998 Logger::log('Got cached XML from conversation for URI '.$related_uri, Logger::DEBUG);
999 $xml = $conversation['source'];
1004 self::process($xml, $importer, $contact, $hub, $stored, false);
1006 Logger::log("XML couldn't be fetched for URI: ".$related_uri." - href: ".$related, Logger::DEBUG);
1012 * @brief Processes the XML for a repeated post
1014 * @param object $xpath The xpath object
1015 * @param object $entry The xml entry that is processed
1016 * @param array $item The item array
1017 * @param array $importer user record of the importing user
1019 * @return array with data from links
1021 private static function processRepeatedItem(DOMXPath $xpath, $entry, array &$item, array $importer)
1023 $activityobject = $xpath->query('activity:object', $entry)->item(0);
1025 if (!is_object($activityobject)) {
1031 $orig_uri = XML::getFirstNodeValue($xpath, 'atom:id/text()', $activityobject);
1033 $links = $xpath->query("atom:link", $activityobject);
1035 $link_data = self::processLinks($links, $item);
1038 $orig_body = XML::getFirstNodeValue($xpath, 'atom:content/text()', $activityobject);
1039 $orig_created = XML::getFirstNodeValue($xpath, 'atom:published/text()', $activityobject);
1040 $orig_edited = XML::getFirstNodeValue($xpath, 'atom:updated/text()', $activityobject);
1042 $orig_author = self::fetchAuthor($xpath, $activityobject, $importer, $dummy, false);
1044 $item["author-name"] = $orig_author["author-name"];
1045 $item["author-link"] = $orig_author["author-link"];
1046 $item["author-id"] = $orig_author["author-id"];
1048 $item["body"] = HTML::toBBCode($orig_body);
1049 $item["created"] = $orig_created;
1050 $item["edited"] = $orig_edited;
1052 $item["uri"] = $orig_uri;
1054 $item["verb"] = XML::getFirstNodeValue($xpath, 'activity:verb/text()', $activityobject);
1056 $item["object-type"] = XML::getFirstNodeValue($xpath, 'activity:object-type/text()', $activityobject);
1058 // Mastodon Content Warning
1059 if (($item["verb"] == ACTIVITY_POST) && $xpath->evaluate('boolean(atom:summary)', $activityobject)) {
1060 $clear_text = XML::getFirstNodeValue($xpath, 'atom:summary/text()', $activityobject);
1061 if (!empty($clear_text)) {
1062 $item['content-warning'] = HTML::toBBCode($clear_text);
1066 $inreplyto = $xpath->query('thr:in-reply-to', $activityobject);
1067 if (is_object($inreplyto->item(0))) {
1068 foreach ($inreplyto->item(0)->attributes as $attributes) {
1069 if ($attributes->name == "ref") {
1070 $item["parent-uri"] = $attributes->textContent;
1079 * @brief Processes links in the XML
1081 * @param object $links The xml data that contain links
1082 * @param array $item The item array
1084 * @return array with data from the links
1086 private static function processLinks($links, array &$item)
1088 $link_data = ['add_body' => '', 'self' => ''];
1090 foreach ($links as $link) {
1091 $attribute = self::readAttributes($link);
1093 if (!empty($attribute['rel']) && !empty($attribute['href'])) {
1094 switch ($attribute['rel']) {
1096 $item["plink"] = $attribute['href'];
1097 if (($item["object-type"] == ACTIVITY_OBJ_QUESTION)
1098 || ($item["object-type"] == ACTIVITY_OBJ_EVENT)
1100 $item["body"] .= add_page_info($attribute['href']);
1103 case "ostatus:conversation":
1104 $link_data['conversation'] = $attribute['href'];
1105 $item['conversation-href'] = $link_data['conversation'];
1106 if (!isset($item['conversation-uri'])) {
1107 $item['conversation-uri'] = $item['conversation-href'];
1111 $filetype = strtolower(substr($attribute['type'], 0, strpos($attribute['type'], '/')));
1112 if ($filetype == 'image') {
1113 $link_data['add_body'] .= "\n[img]".$attribute['href'].'[/img]';
1115 if (!empty($item["attach"])) {
1116 $item["attach"] .= ',';
1118 $item["attach"] = '';
1120 if (!isset($attribute['length'])) {
1121 $attribute['length'] = "0";
1123 $item["attach"] .= '[attach]href="'.$attribute['href'].'" length="'.$attribute['length'].'" type="'.$attribute['type'].'" title="'.defaults($attribute, 'title', '').'"[/attach]';
1127 if ($item["object-type"] != ACTIVITY_OBJ_BOOKMARK) {
1128 if (!isset($item["parent-uri"])) {
1129 $item["parent-uri"] = $attribute['href'];
1131 $link_data['related'] = $attribute['href'];
1133 $item["body"] .= add_page_info($attribute['href']);
1137 if (empty($item["plink"])) {
1138 $item["plink"] = $attribute['href'];
1140 $link_data['self'] = $attribute['href'];
1149 * @brief Create an url out of an uri
1151 * @param string $href URI in the format "parameter1:parameter1:..."
1153 * @return string URL in the format http(s)://....
1155 public static function convertHref($href)
1157 $elements = explode(":", $href);
1159 if ((count($elements) <= 2) || ($elements[0] != "tag")) {
1163 $server = explode(",", $elements[1]);
1164 $conversation = explode("=", $elements[2]);
1166 if ((count($elements) == 4) && ($elements[2] == "post")) {
1167 return "http://".$server[0]."/notice/".$elements[3];
1170 if ((count($conversation) != 2) || ($conversation[1] =="")) {
1173 if ($elements[3] == "objectType=thread") {
1174 return "http://".$server[0]."/conversation/".$conversation[1];
1176 return "http://".$server[0]."/notice/".$conversation[1];
1182 * @brief Checks if the current post is a reshare
1184 * @param array $item The item array of thw post
1186 * @return string The guid if the post is a reshare
1188 private static function getResharedGuid(array $item)
1190 $body = trim($item["body"]);
1192 // Skip if it isn't a pure repeated messages
1193 // Does it start with a share?
1194 if (strpos($body, "[share") > 0) {
1198 // Does it end with a share?
1199 if (strlen($body) > (strrpos($body, "[/share]") + 8)) {
1203 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "$1", $body);
1204 // Skip if there is no shared message in there
1205 if ($body == $attributes) {
1210 preg_match("/guid='(.*?)'/ism", $attributes, $matches);
1211 if (!empty($matches[1])) {
1212 $guid = $matches[1];
1215 preg_match('/guid="(.*?)"/ism', $attributes, $matches);
1216 if (!empty($matches[1])) {
1217 $guid = $matches[1];
1224 * @brief Cleans the body of a post if it contains picture links
1226 * @param string $body The body
1228 * @return string The cleaned body
1230 private static function formatPicturePost($body)
1232 $siteinfo = BBCode::getAttachedData($body);
1234 if (($siteinfo["type"] == "photo")) {
1235 if (isset($siteinfo["preview"])) {
1236 $preview = $siteinfo["preview"];
1238 $preview = $siteinfo["image"];
1241 // Is it a remote picture? Then make a smaller preview here
1242 $preview = ProxyUtils::proxifyUrl($preview, false, ProxyUtils::SIZE_SMALL);
1244 // Is it a local picture? Then make it smaller here
1245 $preview = str_replace(["-0.jpg", "-0.png"], ["-2.jpg", "-2.png"], $preview);
1246 $preview = str_replace(["-1.jpg", "-1.png"], ["-2.jpg", "-2.png"], $preview);
1248 if (isset($siteinfo["url"])) {
1249 $url = $siteinfo["url"];
1251 $url = $siteinfo["image"];
1254 $body = trim($siteinfo["text"])." [url]".$url."[/url]\n[img]".$preview."[/img]";
1261 * @brief Adds the header elements to the XML document
1263 * @param object $doc XML document
1264 * @param array $owner Contact data of the poster
1265 * @param string $filter The related feed filter (activity, posts or comments)
1266 * @param bool $feed_mode Behave like a regular feed for users if true
1268 * @return object header root element
1270 private static function addHeader(DOMDocument $doc, array $owner, $filter, $feed_mode = false)
1274 $root = $doc->createElementNS(NAMESPACE_ATOM1, 'feed');
1275 $doc->appendChild($root);
1277 $root->setAttribute("xmlns:thr", NAMESPACE_THREAD);
1278 $root->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
1279 $root->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
1280 $root->setAttribute("xmlns:media", NAMESPACE_MEDIA);
1281 $root->setAttribute("xmlns:poco", NAMESPACE_POCO);
1282 $root->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
1283 $root->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
1284 $root->setAttribute("xmlns:mastodon", NAMESPACE_MASTODON);
1287 $selfUri = '/feed/' . $owner["nick"] . '/';
1290 $title = L10n::t('%s\'s timeline', $owner['name']);
1291 $selfUri .= $filter;
1294 $title = L10n::t('%s\'s posts', $owner['name']);
1297 $title = L10n::t('%s\'s comments', $owner['name']);
1298 $selfUri .= $filter;
1302 $attributes = ["uri" => "https://friendi.ca", "version" => FRIENDICA_VERSION . "-" . DB_UPDATE_VERSION];
1303 XML::addElement($doc, $root, "generator", FRIENDICA_PLATFORM, $attributes);
1304 XML::addElement($doc, $root, "id", System::baseUrl() . "/profile/" . $owner["nick"]);
1305 XML::addElement($doc, $root, "title", $title);
1306 XML::addElement($doc, $root, "subtitle", sprintf("Updates from %s on %s", $owner["name"], Config::get('config', 'sitename')));
1307 XML::addElement($doc, $root, "logo", $owner["photo"]);
1308 XML::addElement($doc, $root, "updated", DateTimeFormat::utcNow(DateTimeFormat::ATOM));
1310 $author = self::addAuthor($doc, $owner);
1311 $root->appendChild($author);
1313 $attributes = ["href" => $owner["url"], "rel" => "alternate", "type" => "text/html"];
1314 XML::addElement($doc, $root, "link", "", $attributes);
1316 /// @TODO We have to find out what this is
1317 /// $attributes = array("href" => System::baseUrl()."/sup",
1318 /// "rel" => "http://api.friendfeed.com/2008/03#sup",
1319 /// "type" => "application/json");
1320 /// XML::addElement($doc, $root, "link", "", $attributes);
1322 self::hublinks($doc, $root, $owner["nick"]);
1324 $attributes = ["href" => System::baseUrl() . "/salmon/" . $owner["nick"], "rel" => "salmon"];
1325 XML::addElement($doc, $root, "link", "", $attributes);
1327 $attributes = ["href" => System::baseUrl() . "/salmon/" . $owner["nick"], "rel" => "http://salmon-protocol.org/ns/salmon-replies"];
1328 XML::addElement($doc, $root, "link", "", $attributes);
1330 $attributes = ["href" => System::baseUrl() . "/salmon/" . $owner["nick"], "rel" => "http://salmon-protocol.org/ns/salmon-mention"];
1331 XML::addElement($doc, $root, "link", "", $attributes);
1334 $selfUri = "/dfrn_poll/" . $owner["nick"];
1336 $attributes = ["href" => System::baseUrl() . $selfUri, "rel" => "self", "type" => "application/atom+xml"];
1337 XML::addElement($doc, $root, "link", "", $attributes);
1339 if ($owner['account-type'] == Contact::ACCOUNT_TYPE_COMMUNITY) {
1340 $condition = ['uid' => $owner['uid'], 'self' => false, 'pending' => false,
1341 'archive' => false, 'hidden' => false, 'blocked' => false];
1342 $members = DBA::count('contact', $condition);
1343 XML::addElement($doc, $root, "statusnet:group_info", "", ["member_count" => $members]);
1350 * @brief Add the link to the push hubs to the XML document
1352 * @param object $doc XML document
1353 * @param object $root XML root element where the hub links are added
1354 * @param object $nick nick
1357 public static function hublinks(DOMDocument $doc, $root, $nick)
1359 $h = System::baseUrl() . '/pubsubhubbub/'.$nick;
1360 XML::addElement($doc, $root, "link", "", ["href" => $h, "rel" => "hub"]);
1364 * @brief Adds attachment data to the XML document
1366 * @param object $doc XML document
1367 * @param object $root XML root element where the hub links are added
1368 * @param array $item Data of the item that is to be posted
1371 private static function getAttachment(DOMDocument $doc, $root, $item)
1374 $siteinfo = BBCode::getAttachedData($item["body"]);
1376 switch ($siteinfo["type"]) {
1378 if (!empty($siteinfo["image"])) {
1379 $imgdata = Image::getInfoFromURL($siteinfo["image"]);
1381 $attributes = ["rel" => "enclosure",
1382 "href" => $siteinfo["image"],
1383 "type" => $imgdata["mime"],
1384 "length" => intval($imgdata["size"])];
1385 XML::addElement($doc, $root, "link", "", $attributes);
1390 $attributes = ["rel" => "enclosure",
1391 "href" => $siteinfo["url"],
1392 "type" => "text/html; charset=UTF-8",
1394 "title" => defaults($siteinfo, "title", $siteinfo["url"])];
1395 XML::addElement($doc, $root, "link", "", $attributes);
1401 if (!Config::get('system', 'ostatus_not_attach_preview') && ($siteinfo["type"] != "photo") && isset($siteinfo["image"])) {
1402 $imgdata = Image::getInfoFromURL($siteinfo["image"]);
1404 $attributes = ["rel" => "enclosure",
1405 "href" => $siteinfo["image"],
1406 "type" => $imgdata["mime"],
1407 "length" => intval($imgdata["size"])];
1409 XML::addElement($doc, $root, "link", "", $attributes);
1413 $arr = explode('[/attach],', $item['attach']);
1415 foreach ($arr as $r) {
1417 $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"|', $r, $matches);
1419 $attributes = ["rel" => "enclosure",
1420 "href" => $matches[1],
1421 "type" => $matches[3]];
1423 if (intval($matches[2])) {
1424 $attributes["length"] = intval($matches[2]);
1426 if (trim($matches[4]) != "") {
1427 $attributes["title"] = trim($matches[4]);
1429 XML::addElement($doc, $root, "link", "", $attributes);
1436 * @brief Adds the author element to the XML document
1438 * @param object $doc XML document
1439 * @param array $owner Contact data of the poster
1440 * @param bool $show_profile Whether to show profile
1442 * @return object author element
1444 private static function addAuthor(DOMDocument $doc, array $owner, $show_profile = true)
1446 $profile = DBA::selectFirst('profile', ['homepage', 'publish'], ['uid' => $owner['uid'], 'is-default' => true]);
1447 $author = $doc->createElement("author");
1448 XML::addElement($doc, $author, "id", $owner["url"]);
1449 if ($owner['account-type'] == Contact::ACCOUNT_TYPE_COMMUNITY) {
1450 XML::addElement($doc, $author, "activity:object-type", ACTIVITY_OBJ_GROUP);
1452 XML::addElement($doc, $author, "activity:object-type", ACTIVITY_OBJ_PERSON);
1454 XML::addElement($doc, $author, "uri", $owner["url"]);
1455 XML::addElement($doc, $author, "name", $owner["nick"]);
1456 XML::addElement($doc, $author, "email", $owner["addr"]);
1457 if ($show_profile) {
1458 XML::addElement($doc, $author, "summary", BBCode::convert($owner["about"], false, 7));
1461 $attributes = ["rel" => "alternate", "type" => "text/html", "href" => $owner["url"]];
1462 XML::addElement($doc, $author, "link", "", $attributes);
1466 "type" => "image/jpeg", // To-Do?
1467 "media:width" => 300,
1468 "media:height" => 300,
1469 "href" => $owner["photo"]];
1470 XML::addElement($doc, $author, "link", "", $attributes);
1472 if (isset($owner["thumb"])) {
1475 "type" => "image/jpeg", // To-Do?
1476 "media:width" => 80,
1477 "media:height" => 80,
1478 "href" => $owner["thumb"]];
1479 XML::addElement($doc, $author, "link", "", $attributes);
1482 XML::addElement($doc, $author, "poco:preferredUsername", $owner["nick"]);
1483 XML::addElement($doc, $author, "poco:displayName", $owner["name"]);
1484 if ($show_profile) {
1485 XML::addElement($doc, $author, "poco:note", BBCode::convert($owner["about"], false, 7));
1487 if (trim($owner["location"]) != "") {
1488 $element = $doc->createElement("poco:address");
1489 XML::addElement($doc, $element, "poco:formatted", $owner["location"]);
1490 $author->appendChild($element);
1494 if (DBA::isResult($profile) && !$show_profile) {
1495 if (trim($profile["homepage"]) != "") {
1496 $urls = $doc->createElement("poco:urls");
1497 XML::addElement($doc, $urls, "poco:type", "homepage");
1498 XML::addElement($doc, $urls, "poco:value", $profile["homepage"]);
1499 XML::addElement($doc, $urls, "poco:primary", "true");
1500 $author->appendChild($urls);
1503 XML::addElement($doc, $author, "followers", "", ["url" => System::baseUrl()."/viewcontacts/".$owner["nick"]]);
1504 XML::addElement($doc, $author, "statusnet:profile_info", "", ["local_id" => $owner["uid"]]);
1506 if ($profile["publish"]) {
1507 XML::addElement($doc, $author, "mastodon:scope", "public");
1515 * @TODO Picture attachments should look like this:
1516 * <a href="https://status.pirati.ca/attachment/572819" title="https://status.pirati.ca/file/heluecht-20151202T222602-rd3u49p.gif"
1517 * class="attachment thumbnail" id="attachment-572819" rel="nofollow external">https://status.pirati.ca/attachment/572819</a>
1521 * @brief Returns the given activity if present - otherwise returns the "post" activity
1523 * @param array $item Data of the item that is to be posted
1525 * @return string activity
1527 private static function constructVerb(array $item)
1529 if (!empty($item['verb'])) {
1530 return $item['verb'];
1533 return ACTIVITY_POST;
1537 * @brief Returns the given object type if present - otherwise returns the "note" object type
1539 * @param array $item Data of the item that is to be posted
1541 * @return string Object type
1543 private static function constructObjecttype(array $item)
1545 if (in_array($item['object-type'], [ACTIVITY_OBJ_NOTE, ACTIVITY_OBJ_COMMENT]))
1546 return $item['object-type'];
1547 return ACTIVITY_OBJ_NOTE;
1551 * @brief Adds an entry element to the XML document
1553 * @param object $doc XML document
1554 * @param array $item Data of the item that is to be posted
1555 * @param array $owner Contact data of the poster
1556 * @param bool $toplevel optional default false
1557 * @param bool $feed_mode Behave like a regular feed for users if true
1559 * @return object Entry element
1561 private static function entry(DOMDocument $doc, array $item, array $owner, $toplevel = false, $feed_mode = false)
1565 $repeated_guid = self::getResharedGuid($item);
1566 if ($repeated_guid != "") {
1567 $xml = self::reshareEntry($doc, $item, $owner, $repeated_guid, $toplevel);
1574 if ($item["verb"] == ACTIVITY_LIKE) {
1575 return self::likeEntry($doc, $item, $owner, $toplevel);
1576 } elseif (in_array($item["verb"], [ACTIVITY_FOLLOW, NAMESPACE_OSTATUS."/unfollow"])) {
1577 return self::followEntry($doc, $item, $owner, $toplevel);
1579 return self::noteEntry($doc, $item, $owner, $toplevel, $feed_mode);
1584 * @brief Adds a source entry to the XML document
1586 * @param object $doc XML document
1587 * @param array $contact Array of the contact that is added
1589 * @return object Source element
1591 private static function sourceEntry(DOMDocument $doc, array $contact)
1593 $source = $doc->createElement("source");
1594 XML::addElement($doc, $source, "id", $contact["poll"]);
1595 XML::addElement($doc, $source, "title", $contact["name"]);
1596 XML::addElement($doc, $source, "link", "", ["rel" => "alternate", "type" => "text/html", "href" => $contact["alias"]]);
1597 XML::addElement($doc, $source, "link", "", ["rel" => "self", "type" => "application/atom+xml", "href" => $contact["poll"]]);
1598 XML::addElement($doc, $source, "icon", $contact["photo"]);
1599 XML::addElement($doc, $source, "updated", DateTimeFormat::utc($contact["success_update"]."+00:00", DateTimeFormat::ATOM));
1605 * @brief Fetches contact data from the contact or the gcontact table
1607 * @param string $url URL of the contact
1608 * @param array $owner Contact data of the poster
1610 * @return array Contact array
1612 private static function contactEntry($url, array $owner)
1615 "SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` IN (0, %d) ORDER BY `uid` DESC LIMIT 1",
1616 DBA::escape(Strings::normaliseLink($url)),
1617 intval($owner["uid"])
1619 if (DBA::isResult($r)) {
1621 $contact["uid"] = -1;
1624 if (!DBA::isResult($r)) {
1625 $gcontact = DBA::selectFirst('gcontact', [], ['nurl' => Strings::normaliseLink($url)]);
1626 if (DBA::isResult($r)) {
1627 $contact = $gcontact;
1628 $contact["uid"] = -1;
1629 $contact["success_update"] = $contact["updated"];
1633 if (!DBA::isResult($r)) {
1637 if (!isset($contact["poll"])) {
1638 $data = Probe::uri($url);
1639 $contact["poll"] = $data["poll"];
1641 if (!$contact["alias"]) {
1642 $contact["alias"] = $data["alias"];
1646 if (!isset($contact["alias"])) {
1647 $contact["alias"] = $contact["url"];
1650 $contact['account-type'] = $owner['account-type'];
1656 * @brief Adds an entry element with reshared content
1658 * @param object $doc XML document
1659 * @param array $item Data of the item that is to be posted
1660 * @param array $owner Contact data of the poster
1661 * @param string $repeated_guid guid
1662 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1664 * @return object Entry element
1666 private static function reshareEntry(DOMDocument $doc, array $item, array $owner, $repeated_guid, $toplevel)
1668 if (($item["id"] != $item["parent"]) && (Strings::normaliseLink($item["author-link"]) != Strings::normaliseLink($owner["url"]))) {
1669 Logger::log("OStatus entry is from author ".$owner["url"]." - not from ".$item["author-link"].". Quitting.", Logger::DEBUG);
1672 $title = self::entryHeader($doc, $entry, $owner, $item, $toplevel);
1674 $condition = ['uid' => $owner["uid"], 'guid' => $repeated_guid, 'private' => false,
1675 'network' => [Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS]];
1676 $repeated_item = Item::selectFirst([], $condition);
1677 if (!DBA::isResult($repeated_item)) {
1681 $contact = self::contactEntry($repeated_item['author-link'], $owner);
1683 $title = $owner["nick"]." repeated a notice by ".$contact["nick"];
1685 self::entryContent($doc, $entry, $item, $owner, $title, ACTIVITY_SHARE, false);
1687 $as_object = $doc->createElement("activity:object");
1689 XML::addElement($doc, $as_object, "activity:object-type", NAMESPACE_ACTIVITY_SCHEMA."activity");
1691 self::entryContent($doc, $as_object, $repeated_item, $owner, "", "", false);
1693 $author = self::addAuthor($doc, $contact, false);
1694 $as_object->appendChild($author);
1696 $as_object2 = $doc->createElement("activity:object");
1698 XML::addElement($doc, $as_object2, "activity:object-type", self::constructObjecttype($repeated_item));
1700 $title = sprintf("New comment by %s", $contact["nick"]);
1702 self::entryContent($doc, $as_object2, $repeated_item, $owner, $title);
1704 $as_object->appendChild($as_object2);
1706 self::entryFooter($doc, $as_object, $item, $owner, false);
1708 $source = self::sourceEntry($doc, $contact);
1710 $as_object->appendChild($source);
1712 $entry->appendChild($as_object);
1714 self::entryFooter($doc, $entry, $item, $owner);
1720 * @brief Adds an entry element with a "like"
1722 * @param object $doc XML document
1723 * @param array $item Data of the item that is to be posted
1724 * @param array $owner Contact data of the poster
1725 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1727 * @return object Entry element with "like"
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 $title = self::entryHeader($doc, $entry, $owner, $item, $toplevel);
1737 $verb = NAMESPACE_ACTIVITY_SCHEMA."favorite";
1738 self::entryContent($doc, $entry, $item, $owner, "Favorite", $verb, false);
1740 $as_object = $doc->createElement("activity:object");
1742 $parent = Item::selectFirst([], ['uri' => $item["thr-parent"], 'uid' => $item["uid"]]);
1748 XML::addElement($doc, $as_object, "activity:object-type", self::constructObjecttype($parent));
1750 self::entryContent($doc, $as_object, $parent, $owner, "New entry");
1752 $entry->appendChild($as_object);
1754 self::entryFooter($doc, $entry, $item, $owner);
1760 * @brief Adds the person object element to the XML document
1762 * @param object $doc XML document
1763 * @param array $owner Contact data of the poster
1764 * @param array $contact Contact data of the target
1766 * @return object author element
1768 private static function addPersonObject(DOMDocument $doc, array $owner, array $contact)
1770 $object = $doc->createElement("activity:object");
1771 XML::addElement($doc, $object, "activity:object-type", ACTIVITY_OBJ_PERSON);
1773 if ($contact['network'] == Protocol::PHANTOM) {
1774 XML::addElement($doc, $object, "id", $contact['url']);
1778 XML::addElement($doc, $object, "id", $contact["alias"]);
1779 XML::addElement($doc, $object, "title", $contact["nick"]);
1781 $attributes = ["rel" => "alternate", "type" => "text/html", "href" => $contact["url"]];
1782 XML::addElement($doc, $object, "link", "", $attributes);
1786 "type" => "image/jpeg", // To-Do?
1787 "media:width" => 300,
1788 "media:height" => 300,
1789 "href" => $contact["photo"]];
1790 XML::addElement($doc, $object, "link", "", $attributes);
1792 XML::addElement($doc, $object, "poco:preferredUsername", $contact["nick"]);
1793 XML::addElement($doc, $object, "poco:displayName", $contact["name"]);
1795 if (trim($contact["location"]) != "") {
1796 $element = $doc->createElement("poco:address");
1797 XML::addElement($doc, $element, "poco:formatted", $contact["location"]);
1798 $object->appendChild($element);
1805 * @brief Adds a follow/unfollow entry element
1807 * @param object $doc XML document
1808 * @param array $item Data of the follow/unfollow message
1809 * @param array $owner Contact data of the poster
1810 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1812 * @return object Entry element
1814 private static function followEntry(DOMDocument $doc, array $item, array $owner, $toplevel)
1816 $item["id"] = $item["parent"] = 0;
1817 $item["created"] = $item["edited"] = date("c");
1818 $item["private"] = true;
1820 $contact = Probe::uri($item['follow']);
1822 if ($contact['alias'] == '') {
1823 $contact['alias'] = $contact["url"];
1825 $item['follow'] = $contact['alias'];
1828 $condition = ['uid' => $owner['uid'], 'nurl' => Strings::normaliseLink($contact["url"])];
1829 $user_contact = DBA::selectFirst('contact', ['id'], $condition);
1831 if (DBA::isResult($user_contact)) {
1832 $connect_id = $user_contact['id'];
1837 if ($item['verb'] == ACTIVITY_FOLLOW) {
1838 $message = L10n::t('%s is now following %s.');
1839 $title = L10n::t('following');
1840 $action = "subscription";
1842 $message = L10n::t('%s stopped following %s.');
1843 $title = L10n::t('stopped following');
1844 $action = "unfollow";
1847 $item["uri"] = $item['parent-uri'] = $item['thr-parent']
1848 = 'tag:'.get_app()->getHostName().
1849 ','.date('Y-m-d').':'.$action.':'.$owner['uid'].
1850 ':person:'.$connect_id.':'.$item['created'];
1852 $item["body"] = sprintf($message, $owner["nick"], $contact["nick"]);
1854 self::entryHeader($doc, $entry, $owner, $item, $toplevel);
1856 self::entryContent($doc, $entry, $item, $owner, $title);
1858 $object = self::addPersonObject($doc, $owner, $contact);
1859 $entry->appendChild($object);
1861 self::entryFooter($doc, $entry, $item, $owner);
1867 * @brief Adds a regular entry element
1869 * @param object $doc XML document
1870 * @param array $item Data of the item that is to be posted
1871 * @param array $owner Contact data of the poster
1872 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1873 * @param bool $feed_mode Behave like a regular feed for users if true
1875 * @return object Entry element
1877 private static function noteEntry(DOMDocument $doc, array $item, array $owner, $toplevel, $feed_mode)
1879 if (($item["id"] != $item["parent"]) && (Strings::normaliseLink($item["author-link"]) != Strings::normaliseLink($owner["url"]))) {
1880 Logger::log("OStatus entry is from author ".$owner["url"]." - not from ".$item["author-link"].". Quitting.", Logger::DEBUG);
1883 $title = self::entryHeader($doc, $entry, $owner, $item, $toplevel);
1885 XML::addElement($doc, $entry, "activity:object-type", ACTIVITY_OBJ_NOTE);
1887 self::entryContent($doc, $entry, $item, $owner, $title, '', true, $feed_mode);
1889 self::entryFooter($doc, $entry, $item, $owner, !$feed_mode, $feed_mode);
1895 * @brief Adds a header element to the XML document
1897 * @param object $doc XML document
1898 * @param object $entry The entry element where the elements are added
1899 * @param array $owner Contact data of the poster
1900 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1902 * @return string The title for the element
1904 private static function entryHeader(DOMDocument $doc, &$entry, array $owner, array $item, $toplevel)
1906 /// @todo Check if this title stuff is really needed (I guess not)
1908 $entry = $doc->createElement("entry");
1909 if (!empty($item['title'])) {
1910 $title = BBCode::convert($item['title'], false, 7);
1912 $title = sprintf("New note by %s", $owner["nick"]);
1915 if ($owner['account-type'] == Contact::ACCOUNT_TYPE_COMMUNITY) {
1916 $contact = self::contactEntry($item['author-link'], $owner);
1917 $author = self::addAuthor($doc, $contact, false);
1918 $entry->appendChild($author);
1921 $entry = $doc->createElementNS(NAMESPACE_ATOM1, "entry");
1923 $entry->setAttribute("xmlns:thr", NAMESPACE_THREAD);
1924 $entry->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
1925 $entry->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
1926 $entry->setAttribute("xmlns:media", NAMESPACE_MEDIA);
1927 $entry->setAttribute("xmlns:poco", NAMESPACE_POCO);
1928 $entry->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
1929 $entry->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
1930 $entry->setAttribute("xmlns:mastodon", NAMESPACE_MASTODON);
1932 $author = self::addAuthor($doc, $owner);
1933 $entry->appendChild($author);
1935 $title = sprintf("New comment by %s", $owner["nick"]);
1941 * @brief Adds elements to the XML document
1943 * @param object $doc XML document
1944 * @param object $entry Entry element where the content is added
1945 * @param array $item Data of the item that is to be posted
1946 * @param array $owner Contact data of the poster
1947 * @param string $title Title for the post
1948 * @param string $verb The activity verb
1949 * @param bool $complete Add the "status_net" element?
1950 * @param bool $feed_mode Behave like a regular feed for users if true
1953 private static function entryContent(DOMDocument $doc, $entry, array $item, array $owner, $title, $verb = "", $complete = true, $feed_mode = false)
1956 $verb = self::constructVerb($item);
1959 XML::addElement($doc, $entry, "id", $item["uri"]);
1960 XML::addElement($doc, $entry, "title", $title);
1962 $body = self::formatPicturePost($item['body']);
1964 if (!empty($item['title']) && !$feed_mode) {
1965 $body = "[b]".$item['title']."[/b]\n\n".$body;
1968 $body = BBCode::convert($body, false, 7);
1970 XML::addElement($doc, $entry, "content", $body, ["type" => "html"]);
1972 XML::addElement($doc, $entry, "link", "", ["rel" => "alternate", "type" => "text/html",
1973 "href" => System::baseUrl()."/display/".$item["guid"]]
1976 if (!$feed_mode && $complete && ($item["id"] > 0)) {
1977 XML::addElement($doc, $entry, "status_net", "", ["notice_id" => $item["id"]]);
1981 XML::addElement($doc, $entry, "activity:verb", $verb);
1984 XML::addElement($doc, $entry, "published", DateTimeFormat::utc($item["created"]."+00:00", DateTimeFormat::ATOM));
1985 XML::addElement($doc, $entry, "updated", DateTimeFormat::utc($item["edited"]."+00:00", DateTimeFormat::ATOM));
1989 * @brief Adds the elements at the foot of an entry to the XML document
1991 * @param object $doc XML document
1992 * @param object $entry The entry element where the elements are added
1993 * @param array $item Data of the item that is to be posted
1994 * @param array $owner Contact data of the poster
1995 * @param bool $complete default true
1996 * @param bool $feed_mode Behave like a regular feed for users if true
1999 private static function entryFooter(DOMDocument $doc, $entry, array $item, array $owner, $complete = true, $feed_mode = false)
2003 if (($item['parent'] != $item['id']) || ($item['parent-uri'] !== $item['uri']) || (($item['thr-parent'] !== '') && ($item['thr-parent'] !== $item['uri']))) {
2004 $parent = Item::selectFirst(['guid', 'author-link', 'owner-link'], ['id' => $item["parent"]]);
2005 $parent_item = (($item['thr-parent']) ? $item['thr-parent'] : $item['parent-uri']);
2007 $thrparent = Item::selectFirst(['guid', 'author-link', 'owner-link', 'plink'], ['uid' => $owner["uid"], 'uri' => $parent_item]);
2009 if (DBA::isResult($thrparent)) {
2010 $mentioned[$thrparent["author-link"]] = $thrparent["author-link"];
2011 $mentioned[$thrparent["owner-link"]] = $thrparent["owner-link"];
2012 $parent_plink = $thrparent["plink"];
2014 $mentioned[$parent["author-link"]] = $parent["author-link"];
2015 $mentioned[$parent["owner-link"]] = $parent["owner-link"];
2016 $parent_plink = System::baseUrl()."/display/".$parent["guid"];
2020 "ref" => $parent_item,
2021 "href" => $parent_plink];
2022 XML::addElement($doc, $entry, "thr:in-reply-to", "", $attributes);
2026 "href" => $parent_plink];
2027 XML::addElement($doc, $entry, "link", "", $attributes);
2030 if (!$feed_mode && (intval($item["parent"]) > 0)) {
2031 $conversation_href = $conversation_uri = str_replace('/objects/', '/context/', $item['parent-uri']);
2033 if (isset($parent_item)) {
2034 $conversation = DBA::selectFirst('conversation', ['conversation-uri', 'conversation-href'], ['item-uri' => $parent_item]);
2035 if (DBA::isResult($conversation)) {
2036 if ($conversation['conversation-uri'] != '') {
2037 $conversation_uri = $conversation['conversation-uri'];
2039 if ($conversation['conversation-href'] != '') {
2040 $conversation_href = $conversation['conversation-href'];
2045 XML::addElement($doc, $entry, "link", "", ["rel" => "ostatus:conversation", "href" => $conversation_href]);
2048 "href" => $conversation_href,
2049 "local_id" => $item["parent"],
2050 "ref" => $conversation_uri];
2052 XML::addElement($doc, $entry, "ostatus:conversation", $conversation_uri, $attributes);
2055 $tags = item::getFeedTags($item);
2058 foreach ($tags as $t) {
2060 $mentioned[$t[1]] = $t[1];
2065 // Make sure that mentions are accepted (GNU Social has problems with mixing HTTP and HTTPS)
2067 foreach ($mentioned as $mention) {
2068 $newmentions[str_replace("http://", "https://", $mention)] = str_replace("http://", "https://", $mention);
2069 $newmentions[str_replace("https://", "http://", $mention)] = str_replace("https://", "http://", $mention);
2071 $mentioned = $newmentions;
2073 foreach ($mentioned as $mention) {
2074 $condition = ['uid' => $owner['uid'], 'nurl' => Strings::normaliseLink($mention)];
2075 $contact = DBA::selectFirst('contact', ['forum', 'prv', 'self', 'contact-type'], $condition);
2076 if ($contact["forum"] || $contact["prv"] || ($owner['contact-type'] == Contact::ACCOUNT_TYPE_COMMUNITY) ||
2077 ($contact['self'] && ($owner['account-type'] == Contact::ACCOUNT_TYPE_COMMUNITY))) {
2078 XML::addElement($doc, $entry, "link", "",
2080 "rel" => "mentioned",
2081 "ostatus:object-type" => ACTIVITY_OBJ_GROUP,
2085 XML::addElement($doc, $entry, "link", "",
2087 "rel" => "mentioned",
2088 "ostatus:object-type" => ACTIVITY_OBJ_PERSON,
2094 if ($owner['account-type'] == Contact::ACCOUNT_TYPE_COMMUNITY) {
2095 XML::addElement($doc, $entry, "link", "", [
2096 "rel" => "mentioned",
2097 "ostatus:object-type" => "http://activitystrea.ms/schema/1.0/group",
2098 "href" => $owner['url']
2102 if (!$item["private"] && !$feed_mode) {
2103 XML::addElement($doc, $entry, "link", "", ["rel" => "ostatus:attention",
2104 "href" => "http://activityschema.org/collection/public"]);
2105 XML::addElement($doc, $entry, "link", "", ["rel" => "mentioned",
2106 "ostatus:object-type" => "http://activitystrea.ms/schema/1.0/collection",
2107 "href" => "http://activityschema.org/collection/public"]);
2108 XML::addElement($doc, $entry, "mastodon:scope", "public");
2112 foreach ($tags as $t) {
2114 XML::addElement($doc, $entry, "category", "", ["term" => $t[2]]);
2119 self::getAttachment($doc, $entry, $item);
2121 if ($complete && ($item["id"] > 0)) {
2122 $app = $item["app"];
2127 $attributes = ["local_id" => $item["id"], "source" => $app];
2129 if (isset($parent["id"])) {
2130 $attributes["repeat_of"] = $parent["id"];
2133 if ($item["coord"] != "") {
2134 XML::addElement($doc, $entry, "georss:point", $item["coord"]);
2137 XML::addElement($doc, $entry, "statusnet:notice_info", "", $attributes);
2142 * Creates the XML feed for a given nickname
2144 * Supported filters:
2145 * - activity (default): all the public posts
2146 * - posts: all the public top-level posts
2147 * - comments: all the public replies
2149 * Updates the provided last_update parameter if the result comes from the
2150 * cache or it is empty
2152 * @brief Creates the XML feed for a given nickname
2154 * @param string $owner_nick Nickname of the feed owner
2155 * @param string $last_update Date of the last update
2156 * @param integer $max_items Number of maximum items to fetch
2157 * @param string $filter Feed items filter (activity, posts or comments)
2158 * @param boolean $nocache Wether to bypass caching
2159 * @param boolean $feed_mode Behave like a regular feed for users if true
2161 * @return string XML feed
2163 public static function feed($owner_nick, &$last_update, $max_items = 300, $filter = 'activity', $nocache = false, $feed_mode = false)
2165 $stamp = microtime(true);
2167 $owner = User::getOwnerDataByNick($owner_nick);
2172 $cachekey = "ostatus:feed:" . $owner_nick . ":" . $filter . ":" . $last_update;
2174 $previous_created = $last_update;
2176 // Don't cache when the last item was posted less then 15 minutes ago (Cache duration)
2177 if ((time() - strtotime($owner['last-item'])) < 15*60) {
2178 $result = Cache::get($cachekey);
2179 if (!$nocache && !is_null($result)) {
2180 Logger::log('Feed duration: ' . number_format(microtime(true) - $stamp, 3) . ' - ' . $owner_nick . ' - ' . $filter . ' - ' . $previous_created . ' (cached)', Logger::DEBUG);
2181 $last_update = $result['last_update'];
2182 return $result['feed'];
2186 if (!strlen($last_update)) {
2187 $last_update = 'now -30 days';
2190 $check_date = DateTimeFormat::utc($last_update);
2191 $authorid = Contact::getIdForURL($owner["url"], 0, true);
2193 $condition = ["`uid` = ? AND `created` > ? AND NOT `deleted`
2194 AND NOT `private` AND `visible` AND `wall` AND `parent-network` IN (?, ?)",
2195 $owner["uid"], $check_date, Protocol::OSTATUS, Protocol::DFRN];
2197 if ($filter === 'comments') {
2198 $condition[0] .= " AND `object-type` = ? ";
2199 $condition[] = ACTIVITY_OBJ_COMMENT;
2202 if ($owner['account-type'] != Contact::ACCOUNT_TYPE_COMMUNITY) {
2203 $condition[0] .= " AND `contact-id` = ? AND `author-id` = ?";
2204 $condition[] = $owner["id"];
2205 $condition[] = $authorid;
2208 $params = ['order' => ['created' => true], 'limit' => $max_items];
2210 if ($filter === 'posts') {
2211 $ret = Item::selectThread([], $condition, $params);
2213 $ret = Item::select([], $condition, $params);
2216 $items = Item::inArray($ret);
2218 $doc = new DOMDocument('1.0', 'utf-8');
2219 $doc->formatOutput = true;
2221 $root = self::addHeader($doc, $owner, $filter, $feed_mode);
2223 foreach ($items as $item) {
2224 if (Config::get('system', 'ostatus_debug')) {
2225 $item['body'] .= '🍼';
2228 $entry = self::entry($doc, $item, $owner, false, $feed_mode);
2229 $root->appendChild($entry);
2231 if ($last_update < $item['created']) {
2232 $last_update = $item['created'];
2236 $feeddata = trim($doc->saveXML());
2238 $msg = ['feed' => $feeddata, 'last_update' => $last_update];
2239 Cache::set($cachekey, $msg, Cache::QUARTER_HOUR);
2241 Logger::log('Feed duration: ' . number_format(microtime(true) - $stamp, 3) . ' - ' . $owner_nick . ' - ' . $filter . ' - ' . $previous_created, Logger::DEBUG);
2247 * @brief Creates the XML for a salmon message
2249 * @param array $item Data of the item that is to be posted
2250 * @param array $owner Contact data of the poster
2252 * @return string XML for the salmon
2254 public static function salmon(array $item, array $owner)
2256 $doc = new DOMDocument('1.0', 'utf-8');
2257 $doc->formatOutput = true;
2259 if (Config::get('system', 'ostatus_debug')) {
2260 $item['body'] .= '🐟';
2263 $entry = self::entry($doc, $item, $owner, true);
2265 $doc->appendChild($entry);
2267 return trim($doc->saveXML());