3 * @file src/Protocol/OStatus.php
5 namespace Friendica\Protocol;
10 use Friendica\Content\Text\BBCode;
11 use Friendica\Content\Text\HTML;
12 use Friendica\Core\Cache;
13 use Friendica\Core\Config;
14 use Friendica\Core\L10n;
15 use Friendica\Core\Lock;
16 use Friendica\Core\System;
17 use Friendica\Database\DBM;
18 use Friendica\Model\Contact;
19 use Friendica\Model\Conversation;
20 use Friendica\Model\GContact;
21 use Friendica\Model\Item;
22 use Friendica\Model\User;
23 use Friendica\Network\Probe;
24 use Friendica\Object\Image;
25 use Friendica\Util\DateTimeFormat;
26 use Friendica\Util\Network;
27 use Friendica\Util\XML;
29 require_once 'include/dba.php';
30 require_once 'include/items.php';
31 require_once 'mod/share.php';
32 require_once 'include/enotify.php';
33 require_once 'include/api.php';
34 require_once 'mod/proxy.php';
37 * @brief This class contain functions for the OStatus protocol
41 private static $itemlist;
42 private static $conv_list = [];
45 * @brief Fetches author data
47 * @param object $xpath The xpath object
48 * @param object $context The xml context of the author details
49 * @param array $importer user record of the importing user
50 * @param array $contact Called by reference, will contain the fetched contact
51 * @param bool $onlyfetch Only fetch the header without updating the contact entries
53 * @return array Array of author related entries for the item
55 private static function fetchAuthor($xpath, $context, $importer, &$contact, $onlyfetch)
58 $author["author-link"] = XML::getFirstNodeValue($xpath, 'atom:author/atom:uri/text()', $context);
59 $author["author-name"] = XML::getFirstNodeValue($xpath, 'atom:author/atom:name/text()', $context);
60 $addr = XML::getFirstNodeValue($xpath, 'atom:author/atom:email/text()', $context);
62 $aliaslink = $author["author-link"];
64 $alternate_item = $xpath->query("atom:author/atom:link[@rel='alternate']", $context)->item(0);
65 if (is_object($alternate_item)) {
66 foreach ($alternate_item->attributes as $attributes) {
67 if (($attributes->name == "href") && ($attributes->textContent != "")) {
68 $author["author-link"] = $attributes->textContent;
72 $author["author-id"] = Contact::getIdForURL($author["author-link"]);
74 $author["contact-id"] = $contact["id"];
77 if ($aliaslink != '') {
78 $condition = ["`uid` = ? AND `alias` = ? AND `network` != ? AND `rel` IN (?, ?)",
79 $importer["uid"], $aliaslink, NETWORK_STATUSNET,
80 CONTACT_IS_SHARING, CONTACT_IS_FRIEND];
81 $contact = dba::selectFirst('contact', [], $condition);
84 if (!DBM::is_result($contact) && $author["author-link"] != '') {
85 if ($aliaslink == "") {
86 $aliaslink = $author["author-link"];
89 $condition = ["`uid` = ? AND `nurl` IN (?, ?) AND `network` != ? AND `rel` IN (?, ?)",
90 $importer["uid"], normalise_link($author["author-link"]), normalise_link($aliaslink),
91 NETWORK_STATUSNET, CONTACT_IS_SHARING, CONTACT_IS_FRIEND];
92 $contact = dba::selectFirst('contact', [], $condition);
95 if (!DBM::is_result($contact) && ($addr != '')) {
96 $condition = ["`uid` = ? AND `addr` = ? AND `network` != ? AND `rel` IN (?, ?)",
97 $importer["uid"], $addr, NETWORK_STATUSNET,
98 CONTACT_IS_SHARING, CONTACT_IS_FRIEND];
99 $contact = dba::selectFirst('contact', [], $condition);
102 if (DBM::is_result($contact)) {
103 if ($contact['blocked']) {
106 $author["contact-id"] = $contact["id"];
110 $avatars = $xpath->query("atom:author/atom:link[@rel='avatar']", $context);
111 foreach ($avatars as $avatar) {
114 foreach ($avatar->attributes as $attributes) {
115 if ($attributes->name == "href") {
116 $href = $attributes->textContent;
118 if ($attributes->name == "width") {
119 $width = $attributes->textContent;
123 $avatarlist[$width] = $href;
126 if (count($avatarlist) > 0) {
128 $author["author-avatar"] = Probe::fixAvatar(current($avatarlist), $author["author-link"]);
131 $displayname = XML::getFirstNodeValue($xpath, 'atom:author/poco:displayName/text()', $context);
132 if ($displayname != "") {
133 $author["author-name"] = $displayname;
136 $author["owner-id"] = $author["author-id"];
138 // Only update the contacts if it is an OStatus contact
139 if (DBM::is_result($contact) && ($contact['id'] > 0) && !$onlyfetch && ($contact["network"] == NETWORK_OSTATUS)) {
141 // Update contact data
143 unset($current['name-date']);
145 // This query doesn't seem to work
146 // $value = $xpath->query("atom:link[@rel='salmon']", $context)->item(0)->nodeValue;
148 // $contact["notify"] = $value;
150 // This query doesn't seem to work as well - I hate these queries
151 // $value = $xpath->query("atom:link[@rel='self' and @type='application/atom+xml']", $context)->item(0)->nodeValue;
153 // $contact["poll"] = $value;
155 $contact['url'] = $author["author-link"];
156 $contact['nurl'] = normalise_link($contact['url']);
158 $value = XML::getFirstNodeValue($xpath, 'atom:author/atom:uri/text()', $context);
160 $contact["alias"] = $value;
163 $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:displayName/text()', $context);
165 $contact["name"] = $value;
168 $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:preferredUsername/text()', $context);
170 $contact["nick"] = $value;
173 $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:note/text()', $context);
175 $contact["about"] = HTML::toBBCode($value);
178 $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:address/poco:formatted/text()', $context);
180 $contact["location"] = $value;
183 $contact['name-date'] = DateTimeFormat::utcNow();
185 dba::update('contact', $contact, ['id' => $contact["id"]], $current);
187 if (!empty($author["author-avatar"]) && ($author["author-avatar"] != $current['avatar'])) {
188 logger("Update profile picture for contact ".$contact["id"], LOGGER_DEBUG);
189 Contact::updateAvatar($author["author-avatar"], $importer["uid"], $contact["id"]);
192 // Ensure that we are having this contact (with uid=0)
193 $cid = Contact::getIdForURL($aliaslink, 0, true);
196 $fields = ['url', 'nurl', 'name', 'nick', 'alias', 'about', 'location'];
197 $old_contact = dba::selectFirst('contact', $fields, ['id' => $cid]);
199 // Update it with the current values
200 $fields = ['url' => $author["author-link"], 'name' => $contact["name"],
201 'nurl' => normalise_link($author["author-link"]),
202 'nick' => $contact["nick"], 'alias' => $contact["alias"],
203 'about' => $contact["about"], 'location' => $contact["location"],
204 'success_update' => DateTimeFormat::utcNow(), 'last-update' => DateTimeFormat::utcNow()];
206 dba::update('contact', $fields, ['id' => $cid], $old_contact);
209 if (!empty($author["author-avatar"])) {
210 Contact::updateAvatar($author["author-avatar"], 0, $cid);
214 $contact["generation"] = 2;
215 $contact["hide"] = false; // OStatus contacts are never hidden
216 if (!empty($author["author-avatar"])) {
217 $contact["photo"] = $author["author-avatar"];
219 $gcid = GContact::update($contact);
221 GContact::link($gcid, $contact["uid"], $contact["id"]);
228 * @brief Fetches author data from a given XML string
230 * @param string $xml The XML
231 * @param array $importer user record of the importing user
233 * @return array Array of author related entries for the item
235 public static function salmonAuthor($xml, $importer)
241 $doc = new DOMDocument();
242 @$doc->loadXML($xml);
244 $xpath = new DOMXPath($doc);
245 $xpath->registerNamespace('atom', NAMESPACE_ATOM1);
246 $xpath->registerNamespace('thr', NAMESPACE_THREAD);
247 $xpath->registerNamespace('georss', NAMESPACE_GEORSS);
248 $xpath->registerNamespace('activity', NAMESPACE_ACTIVITY);
249 $xpath->registerNamespace('media', NAMESPACE_MEDIA);
250 $xpath->registerNamespace('poco', NAMESPACE_POCO);
251 $xpath->registerNamespace('ostatus', NAMESPACE_OSTATUS);
252 $xpath->registerNamespace('statusnet', NAMESPACE_STATUSNET);
254 $contact = ["id" => 0];
256 // Fetch the first author
257 $authordata = $xpath->query('//author')->item(0);
258 $author = self::fetchAuthor($xpath, $authordata, $importer, $contact, true);
263 * @brief Read attributes from element
265 * @param object $element Element object
267 * @return array attributes
269 private static function readAttributes($element)
273 foreach ($element->attributes as $attributes) {
274 $attribute[$attributes->name] = $attributes->textContent;
281 * @brief Imports an XML string containing OStatus elements
283 * @param string $xml The XML
284 * @param array $importer user record of the importing user
285 * @param array $contact contact
286 * @param string $hub Called by reference, returns the fetched hub data
289 public static function import($xml, $importer, &$contact, &$hub)
291 self::process($xml, $importer, $contact, $hub);
295 * @brief Internal feed processing
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
301 * @param boolean $stored Is the post fresh imported or from the database?
302 * @param boolean $initialize Is it the leading post so that data has to be initialized?
304 * @return boolean Could the XML be processed?
306 private static function process($xml, $importer, &$contact, &$hub, $stored = false, $initialize = true)
309 self::$itemlist = [];
310 self::$conv_list = [];
313 logger("Import OStatus message", LOGGER_DEBUG);
318 $doc = new DOMDocument();
319 @$doc->loadXML($xml);
321 $xpath = new DOMXPath($doc);
322 $xpath->registerNamespace('atom', NAMESPACE_ATOM1);
323 $xpath->registerNamespace('thr', NAMESPACE_THREAD);
324 $xpath->registerNamespace('georss', NAMESPACE_GEORSS);
325 $xpath->registerNamespace('activity', NAMESPACE_ACTIVITY);
326 $xpath->registerNamespace('media', NAMESPACE_MEDIA);
327 $xpath->registerNamespace('poco', NAMESPACE_POCO);
328 $xpath->registerNamespace('ostatus', NAMESPACE_OSTATUS);
329 $xpath->registerNamespace('statusnet', NAMESPACE_STATUSNET);
332 $hub_items = $xpath->query("/atom:feed/atom:link[@rel='hub']")->item(0);
333 if (is_object($hub_items)) {
334 $hub_attributes = $hub_items->attributes;
335 if (is_object($hub_attributes)) {
336 foreach ($hub_attributes as $hub_attribute) {
337 if ($hub_attribute->name == "href") {
338 $hub = $hub_attribute->textContent;
339 logger("Found hub ".$hub, LOGGER_DEBUG);
346 $header["uid"] = $importer["uid"];
347 $header["network"] = NETWORK_OSTATUS;
348 $header["type"] = "remote-comment";
350 $header["origin"] = 0;
351 $header["gravity"] = GRAVITY_COMMENT;
353 $first_child = $doc->firstChild->tagName;
355 if ($first_child == "feed") {
356 $entries = $xpath->query('/atom:feed/atom:entry');
358 $entries = $xpath->query('/atom:entry');
361 if ($entries->length == 1) {
362 // We reformat the XML to make it better readable
363 $doc2 = new DOMDocument();
364 $doc2->loadXML($xml);
365 $doc2->preserveWhiteSpace = false;
366 $doc2->formatOutput = true;
367 $xml2 = $doc2->saveXML();
369 $header["protocol"] = PROTOCOL_OSTATUS_SALMON;
370 $header["source"] = $xml2;
371 } elseif (!$initialize) {
375 // Fetch the first author
376 $authordata = $xpath->query('//author')->item(0);
377 $author = self::fetchAuthor($xpath, $authordata, $importer, $contact, $stored);
379 $entry = $xpath->query('/atom:entry');
381 // Reverse the order of the entries
384 foreach ($entries as $entry) {
385 $entrylist[] = $entry;
388 foreach (array_reverse($entrylist) as $entry) {
390 $authorelement = $xpath->query('/atom:entry/atom:author', $entry);
392 if ($authorelement->length == 0) {
393 $authorelement = $xpath->query('atom:author', $entry);
396 if ($authorelement->length > 0) {
397 $author = self::fetchAuthor($xpath, $entry, $importer, $contact, $stored);
400 $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:preferredUsername/text()', $entry);
404 $nickname = $author["author-name"];
407 $item = array_merge($header, $author);
409 $item["uri"] = XML::getFirstNodeValue($xpath, 'atom:id/text()', $entry);
411 $item["verb"] = XML::getFirstNodeValue($xpath, 'activity:verb/text()', $entry);
414 if (in_array($item["verb"], ['qvitter-delete-notice', ACTIVITY_DELETE, 'delete'])) {
415 self::deleteNotice($item);
419 if (in_array($item["verb"], [NAMESPACE_OSTATUS."/unfavorite", ACTIVITY_UNFAVORITE])) {
420 // Ignore "Unfavorite" message
421 logger("Ignore unfavorite message ".print_r($item, true), LOGGER_DEBUG);
425 // Deletions come with the same uri, so we check for duplicates after processing deletions
426 if (Item::exists(['uid' => $importer["uid"], 'uri' => $item["uri"]])) {
427 logger('Post with URI '.$item["uri"].' already existed for user '.$importer["uid"].'.', LOGGER_DEBUG);
430 logger('Processing post with URI '.$item["uri"].' for user '.$importer["uid"].'.', LOGGER_DEBUG);
433 if ($item["verb"] == ACTIVITY_JOIN) {
434 // ignore "Join" messages
435 logger("Ignore join message ".print_r($item, true), LOGGER_DEBUG);
439 if ($item["verb"] == "http://mastodon.social/schema/1.0/block") {
440 // ignore mastodon "block" messages
441 logger("Ignore block message ".print_r($item, true), LOGGER_DEBUG);
445 if ($item["verb"] == ACTIVITY_FOLLOW) {
446 Contact::addRelationship($importer, $contact, $item, $nickname);
450 if ($item["verb"] == NAMESPACE_OSTATUS."/unfollow") {
452 Contact::removeFollower($importer, $contact, $item, $dummy);
456 if ($item["verb"] == ACTIVITY_FAVORITE) {
457 $orig_uri = $xpath->query("activity:object/atom:id", $entry)->item(0)->nodeValue;
458 logger("Favorite ".$orig_uri." ".print_r($item, true));
460 $item["type"] = "activity";
461 $item["verb"] = ACTIVITY_LIKE;
462 $item["parent-uri"] = $orig_uri;
463 $item["gravity"] = GRAVITY_ACTIVITY;
464 $item["object-type"] = ACTIVITY_OBJ_NOTE;
467 // http://activitystrea.ms/schema/1.0/rsvp-yes
468 if (!in_array($item["verb"], [ACTIVITY_POST, ACTIVITY_LIKE, ACTIVITY_SHARE])) {
469 logger("Unhandled verb ".$item["verb"]." ".print_r($item, true), LOGGER_DEBUG);
472 self::processPost($xpath, $entry, $item, $importer);
474 if ($initialize && (count(self::$itemlist) > 0)) {
475 if (self::$itemlist[0]['uri'] == self::$itemlist[0]['parent-uri']) {
476 // We will import it everytime, when it is started by our contacts
477 $valid = !empty(self::$itemlist[0]['contact-id']);
479 // If not, then it depends on this setting
480 $valid = !Config::get('system', 'ostatus_full_threads');
482 logger("Item with uri ".self::$itemlist[0]['uri']." will be imported due to the system settings.", LOGGER_DEBUG);
485 logger("Item with uri ".self::$itemlist[0]['uri']." belongs to a contact (".self::$itemlist[0]['contact-id']."). It will be imported.", LOGGER_DEBUG);
488 // Never post a thread when the only interaction by our contact was a like
490 $verbs = [ACTIVITY_POST, ACTIVITY_SHARE];
491 foreach (self::$itemlist as $item) {
492 if (!empty($item['contact-id']) && in_array($item['verb'], $verbs)) {
497 logger("Item with uri ".self::$itemlist[0]['uri']." will be imported since the thread contains posts or shares.", LOGGER_DEBUG);
501 // But we will only import complete threads
502 $valid = Item::exists(['uid' => $importer["uid"], 'uri' => self::$itemlist[0]['parent-uri']]);
504 logger("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);
509 $default_contact = 0;
510 $key = count(self::$itemlist);
511 for ($key = count(self::$itemlist) - 1; $key >= 0; $key--) {
512 if (empty(self::$itemlist[$key]['contact-id'])) {
513 self::$itemlist[$key]['contact-id'] = $default_contact;
515 $default_contact = $item['contact-id'];
518 foreach (self::$itemlist as $item) {
519 $found = Item::exists(['uid' => $importer["uid"], 'uri' => $item["uri"]]);
521 logger("Item with uri ".$item["uri"]." for user ".$importer["uid"]." already exists.", LOGGER_DEBUG);
522 } elseif ($item['contact-id'] < 0) {
523 logger("Item with uri ".$item["uri"]." is from a blocked contact.", LOGGER_DEBUG);
525 // We are having duplicated entries. Hopefully this solves it.
526 if (Lock::acquire('ostatus_process_item_insert')) {
527 $ret = Item::insert($item);
528 Lock::release('ostatus_process_item_insert');
529 logger("Item with uri ".$item["uri"]." for user ".$importer["uid"].' stored. Return value: '.$ret);
531 $ret = Item::insert($item);
532 logger("We couldn't lock - but tried to store the item anyway. Return value is ".$ret);
537 self::$itemlist = [];
539 logger('Processing done for post with URI '.$item["uri"].' for user '.$importer["uid"].'.', LOGGER_DEBUG);
545 * @param object $item item
548 private static function deleteNotice($item)
550 $condition = ['uid' => $item['uid'], 'author-id' => $item['author-id'], 'uri' => $item['uri']];
551 if (!Item::exists($condition)) {
552 logger('Item from '.$item['author-link'].' with uri '.$item['uri'].' for user '.$item['uid']." wasn't found. We don't delete it.");
556 Item::delete($condition);
558 logger('Deleted item with uri '.$item['uri'].' for user '.$item['uid']);
562 * @brief Processes the XML for a post
564 * @param object $xpath The xpath object
565 * @param object $entry The xml entry that is processed
566 * @param array $item The item array
567 * @param array $importer user record of the importing user
570 private static function processPost($xpath, $entry, &$item, $importer)
572 $item["body"] = HTML::toBBCode(XML::getFirstNodeValue($xpath, 'atom:content/text()', $entry));
573 $item["object-type"] = XML::getFirstNodeValue($xpath, 'activity:object-type/text()', $entry);
574 if (($item["object-type"] == ACTIVITY_OBJ_BOOKMARK) || ($item["object-type"] == ACTIVITY_OBJ_EVENT)) {
575 $item["title"] = XML::getFirstNodeValue($xpath, 'atom:title/text()', $entry);
576 $item["body"] = XML::getFirstNodeValue($xpath, 'atom:summary/text()', $entry);
577 } elseif ($item["object-type"] == ACTIVITY_OBJ_QUESTION) {
578 $item["title"] = XML::getFirstNodeValue($xpath, 'atom:title/text()', $entry);
581 $item["created"] = XML::getFirstNodeValue($xpath, 'atom:published/text()', $entry);
582 $item["edited"] = XML::getFirstNodeValue($xpath, 'atom:updated/text()', $entry);
583 $item['conversation-uri'] = XML::getFirstNodeValue($xpath, 'ostatus:conversation/text()', $entry);
585 $conv = $xpath->query('ostatus:conversation', $entry);
586 if (is_object($conv->item(0))) {
587 foreach ($conv->item(0)->attributes as $attributes) {
588 if ($attributes->name == "ref") {
589 $item['conversation-uri'] = $attributes->textContent;
591 if ($attributes->name == "href") {
592 $item['conversation-href'] = $attributes->textContent;
599 $inreplyto = $xpath->query('thr:in-reply-to', $entry);
600 if (is_object($inreplyto->item(0))) {
601 foreach ($inreplyto->item(0)->attributes as $attributes) {
602 if ($attributes->name == "ref") {
603 $item["parent-uri"] = $attributes->textContent;
605 if ($attributes->name == "href") {
606 $related = $attributes->textContent;
611 $georsspoint = $xpath->query('georss:point', $entry);
612 if (!empty($georsspoint) && ($georsspoint->length > 0)) {
613 $item["coord"] = $georsspoint->item(0)->nodeValue;
616 $categories = $xpath->query('atom:category', $entry);
618 foreach ($categories as $category) {
619 foreach ($category->attributes as $attributes) {
620 if ($attributes->name == "term") {
621 $term = $attributes->textContent;
622 if (!empty($item["tag"])) {
628 $item["tag"] .= "#[url=".System::baseUrl()."/search?tag=".$term."]".$term."[/url]";
637 $links = $xpath->query('atom:link', $entry);
639 $link_data = self::processLinks($links, $item);
640 $self = $link_data['self'];
641 $add_body = $link_data['add_body'];
646 $notice_info = $xpath->query('statusnet:notice_info', $entry);
647 if ($notice_info && ($notice_info->length > 0)) {
648 foreach ($notice_info->item(0)->attributes as $attributes) {
649 if ($attributes->name == "source") {
650 $item["app"] = strip_tags($attributes->textContent);
652 if ($attributes->name == "repeat_of") {
653 $repeat_of = $attributes->textContent;
657 // Is it a repeated post?
658 if (($repeat_of != "") || ($item["verb"] == ACTIVITY_SHARE)) {
659 $link_data = self::processRepeatedItem($xpath, $entry, $item, $importer);
660 if (!empty($link_data['add_body'])) {
661 $add_body .= $link_data['add_body'];
665 $item["body"] .= $add_body;
667 // Only add additional data when there is no picture in the post
668 if (!strstr($item["body"], '[/img]')) {
669 $item["body"] = add_page_info_to_body($item["body"]);
672 // Mastodon Content Warning
673 if (($item["verb"] == ACTIVITY_POST) && $xpath->evaluate('boolean(atom:summary)', $entry)) {
674 $clear_text = XML::getFirstNodeValue($xpath, 'atom:summary/text()', $entry);
675 if (!empty($clear_text)) {
676 $item['content-warning'] = HTML::toBBCode($clear_text);
680 if (($self != '') && empty($item['protocol'])) {
681 self::fetchSelf($self, $item);
684 if (!empty($item["conversation-href"])) {
685 self::fetchConversation($item['conversation-href'], $item['conversation-uri']);
688 if (isset($item["parent-uri"])) {
689 if (!Item::exists(['uid' => $importer["uid"], 'uri' => $item['parent-uri']])) {
690 if ($related != '') {
691 self::fetchRelated($related, $item["parent-uri"], $importer);
694 logger('Reply with URI '.$item["uri"].' already existed for user '.$importer["uid"].'.', LOGGER_DEBUG);
697 $item["parent-uri"] = $item["uri"];
698 $item["gravity"] = GRAVITY_PARENT;
699 $item["type"] = "remote";
702 if (($item['author-link'] != '') && !empty($item['protocol'])) {
703 $item = Conversation::insert($item);
706 self::$itemlist[] = $item;
710 * @brief Fetch the conversation for posts
712 * @param string $conversation The link to the conversation
713 * @param string $conversation_uri The conversation in "uri" format
716 private static function fetchConversation($conversation, $conversation_uri)
718 // Ensure that we only store a conversation once in a process
719 if (isset(self::$conv_list[$conversation])) {
723 self::$conv_list[$conversation] = true;
725 $conversation_data = Network::curl($conversation, false, $redirects, ['accept_content' => 'application/atom+xml, text/html']);
727 if (!$conversation_data['success']) {
733 if (stristr($conversation_data['header'], 'Content-Type: application/atom+xml')) {
734 $xml = $conversation_data['body'];
738 $doc = new DOMDocument();
739 if (!@$doc->loadHTML($conversation_data['body'])) {
742 $xpath = new DOMXPath($doc);
744 $links = $xpath->query('//link');
747 foreach ($links as $link) {
748 $attribute = self::readAttributes($link);
749 if (($attribute['rel'] == 'alternate') && ($attribute['type'] == 'application/atom+xml')) {
750 $file = $attribute['href'];
754 $conversation_atom = Network::curl($attribute['href']);
756 if ($conversation_atom['success']) {
757 $xml = $conversation_atom['body'];
767 self::storeConversation($xml, $conversation, $conversation_uri);
771 * @brief Store a feed in several conversation entries
773 * @param string $xml The feed
774 * @param string $conversation conversation
775 * @param string $conversation_uri conversation uri
778 private static function storeConversation($xml, $conversation = '', $conversation_uri = '')
780 $doc = new DOMDocument();
781 @$doc->loadXML($xml);
783 $xpath = new DOMXPath($doc);
784 $xpath->registerNamespace('atom', NAMESPACE_ATOM1);
785 $xpath->registerNamespace('thr', NAMESPACE_THREAD);
786 $xpath->registerNamespace('ostatus', NAMESPACE_OSTATUS);
788 $entries = $xpath->query('/atom:feed/atom:entry');
790 // Now store the entries
791 foreach ($entries as $entry) {
792 $doc2 = new DOMDocument();
793 $doc2->preserveWhiteSpace = false;
794 $doc2->formatOutput = true;
798 $conv_data['protocol'] = PROTOCOL_SPLITTED_CONV;
799 $conv_data['network'] = NETWORK_OSTATUS;
800 $conv_data['uri'] = XML::getFirstNodeValue($xpath, 'atom:id/text()', $entry);
802 $inreplyto = $xpath->query('thr:in-reply-to', $entry);
803 if (is_object($inreplyto->item(0))) {
804 foreach ($inreplyto->item(0)->attributes as $attributes) {
805 if ($attributes->name == "ref") {
806 $conv_data['reply-to-uri'] = $attributes->textContent;
811 $conv_data['conversation-uri'] = XML::getFirstNodeValue($xpath, 'ostatus:conversation/text()', $entry);
813 $conv = $xpath->query('ostatus:conversation', $entry);
814 if (is_object($conv->item(0))) {
815 foreach ($conv->item(0)->attributes as $attributes) {
816 if ($attributes->name == "ref") {
817 $conv_data['conversation-uri'] = $attributes->textContent;
819 if ($attributes->name == "href") {
820 $conv_data['conversation-href'] = $attributes->textContent;
825 if ($conversation != '') {
826 $conv_data['conversation-uri'] = $conversation;
829 if ($conversation_uri != '') {
830 $conv_data['conversation-uri'] = $conversation_uri;
833 $entry = $doc2->importNode($entry, true);
835 $doc2->appendChild($entry);
837 $conv_data['source'] = $doc2->saveXML();
839 $condition = ['item-uri' => $conv_data['uri'],'protocol' => PROTOCOL_OSTATUS_FEED];
840 if (dba::exists('conversation', $condition)) {
841 logger('Delete deprecated entry for URI '.$conv_data['uri'], LOGGER_DEBUG);
842 dba::delete('conversation', ['item-uri' => $conv_data['uri']]);
845 logger('Store conversation data for uri '.$conv_data['uri'], LOGGER_DEBUG);
846 Conversation::insert($conv_data);
851 * @brief Fetch the own post so that it can be stored later
853 * We want to store the original data for later processing.
854 * This function is meant for cases where we process a feed with multiple entries.
855 * In that case we need to fetch the single posts here.
857 * @param string $self The link to the self item
858 * @param array $item The item array
861 private static function fetchSelf($self, &$item)
863 $condition = ['`item-uri` = ? AND `protocol` IN (?, ?)', $self, PROTOCOL_DFRN, PROTOCOL_OSTATUS_SALMON];
864 if (dba::exists('conversation', $condition)) {
865 logger('Conversation '.$item['uri'].' is already stored.', LOGGER_DEBUG);
869 $self_data = Network::curl($self);
871 if (!$self_data['success']) {
875 // We reformat the XML to make it better readable
876 $doc = new DOMDocument();
877 $doc->loadXML($self_data['body']);
878 $doc->preserveWhiteSpace = false;
879 $doc->formatOutput = true;
880 $xml = $doc->saveXML();
882 $item["protocol"] = PROTOCOL_OSTATUS_SALMON;
883 $item["source"] = $xml;
885 logger('Conversation '.$item['uri'].' is now fetched.', LOGGER_DEBUG);
889 * @brief Fetch related posts and processes them
891 * @param string $related The link to the related item
892 * @param string $related_uri The related item in "uri" format
893 * @param array $importer user record of the importing user
896 private static function fetchRelated($related, $related_uri, $importer)
898 $condition = ['`item-uri` = ? AND `protocol` IN (?, ?)', $related_uri, PROTOCOL_DFRN, PROTOCOL_OSTATUS_SALMON];
899 $conversation = dba::selectFirst('conversation', ['source', 'protocol'], $condition);
900 if (DBM::is_result($conversation)) {
902 $xml = $conversation['source'];
903 if (self::process($xml, $importer, $contact, $hub, $stored, false)) {
904 logger('Got valid cached XML for URI '.$related_uri, LOGGER_DEBUG);
907 if ($conversation['protocol'] == PROTOCOL_OSTATUS_SALMON) {
908 logger('Delete invalid cached XML for URI '.$related_uri, LOGGER_DEBUG);
909 dba::delete('conversation', ['item-uri' => $related_uri]);
914 $related_data = Network::curl($related, false, $redirects, ['accept_content' => 'application/atom+xml, text/html']);
916 if (!$related_data['success']) {
922 if (stristr($related_data['header'], 'Content-Type: application/atom+xml')) {
923 logger('Directly fetched XML for URI '.$related_uri, LOGGER_DEBUG);
924 $xml = $related_data['body'];
928 $doc = new DOMDocument();
929 if (!@$doc->loadHTML($related_data['body'])) {
932 $xpath = new DOMXPath($doc);
936 $links = $xpath->query('//link');
938 foreach ($links as $link) {
939 $attribute = self::readAttributes($link);
940 if (($attribute['rel'] == 'alternate') && ($attribute['type'] == 'application/atom+xml')) {
941 $atom_file = $attribute['href'];
944 if ($atom_file != '') {
945 $related_atom = Network::curl($atom_file);
947 if ($related_atom['success']) {
948 logger('Fetched XML for URI '.$related_uri, LOGGER_DEBUG);
949 $xml = $related_atom['body'];
955 // Workaround for older GNU Social servers
956 if (($xml == '') && strstr($related, '/notice/')) {
957 $related_atom = Network::curl(str_replace('/notice/', '/api/statuses/show/', $related).'.atom');
959 if ($related_atom['success']) {
960 logger('GNU Social workaround to fetch XML for URI '.$related_uri, LOGGER_DEBUG);
961 $xml = $related_atom['body'];
965 // Even more worse workaround for GNU Social ;-)
967 $related_guess = OStatus::convertHref($related_uri);
968 $related_atom = Network::curl(str_replace('/notice/', '/api/statuses/show/', $related_guess).'.atom');
970 if ($related_atom['success']) {
971 logger('GNU Social workaround 2 to fetch XML for URI '.$related_uri, LOGGER_DEBUG);
972 $xml = $related_atom['body'];
976 // Finally we take the data that we fetched from "ostatus:conversation"
978 $condition = ['item-uri' => $related_uri, 'protocol' => PROTOCOL_SPLITTED_CONV];
979 $conversation = dba::selectFirst('conversation', ['source'], $condition);
980 if (DBM::is_result($conversation)) {
982 logger('Got cached XML from conversation for URI '.$related_uri, LOGGER_DEBUG);
983 $xml = $conversation['source'];
988 self::process($xml, $importer, $contact, $hub, $stored, false);
990 logger("XML couldn't be fetched for URI: ".$related_uri." - href: ".$related, LOGGER_DEBUG);
996 * @brief Processes the XML for a repeated post
998 * @param object $xpath The xpath object
999 * @param object $entry The xml entry that is processed
1000 * @param array $item The item array
1001 * @param array $importer user record of the importing user
1003 * @return array with data from links
1005 private static function processRepeatedItem($xpath, $entry, &$item, $importer)
1007 $activityobjects = $xpath->query('activity:object', $entry)->item(0);
1009 if (!is_object($activityobjects)) {
1015 $orig_uri = XML::getFirstNodeValue($xpath, 'atom:id/text()', $activityobjects);
1017 $links = $xpath->query("atom:link", $activityobjects);
1019 $link_data = self::processLinks($links, $item);
1022 $orig_body = XML::getFirstNodeValue($xpath, 'atom:content/text()', $activityobjects);
1023 $orig_created = XML::getFirstNodeValue($xpath, 'atom:published/text()', $activityobjects);
1024 $orig_edited = XML::getFirstNodeValue($xpath, 'atom:updated/text()', $activityobjects);
1026 $orig_author = self::fetchAuthor($xpath, $activityobjects, $importer, $dummy, false);
1028 $item["author-name"] = $orig_author["author-name"];
1029 $item["author-link"] = $orig_author["author-link"];
1030 $item["author-id"] = $orig_author["author-id"];
1032 $item["body"] = HTML::toBBCode($orig_body);
1033 $item["created"] = $orig_created;
1034 $item["edited"] = $orig_edited;
1036 $item["uri"] = $orig_uri;
1038 $item["verb"] = XML::getFirstNodeValue($xpath, 'activity:verb/text()', $activityobjects);
1040 $item["object-type"] = XML::getFirstNodeValue($xpath, 'activity:object-type/text()', $activityobjects);
1042 $inreplyto = $xpath->query('thr:in-reply-to', $activityobjects);
1043 if (is_object($inreplyto->item(0))) {
1044 foreach ($inreplyto->item(0)->attributes as $attributes) {
1045 if ($attributes->name == "ref") {
1046 $item["parent-uri"] = $attributes->textContent;
1055 * @brief Processes links in the XML
1057 * @param object $links The xml data that contain links
1058 * @param array $item The item array
1060 * @return array with data from the links
1062 private static function processLinks($links, &$item)
1064 $link_data = ['add_body' => '', 'self' => ''];
1066 foreach ($links as $link) {
1067 $attribute = self::readAttributes($link);
1069 if (!empty($attribute['rel']) && !empty($attribute['href'])) {
1070 switch ($attribute['rel']) {
1072 $item["plink"] = $attribute['href'];
1073 if (($item["object-type"] == ACTIVITY_OBJ_QUESTION)
1074 || ($item["object-type"] == ACTIVITY_OBJ_EVENT)
1076 $item["body"] .= add_page_info($attribute['href']);
1079 case "ostatus:conversation":
1080 $link_data['conversation'] = $attribute['href'];
1081 $item['conversation-href'] = $link_data['conversation'];
1082 if (!isset($item['conversation-uri'])) {
1083 $item['conversation-uri'] = $item['conversation-href'];
1087 $filetype = strtolower(substr($attribute['type'], 0, strpos($attribute['type'], '/')));
1088 if ($filetype == 'image') {
1089 $link_data['add_body'] .= "\n[img]".$attribute['href'].'[/img]';
1091 if (!empty($item["attach"])) {
1092 $item["attach"] .= ',';
1094 $item["attach"] = '';
1096 if (!isset($attribute['length'])) {
1097 $attribute['length'] = "0";
1099 $item["attach"] .= '[attach]href="'.$attribute['href'].'" length="'.$attribute['length'].'" type="'.$attribute['type'].'" title="'.defaults($attribute, 'title', '').'"[/attach]';
1103 if ($item["object-type"] != ACTIVITY_OBJ_BOOKMARK) {
1104 if (!isset($item["parent-uri"])) {
1105 $item["parent-uri"] = $attribute['href'];
1107 $link_data['related'] = $attribute['href'];
1109 $item["body"] .= add_page_info($attribute['href']);
1113 if (empty($item["plink"])) {
1114 $item["plink"] = $attribute['href'];
1116 $link_data['self'] = $attribute['href'];
1125 * @brief Create an url out of an uri
1127 * @param string $href URI in the format "parameter1:parameter1:..."
1129 * @return string URL in the format http(s)://....
1131 public static function convertHref($href)
1133 $elements = explode(":", $href);
1135 if ((count($elements) <= 2) || ($elements[0] != "tag")) {
1139 $server = explode(",", $elements[1]);
1140 $conversation = explode("=", $elements[2]);
1142 if ((count($elements) == 4) && ($elements[2] == "post")) {
1143 return "http://".$server[0]."/notice/".$elements[3];
1146 if ((count($conversation) != 2) || ($conversation[1] =="")) {
1149 if ($elements[3] == "objectType=thread") {
1150 return "http://".$server[0]."/conversation/".$conversation[1];
1152 return "http://".$server[0]."/notice/".$conversation[1];
1158 * @brief Checks if the current post is a reshare
1160 * @param array $item The item array of thw post
1162 * @return string The guid if the post is a reshare
1164 private static function getResharedGuid($item)
1166 $body = trim($item["body"]);
1168 // Skip if it isn't a pure repeated messages
1169 // Does it start with a share?
1170 if (strpos($body, "[share") > 0) {
1174 // Does it end with a share?
1175 if (strlen($body) > (strrpos($body, "[/share]") + 8)) {
1179 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "$1", $body);
1180 // Skip if there is no shared message in there
1181 if ($body == $attributes) {
1186 preg_match("/guid='(.*?)'/ism", $attributes, $matches);
1187 if (!empty($matches[1])) {
1188 $guid = $matches[1];
1191 preg_match('/guid="(.*?)"/ism', $attributes, $matches);
1192 if (!empty($matches[1])) {
1193 $guid = $matches[1];
1200 * @brief Cleans the body of a post if it contains picture links
1202 * @param string $body The body
1204 * @return string The cleaned body
1206 private static function formatPicturePost($body)
1208 $siteinfo = BBCode::getAttachedData($body);
1210 if (($siteinfo["type"] == "photo")) {
1211 if (isset($siteinfo["preview"])) {
1212 $preview = $siteinfo["preview"];
1214 $preview = $siteinfo["image"];
1217 // Is it a remote picture? Then make a smaller preview here
1218 $preview = proxy_url($preview, false, PROXY_SIZE_SMALL);
1220 // Is it a local picture? Then make it smaller here
1221 $preview = str_replace(["-0.jpg", "-0.png"], ["-2.jpg", "-2.png"], $preview);
1222 $preview = str_replace(["-1.jpg", "-1.png"], ["-2.jpg", "-2.png"], $preview);
1224 if (isset($siteinfo["url"])) {
1225 $url = $siteinfo["url"];
1227 $url = $siteinfo["image"];
1230 $body = trim($siteinfo["text"])." [url]".$url."[/url]\n[img]".$preview."[/img]";
1237 * @brief Adds the header elements to the XML document
1239 * @param object $doc XML document
1240 * @param array $owner Contact data of the poster
1241 * @param string $filter The related feed filter (activity, posts or comments)
1243 * @return object header root element
1245 private static function addHeader($doc, $owner, $filter)
1249 $root = $doc->createElementNS(NAMESPACE_ATOM1, 'feed');
1250 $doc->appendChild($root);
1252 $root->setAttribute("xmlns:thr", NAMESPACE_THREAD);
1253 $root->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
1254 $root->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
1255 $root->setAttribute("xmlns:media", NAMESPACE_MEDIA);
1256 $root->setAttribute("xmlns:poco", NAMESPACE_POCO);
1257 $root->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
1258 $root->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
1259 $root->setAttribute("xmlns:mastodon", NAMESPACE_MASTODON);
1263 case 'activity': $title = L10n::t('%s\'s timeline', $owner['name']); break;
1264 case 'posts' : $title = L10n::t('%s\'s posts' , $owner['name']); break;
1265 case 'comments': $title = L10n::t('%s\'s comments', $owner['name']); break;
1268 $attributes = ["uri" => "https://friendi.ca", "version" => FRIENDICA_VERSION . "-" . DB_UPDATE_VERSION];
1269 XML::addElement($doc, $root, "generator", FRIENDICA_PLATFORM, $attributes);
1270 XML::addElement($doc, $root, "id", System::baseUrl() . "/profile/" . $owner["nick"]);
1271 XML::addElement($doc, $root, "title", $title);
1272 XML::addElement($doc, $root, "subtitle", sprintf("Updates from %s on %s", $owner["name"], $a->config["sitename"]));
1273 XML::addElement($doc, $root, "logo", $owner["photo"]);
1274 XML::addElement($doc, $root, "updated", DateTimeFormat::utcNow(DateTimeFormat::ATOM));
1276 $author = self::addAuthor($doc, $owner);
1277 $root->appendChild($author);
1279 $attributes = ["href" => $owner["url"], "rel" => "alternate", "type" => "text/html"];
1280 XML::addElement($doc, $root, "link", "", $attributes);
1282 /// @TODO We have to find out what this is
1283 /// $attributes = array("href" => System::baseUrl()."/sup",
1284 /// "rel" => "http://api.friendfeed.com/2008/03#sup",
1285 /// "type" => "application/json");
1286 /// XML::addElement($doc, $root, "link", "", $attributes);
1288 self::hublinks($doc, $root, $owner["nick"]);
1290 $attributes = ["href" => System::baseUrl() . "/salmon/" . $owner["nick"], "rel" => "salmon"];
1291 XML::addElement($doc, $root, "link", "", $attributes);
1293 $attributes = ["href" => System::baseUrl() . "/salmon/" . $owner["nick"], "rel" => "http://salmon-protocol.org/ns/salmon-replies"];
1294 XML::addElement($doc, $root, "link", "", $attributes);
1296 $attributes = ["href" => System::baseUrl() . "/salmon/" . $owner["nick"], "rel" => "http://salmon-protocol.org/ns/salmon-mention"];
1297 XML::addElement($doc, $root, "link", "", $attributes);
1299 $attributes = ["href" => System::baseUrl() . "/api/statuses/user_timeline/" . $owner["nick"] . ".atom",
1300 "rel" => "self", "type" => "application/atom+xml"];
1301 XML::addElement($doc, $root, "link", "", $attributes);
1303 if ($owner['account-type'] == ACCOUNT_TYPE_COMMUNITY) {
1304 $condition = ['uid' => $owner['uid'], 'self' => false, 'pending' => false,
1305 'archive' => false, 'hidden' => false, 'blocked' => false];
1306 $members = dba::count('contact', $condition);
1307 XML::addElement($doc, $root, "statusnet:group_info", "", ["member_count" => $members]);
1314 * @brief Add the link to the push hubs to the XML document
1316 * @param object $doc XML document
1317 * @param object $root XML root element where the hub links are added
1318 * @param object $nick nick
1321 public static function hublinks($doc, $root, $nick)
1323 $h = System::baseUrl() . '/pubsubhubbub/'.$nick;
1324 XML::addElement($doc, $root, "link", "", ["href" => $h, "rel" => "hub"]);
1328 * @brief Adds attachment data to the XML document
1330 * @param object $doc XML document
1331 * @param object $root XML root element where the hub links are added
1332 * @param array $item Data of the item that is to be posted
1335 private static function getAttachment($doc, $root, $item)
1338 $siteinfo = BBCode::getAttachedData($item["body"]);
1340 switch ($siteinfo["type"]) {
1342 $imgdata = Image::getInfoFromURL($siteinfo["image"]);
1344 $attributes = ["rel" => "enclosure",
1345 "href" => $siteinfo["image"],
1346 "type" => $imgdata["mime"],
1347 "length" => intval($imgdata["size"])];
1348 XML::addElement($doc, $root, "link", "", $attributes);
1352 $attributes = ["rel" => "enclosure",
1353 "href" => $siteinfo["url"],
1354 "type" => "text/html; charset=UTF-8",
1356 "title" => $siteinfo["title"]];
1357 XML::addElement($doc, $root, "link", "", $attributes);
1363 if (!Config::get('system', 'ostatus_not_attach_preview') && ($siteinfo["type"] != "photo") && isset($siteinfo["image"])) {
1364 $imgdata = Image::getInfoFromURL($siteinfo["image"]);
1366 $attributes = ["rel" => "enclosure",
1367 "href" => $siteinfo["image"],
1368 "type" => $imgdata["mime"],
1369 "length" => intval($imgdata["size"])];
1371 XML::addElement($doc, $root, "link", "", $attributes);
1375 $arr = explode('[/attach],', $item['attach']);
1377 foreach ($arr as $r) {
1379 $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"|', $r, $matches);
1381 $attributes = ["rel" => "enclosure",
1382 "href" => $matches[1],
1383 "type" => $matches[3]];
1385 if (intval($matches[2])) {
1386 $attributes["length"] = intval($matches[2]);
1388 if (trim($matches[4]) != "") {
1389 $attributes["title"] = trim($matches[4]);
1391 XML::addElement($doc, $root, "link", "", $attributes);
1398 * @brief Adds the author element to the XML document
1400 * @param object $doc XML document
1401 * @param array $owner Contact data of the poster
1403 * @return object author element
1405 private static function addAuthor($doc, $owner, $show_profile = true)
1407 $profile = dba::selectFirst('profile', ['homepage', 'publish'], ['uid' => $owner['uid'], 'is-default' => true]);
1408 $author = $doc->createElement("author");
1409 XML::addElement($doc, $author, "id", $owner["url"]);
1410 if ($owner['account-type'] == ACCOUNT_TYPE_COMMUNITY) {
1411 XML::addElement($doc, $author, "activity:object-type", ACTIVITY_OBJ_GROUP);
1413 XML::addElement($doc, $author, "activity:object-type", ACTIVITY_OBJ_PERSON);
1415 XML::addElement($doc, $author, "uri", $owner["url"]);
1416 XML::addElement($doc, $author, "name", $owner["nick"]);
1417 XML::addElement($doc, $author, "email", $owner["addr"]);
1418 if ($show_profile) {
1419 XML::addElement($doc, $author, "summary", BBCode::convert($owner["about"], false, 7));
1422 $attributes = ["rel" => "alternate", "type" => "text/html", "href" => $owner["url"]];
1423 XML::addElement($doc, $author, "link", "", $attributes);
1427 "type" => "image/jpeg", // To-Do?
1428 "media:width" => 175,
1429 "media:height" => 175,
1430 "href" => $owner["photo"]];
1431 XML::addElement($doc, $author, "link", "", $attributes);
1433 if (isset($owner["thumb"])) {
1436 "type" => "image/jpeg", // To-Do?
1437 "media:width" => 80,
1438 "media:height" => 80,
1439 "href" => $owner["thumb"]];
1440 XML::addElement($doc, $author, "link", "", $attributes);
1443 XML::addElement($doc, $author, "poco:preferredUsername", $owner["nick"]);
1444 XML::addElement($doc, $author, "poco:displayName", $owner["name"]);
1445 if ($show_profile) {
1446 XML::addElement($doc, $author, "poco:note", BBCode::convert($owner["about"], false, 7));
1448 if (trim($owner["location"]) != "") {
1449 $element = $doc->createElement("poco:address");
1450 XML::addElement($doc, $element, "poco:formatted", $owner["location"]);
1451 $author->appendChild($element);
1455 if (DBM::is_result($profile) && !$show_profile) {
1456 if (trim($profile["homepage"]) != "") {
1457 $urls = $doc->createElement("poco:urls");
1458 XML::addElement($doc, $urls, "poco:type", "homepage");
1459 XML::addElement($doc, $urls, "poco:value", $profile["homepage"]);
1460 XML::addElement($doc, $urls, "poco:primary", "true");
1461 $author->appendChild($urls);
1464 XML::addElement($doc, $author, "followers", "", ["url" => System::baseUrl()."/viewcontacts/".$owner["nick"]]);
1465 XML::addElement($doc, $author, "statusnet:profile_info", "", ["local_id" => $owner["uid"]]);
1467 if ($profile["publish"]) {
1468 XML::addElement($doc, $author, "mastodon:scope", "public");
1476 * @TODO Picture attachments should look like this:
1477 * <a href="https://status.pirati.ca/attachment/572819" title="https://status.pirati.ca/file/heluecht-20151202T222602-rd3u49p.gif"
1478 * class="attachment thumbnail" id="attachment-572819" rel="nofollow external">https://status.pirati.ca/attachment/572819</a>
1482 * @brief Returns the given activity if present - otherwise returns the "post" activity
1484 * @param array $item Data of the item that is to be posted
1486 * @return string activity
1488 private static function constructVerb($item)
1490 if ($item['verb']) {
1491 return $item['verb'];
1494 return ACTIVITY_POST;
1498 * @brief Returns the given object type if present - otherwise returns the "note" object type
1500 * @param array $item Data of the item that is to be posted
1502 * @return string Object type
1504 private static function constructObjecttype($item)
1506 if (in_array($item['object-type'], [ACTIVITY_OBJ_NOTE, ACTIVITY_OBJ_COMMENT]))
1507 return $item['object-type'];
1508 return ACTIVITY_OBJ_NOTE;
1512 * @brief Adds an entry element to the XML document
1514 * @param object $doc XML document
1515 * @param array $item Data of the item that is to be posted
1516 * @param array $owner Contact data of the poster
1517 * @param bool $toplevel optional default false
1519 * @return object Entry element
1521 private static function entry($doc, $item, $owner, $toplevel = false)
1525 $repeated_guid = self::getResharedGuid($item);
1526 if ($repeated_guid != "") {
1527 $xml = self::reshareEntry($doc, $item, $owner, $repeated_guid, $toplevel);
1534 if ($item["verb"] == ACTIVITY_LIKE) {
1535 return self::likeEntry($doc, $item, $owner, $toplevel);
1536 } elseif (in_array($item["verb"], [ACTIVITY_FOLLOW, NAMESPACE_OSTATUS."/unfollow"])) {
1537 return self::followEntry($doc, $item, $owner, $toplevel);
1539 return self::noteEntry($doc, $item, $owner, $toplevel);
1544 * @brief Adds a source entry to the XML document
1546 * @param object $doc XML document
1547 * @param array $contact Array of the contact that is added
1549 * @return object Source element
1551 private static function sourceEntry($doc, $contact)
1553 $source = $doc->createElement("source");
1554 XML::addElement($doc, $source, "id", $contact["poll"]);
1555 XML::addElement($doc, $source, "title", $contact["name"]);
1556 XML::addElement($doc, $source, "link", "", ["rel" => "alternate", "type" => "text/html", "href" => $contact["alias"]]);
1557 XML::addElement($doc, $source, "link", "", ["rel" => "self", "type" => "application/atom+xml", "href" => $contact["poll"]]);
1558 XML::addElement($doc, $source, "icon", $contact["photo"]);
1559 XML::addElement($doc, $source, "updated", DateTimeFormat::utc($contact["success_update"]."+00:00", DateTimeFormat::ATOM));
1565 * @brief Fetches contact data from the contact or the gcontact table
1567 * @param string $url URL of the contact
1568 * @param array $owner Contact data of the poster
1570 * @return array Contact array
1572 private static function contactEntry($url, $owner)
1575 "SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` IN (0, %d) ORDER BY `uid` DESC LIMIT 1",
1576 dbesc(normalise_link($url)),
1577 intval($owner["uid"])
1579 if (DBM::is_result($r)) {
1581 $contact["uid"] = -1;
1584 if (!DBM::is_result($r)) {
1586 "SELECT * FROM `gcontact` WHERE `nurl` = '%s' LIMIT 1",
1587 dbesc(normalise_link($url))
1589 if (DBM::is_result($r)) {
1591 $contact["uid"] = -1;
1592 $contact["success_update"] = $contact["updated"];
1596 if (!DBM::is_result($r)) {
1600 if (!isset($contact["poll"])) {
1601 $data = Probe::uri($url);
1602 $contact["poll"] = $data["poll"];
1604 if (!$contact["alias"]) {
1605 $contact["alias"] = $data["alias"];
1609 if (!isset($contact["alias"])) {
1610 $contact["alias"] = $contact["url"];
1617 * @brief Adds an entry element with reshared content
1619 * @param object $doc XML document
1620 * @param array $item Data of the item that is to be posted
1621 * @param array $owner Contact data of the poster
1622 * @param string $repeated_guid guid
1623 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1625 * @return object Entry element
1627 private static function reshareEntry($doc, $item, $owner, $repeated_guid, $toplevel)
1629 if (($item["id"] != $item["parent"]) && (normalise_link($item["author-link"]) != normalise_link($owner["url"]))) {
1630 logger("OStatus entry is from author ".$owner["url"]." - not from ".$item["author-link"].". Quitting.", LOGGER_DEBUG);
1633 $title = self::entryHeader($doc, $entry, $owner, $item, $toplevel);
1635 $condition = ['uid' => $owner["uid"], 'guid' => $repeated_guid, 'private' => false,
1636 'network' => [NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS]];
1637 $repeated_item = Item::selectFirst([], $condition);
1638 if (!DBM::is_result($repeated_item)) {
1642 $contact = self::contactEntry($repeated_item['author-link'], $owner);
1643 $contact['account-type'] = $contact['contact-type'];
1645 $title = $owner["nick"]." repeated a notice by ".$contact["nick"];
1647 self::entryContent($doc, $entry, $item, $owner, $title, ACTIVITY_SHARE, false);
1649 $as_object = $doc->createElement("activity:object");
1651 XML::addElement($doc, $as_object, "activity:object-type", NAMESPACE_ACTIVITY_SCHEMA."activity");
1653 self::entryContent($doc, $as_object, $repeated_item, $owner, "", "", false);
1655 $author = self::addAuthor($doc, $contact, false);
1656 $as_object->appendChild($author);
1658 $as_object2 = $doc->createElement("activity:object");
1660 XML::addElement($doc, $as_object2, "activity:object-type", self::constructObjecttype($repeated_item));
1662 $title = sprintf("New comment by %s", $contact["nick"]);
1664 self::entryContent($doc, $as_object2, $repeated_item, $owner, $title);
1666 $as_object->appendChild($as_object2);
1668 self::entryFooter($doc, $as_object, $item, $owner, false);
1670 $source = self::sourceEntry($doc, $contact);
1672 $as_object->appendChild($source);
1674 $entry->appendChild($as_object);
1676 self::entryFooter($doc, $entry, $item, $owner);
1682 * @brief Adds an entry element with a "like"
1684 * @param object $doc XML document
1685 * @param array $item Data of the item that is to be posted
1686 * @param array $owner Contact data of the poster
1687 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1689 * @return object Entry element with "like"
1691 private static function likeEntry($doc, $item, $owner, $toplevel)
1693 if (($item["id"] != $item["parent"]) && (normalise_link($item["author-link"]) != normalise_link($owner["url"]))) {
1694 logger("OStatus entry is from author ".$owner["url"]." - not from ".$item["author-link"].". Quitting.", LOGGER_DEBUG);
1697 $title = self::entryHeader($doc, $entry, $owner, $item, $toplevel);
1699 $verb = NAMESPACE_ACTIVITY_SCHEMA."favorite";
1700 self::entryContent($doc, $entry, $item, $owner, "Favorite", $verb, false);
1702 $as_object = $doc->createElement("activity:object");
1704 $parent = Item::selectFirst([], ['uri' => $item["thr-parent"], 'uid' => $item["uid"]]);
1706 XML::addElement($doc, $as_object, "activity:object-type", self::constructObjecttype($parent));
1708 self::entryContent($doc, $as_object, $parent, $owner, "New entry");
1710 $entry->appendChild($as_object);
1712 self::entryFooter($doc, $entry, $item, $owner);
1718 * @brief Adds the person object element to the XML document
1720 * @param object $doc XML document
1721 * @param array $owner Contact data of the poster
1722 * @param array $contact Contact data of the target
1724 * @return object author element
1726 private static function addPersonObject($doc, $owner, $contact)
1728 $object = $doc->createElement("activity:object");
1729 XML::addElement($doc, $object, "activity:object-type", ACTIVITY_OBJ_PERSON);
1731 if ($contact['network'] == NETWORK_PHANTOM) {
1732 XML::addElement($doc, $object, "id", $contact['url']);
1736 XML::addElement($doc, $object, "id", $contact["alias"]);
1737 XML::addElement($doc, $object, "title", $contact["nick"]);
1739 $attributes = ["rel" => "alternate", "type" => "text/html", "href" => $contact["url"]];
1740 XML::addElement($doc, $object, "link", "", $attributes);
1744 "type" => "image/jpeg", // To-Do?
1745 "media:width" => 175,
1746 "media:height" => 175,
1747 "href" => $contact["photo"]];
1748 XML::addElement($doc, $object, "link", "", $attributes);
1750 XML::addElement($doc, $object, "poco:preferredUsername", $contact["nick"]);
1751 XML::addElement($doc, $object, "poco:displayName", $contact["name"]);
1753 if (trim($contact["location"]) != "") {
1754 $element = $doc->createElement("poco:address");
1755 XML::addElement($doc, $element, "poco:formatted", $contact["location"]);
1756 $object->appendChild($element);
1763 * @brief Adds a follow/unfollow entry element
1765 * @param object $doc XML document
1766 * @param array $item Data of the follow/unfollow message
1767 * @param array $owner Contact data of the poster
1768 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1770 * @return object Entry element
1772 private static function followEntry($doc, $item, $owner, $toplevel)
1774 $item["id"] = $item["parent"] = 0;
1775 $item["created"] = $item["edited"] = date("c");
1776 $item["private"] = true;
1778 $contact = Probe::uri($item['follow']);
1780 if ($contact['alias'] == '') {
1781 $contact['alias'] = $contact["url"];
1783 $item['follow'] = $contact['alias'];
1787 "SELECT `id` FROM `contact` WHERE `uid` = %d AND `nurl` = '%s'",
1788 intval($owner['uid']),
1789 dbesc(normalise_link($contact["url"]))
1792 if (DBM::is_result($r)) {
1793 $connect_id = $r[0]['id'];
1798 if ($item['verb'] == ACTIVITY_FOLLOW) {
1799 $message = L10n::t('%s is now following %s.');
1800 $title = L10n::t('following');
1801 $action = "subscription";
1803 $message = L10n::t('%s stopped following %s.');
1804 $title = L10n::t('stopped following');
1805 $action = "unfollow";
1808 $item["uri"] = $item['parent-uri'] = $item['thr-parent']
1809 = 'tag:'.get_app()->get_hostname().
1810 ','.date('Y-m-d').':'.$action.':'.$owner['uid'].
1811 ':person:'.$connect_id.':'.$item['created'];
1813 $item["body"] = sprintf($message, $owner["nick"], $contact["nick"]);
1815 self::entryHeader($doc, $entry, $owner, $item, $toplevel);
1817 self::entryContent($doc, $entry, $item, $owner, $title);
1819 $object = self::addPersonObject($doc, $owner, $contact);
1820 $entry->appendChild($object);
1822 self::entryFooter($doc, $entry, $item, $owner);
1828 * @brief Adds a regular entry element
1830 * @param object $doc XML document
1831 * @param array $item Data of the item that is to be posted
1832 * @param array $owner Contact data of the poster
1833 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1835 * @return object Entry element
1837 private static function noteEntry($doc, $item, $owner, $toplevel)
1839 if (($item["id"] != $item["parent"]) && (normalise_link($item["author-link"]) != normalise_link($owner["url"]))) {
1840 logger("OStatus entry is from author ".$owner["url"]." - not from ".$item["author-link"].". Quitting.", LOGGER_DEBUG);
1843 $title = self::entryHeader($doc, $entry, $owner, $item, $toplevel);
1845 XML::addElement($doc, $entry, "activity:object-type", ACTIVITY_OBJ_NOTE);
1847 self::entryContent($doc, $entry, $item, $owner, $title);
1849 self::entryFooter($doc, $entry, $item, $owner);
1855 * @brief Adds a header element to the XML document
1857 * @param object $doc XML document
1858 * @param object $entry The entry element where the elements are added
1859 * @param array $owner Contact data of the poster
1860 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1862 * @return string The title for the element
1864 private static function entryHeader($doc, &$entry, $owner, $item, $toplevel)
1866 /// @todo Check if this title stuff is really needed (I guess not)
1868 $entry = $doc->createElement("entry");
1869 $title = sprintf("New note by %s", $owner["nick"]);
1871 if ($owner['account-type'] == ACCOUNT_TYPE_COMMUNITY) {
1872 $contact = self::contactEntry($item['author-link'], $owner);
1873 $author = self::addAuthor($doc, $contact, false);
1874 $entry->appendChild($author);
1877 $entry = $doc->createElementNS(NAMESPACE_ATOM1, "entry");
1879 $entry->setAttribute("xmlns:thr", NAMESPACE_THREAD);
1880 $entry->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
1881 $entry->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
1882 $entry->setAttribute("xmlns:media", NAMESPACE_MEDIA);
1883 $entry->setAttribute("xmlns:poco", NAMESPACE_POCO);
1884 $entry->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
1885 $entry->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
1886 $entry->setAttribute("xmlns:mastodon", NAMESPACE_MASTODON);
1888 $author = self::addAuthor($doc, $owner);
1889 $entry->appendChild($author);
1891 $title = sprintf("New comment by %s", $owner["nick"]);
1897 * @brief Adds elements to the XML document
1899 * @param object $doc XML document
1900 * @param object $entry Entry element where the content is added
1901 * @param array $item Data of the item that is to be posted
1902 * @param array $owner Contact data of the poster
1903 * @param string $title Title for the post
1904 * @param string $verb The activity verb
1905 * @param bool $complete Add the "status_net" element?
1908 private static function entryContent($doc, $entry, $item, $owner, $title, $verb = "", $complete = true)
1911 $verb = self::constructVerb($item);
1914 XML::addElement($doc, $entry, "id", $item["uri"]);
1915 XML::addElement($doc, $entry, "title", $title);
1917 $body = self::formatPicturePost($item['body']);
1919 if ($item['title'] != "") {
1920 $body = "[b]".$item['title']."[/b]\n\n".$body;
1923 $body = BBCode::convert($body, false, 7);
1925 XML::addElement($doc, $entry, "content", $body, ["type" => "html"]);
1927 XML::addElement($doc, $entry, "link", "", ["rel" => "alternate", "type" => "text/html",
1928 "href" => System::baseUrl()."/display/".$item["guid"]]
1931 if ($complete && ($item["id"] > 0)) {
1932 XML::addElement($doc, $entry, "status_net", "", ["notice_id" => $item["id"]]);
1935 XML::addElement($doc, $entry, "activity:verb", $verb);
1937 XML::addElement($doc, $entry, "published", DateTimeFormat::utc($item["created"]."+00:00", DateTimeFormat::ATOM));
1938 XML::addElement($doc, $entry, "updated", DateTimeFormat::utc($item["edited"]."+00:00", DateTimeFormat::ATOM));
1942 * @brief Adds the elements at the foot of an entry to the XML document
1944 * @param object $doc XML document
1945 * @param object $entry The entry element where the elements are added
1946 * @param array $item Data of the item that is to be posted
1947 * @param array $owner Contact data of the poster
1948 * @param bool $complete default true
1951 private static function entryFooter($doc, $entry, array $item, array $owner, $complete = true)
1955 if (($item['parent'] != $item['id']) || ($item['parent-uri'] !== $item['uri']) || (($item['thr-parent'] !== '') && ($item['thr-parent'] !== $item['uri']))) {
1956 $parent = Item::selectFirst(['guid', 'author-link', 'owner-link'], ['id' => $item["parent"]]);
1957 $parent_item = (($item['thr-parent']) ? $item['thr-parent'] : $item['parent-uri']);
1959 $thrparent = Item::selectFirst(['guid', 'author-link', 'owner-link', 'plink'], ['uid' => $owner["uid"], 'uri' => $parent_item]);
1961 if (DBM::is_result($thrparent)) {
1962 $mentioned[$thrparent["author-link"]] = $thrparent["author-link"];
1963 $mentioned[$thrparent["owner-link"]] = $thrparent["owner-link"];
1964 $parent_plink = $thrparent["plink"];
1966 $mentioned[$parent["author-link"]] = $parent["author-link"];
1967 $mentioned[$parent["owner-link"]] = $parent["owner-link"];
1968 $parent_plink = System::baseUrl()."/display/".$parent["guid"];
1972 "ref" => $parent_item,
1973 "href" => $parent_plink];
1974 XML::addElement($doc, $entry, "thr:in-reply-to", "", $attributes);
1978 "href" => $parent_plink];
1979 XML::addElement($doc, $entry, "link", "", $attributes);
1982 if (intval($item["parent"]) > 0) {
1983 $conversation_href = System::baseUrl()."/display/".$owner["nick"]."/".$item["parent"];
1984 $conversation_uri = $conversation_href;
1986 if (isset($parent_item)) {
1987 $conversation = dba::selectFirst('conversation', ['conversation-uri', 'conversation-href'], ['item-uri' => $parent_item]);
1988 if (DBM::is_result($conversation)) {
1989 if ($conversation['conversation-uri'] != '') {
1990 $conversation_uri = $conversation['conversation-uri'];
1992 if ($conversation['conversation-href'] != '') {
1993 $conversation_href = $conversation['conversation-href'];
1998 XML::addElement($doc, $entry, "link", "", ["rel" => "ostatus:conversation", "href" => $conversation_href]);
2001 "href" => $conversation_href,
2002 "local_id" => $item["parent"],
2003 "ref" => $conversation_uri];
2005 XML::addElement($doc, $entry, "ostatus:conversation", $conversation_uri, $attributes);
2008 $tags = item::getFeedTags($item);
2011 foreach ($tags as $t) {
2013 $mentioned[$t[1]] = $t[1];
2018 // Make sure that mentions are accepted (GNU Social has problems with mixing HTTP and HTTPS)
2020 foreach ($mentioned as $mention) {
2021 $newmentions[str_replace("http://", "https://", $mention)] = str_replace("http://", "https://", $mention);
2022 $newmentions[str_replace("https://", "http://", $mention)] = str_replace("https://", "http://", $mention);
2024 $mentioned = $newmentions;
2026 foreach ($mentioned as $mention) {
2027 $condition = ['uid' => $owner['uid'], 'nurl' => normalise_link($mention)];
2028 $contact = dba::selectFirst('contact', ['forum', 'prv', 'self', 'contact-type'], $condition);
2029 if ($contact["forum"] || $contact["prv"] || ($owner['contact-type'] == ACCOUNT_TYPE_COMMUNITY) ||
2030 ($contact['self'] && ($owner['account-type'] == ACCOUNT_TYPE_COMMUNITY))) {
2031 XML::addElement($doc, $entry, "link", "",
2033 "rel" => "mentioned",
2034 "ostatus:object-type" => ACTIVITY_OBJ_GROUP,
2038 XML::addElement($doc, $entry, "link", "",
2040 "rel" => "mentioned",
2041 "ostatus:object-type" => ACTIVITY_OBJ_PERSON,
2047 if ($owner['account-type'] == ACCOUNT_TYPE_COMMUNITY) {
2048 XML::addElement($doc, $entry, "link", "", [
2049 "rel" => "mentioned",
2050 "ostatus:object-type" => "http://activitystrea.ms/schema/1.0/group",
2051 "href" => $owner['url']
2055 if (!$item["private"]) {
2056 XML::addElement($doc, $entry, "link", "", ["rel" => "ostatus:attention",
2057 "href" => "http://activityschema.org/collection/public"]);
2058 XML::addElement($doc, $entry, "link", "", ["rel" => "mentioned",
2059 "ostatus:object-type" => "http://activitystrea.ms/schema/1.0/collection",
2060 "href" => "http://activityschema.org/collection/public"]);
2061 XML::addElement($doc, $entry, "mastodon:scope", "public");
2065 foreach ($tags as $t) {
2067 XML::addElement($doc, $entry, "category", "", ["term" => $t[2]]);
2072 self::getAttachment($doc, $entry, $item);
2074 if ($complete && ($item["id"] > 0)) {
2075 $app = $item["app"];
2080 $attributes = ["local_id" => $item["id"], "source" => $app];
2082 if (isset($parent["id"])) {
2083 $attributes["repeat_of"] = $parent["id"];
2086 if ($item["coord"] != "") {
2087 XML::addElement($doc, $entry, "georss:point", $item["coord"]);
2090 XML::addElement($doc, $entry, "statusnet:notice_info", "", $attributes);
2095 * Creates the XML feed for a given nickname
2097 * Supported filters:
2098 * - activity (default): all the public posts
2099 * - posts: all the public top-level posts
2100 * - comments: all the public replies
2102 * Updates the provided last_update parameter if the result comes from the
2103 * cache or it is empty
2105 * @brief Creates the XML feed for a given nickname
2107 * @param string $owner_nick Nickname of the feed owner
2108 * @param string $last_update Date of the last update
2109 * @param integer $max_items Number of maximum items to fetch
2110 * @param string $filter Feed items filter (activity, posts or comments)
2111 * @param boolean $nocache Wether to bypass caching
2113 * @return string XML feed
2115 public static function feed($owner_nick, &$last_update, $max_items = 300, $filter = 'activity', $nocache = false)
2117 $stamp = microtime(true);
2119 $owner = User::getOwnerDataByNick($owner_nick);
2124 $cachekey = "ostatus:feed:" . $owner_nick . ":" . $filter . ":" . $last_update;
2126 $previous_created = $last_update;
2128 // Don't cache when the last item was posted less then 15 minutes ago (Cache duration)
2129 if ((time() - strtotime($owner['last-item'])) < 15*60) {
2130 $result = Cache::get($cachekey);
2131 if (!$nocache && !is_null($result)) {
2132 logger('Feed duration: ' . number_format(microtime(true) - $stamp, 3) . ' - ' . $owner_nick . ' - ' . $filter . ' - ' . $previous_created . ' (cached)', LOGGER_DEBUG);
2133 $last_update = $result['last_update'];
2134 return $result['feed'];
2138 if (!strlen($last_update)) {
2139 $last_update = 'now -30 days';
2142 $check_date = DateTimeFormat::utc($last_update);
2143 $authorid = Contact::getIdForURL($owner["url"], 0, true);
2145 $condition = ["`uid` = ? AND `created` > ? AND NOT `deleted`
2146 AND NOT `private` AND `visible` AND `wall` AND `parent-network` IN (?, ?)",
2147 $owner["uid"], $check_date, NETWORK_OSTATUS, NETWORK_DFRN];
2149 if ($filter === 'comments') {
2150 $condition[0] .= " AND `object-type` = ? ";
2151 $condition[] = ACTIVITY_OBJ_COMMENT;
2154 if ($owner['account-type'] != ACCOUNT_TYPE_COMMUNITY) {
2155 $condition[0] .= " AND `contact-id` = ? AND `author-id` = ?";
2156 $condition[] = $owner["id"];
2157 $condition[] = $authorid;
2160 $params = ['order' => ['created' => true], 'limit' => $max_items];
2162 if ($filter === 'posts') {
2163 $ret = Item::selectThread([], $condition, $params);
2165 $ret = Item::select([], $condition, $params);
2168 $items = Item::inArray($ret);
2170 $doc = new DOMDocument('1.0', 'utf-8');
2171 $doc->formatOutput = true;
2173 $root = self::addHeader($doc, $owner, $filter);
2175 foreach ($items as $item) {
2176 if (Config::get('system', 'ostatus_debug')) {
2177 $item['body'] .= '🍼';
2179 $entry = self::entry($doc, $item, $owner);
2180 $root->appendChild($entry);
2182 if ($last_update < $item['created']) {
2183 $last_update = $item['created'];
2187 $feeddata = trim($doc->saveXML());
2189 $msg = ['feed' => $feeddata, 'last_update' => $last_update];
2190 Cache::set($cachekey, $msg, CACHE_QUARTER_HOUR);
2192 logger('Feed duration: ' . number_format(microtime(true) - $stamp, 3) . ' - ' . $owner_nick . ' - ' . $filter . ' - ' . $previous_created, LOGGER_DEBUG);
2198 * @brief Creates the XML for a salmon message
2200 * @param array $item Data of the item that is to be posted
2201 * @param array $owner Contact data of the poster
2203 * @return string XML for the salmon
2205 public static function salmon($item, $owner)
2207 $doc = new DOMDocument('1.0', 'utf-8');
2208 $doc->formatOutput = true;
2210 if (Config::get('system', 'ostatus_debug')) {
2211 $item['body'] .= '🐟';
2214 $entry = self::entry($doc, $item, $owner, true);
2216 $doc->appendChild($entry);
2218 return trim($doc->saveXML());