3 * @file src/Protocol/OStatus.php
5 namespace Friendica\Protocol;
8 use Friendica\Core\Cache;
9 use Friendica\Core\Config;
10 use Friendica\Core\System;
11 use Friendica\Database\DBM;
12 use Friendica\Model\Contact;
13 use Friendica\Model\GContact;
14 use Friendica\Network\Probe;
15 use Friendica\Object\Image;
16 use Friendica\Util\Lock;
17 use Friendica\Util\XML;
22 require_once 'include/dba.php';
23 require_once 'include/threads.php';
24 require_once 'include/html2bbcode.php';
25 require_once 'include/bbcode.php';
26 require_once 'include/items.php';
27 require_once 'mod/share.php';
28 require_once 'include/enotify.php';
29 require_once 'include/follow.php';
30 require_once 'include/api.php';
31 require_once 'mod/proxy.php';
34 * @brief This class contain functions for the OStatus protocol
38 private static $itemlist;
39 private static $conv_list = array();
42 * @brief Fetches author data
44 * @param object $xpath The xpath object
45 * @param object $context The xml context of the author details
46 * @param array $importer user record of the importing user
47 * @param array $contact Called by reference, will contain the fetched contact
48 * @param bool $onlyfetch Only fetch the header without updating the contact entries
50 * @return array Array of author related entries for the item
52 private static function fetchAuthor($xpath, $context, $importer, &$contact, $onlyfetch)
55 $author["author-link"] = $xpath->evaluate('atom:author/atom:uri/text()', $context)->item(0)->nodeValue;
56 $author["author-name"] = $xpath->evaluate('atom:author/atom:name/text()', $context)->item(0)->nodeValue;
57 $addr = $xpath->evaluate('atom:author/atom:email/text()', $context)->item(0)->nodeValue;
59 $aliaslink = $author["author-link"];
61 $alternate = $xpath->query("atom:author/atom:link[@rel='alternate']", $context)->item(0)->attributes;
62 if (is_object($alternate)) {
63 foreach ($alternate as $attributes) {
64 if (($attributes->name == "href") && ($attributes->textContent != "")) {
65 $author["author-link"] = $attributes->textContent;
69 $author["contact-id"] = $contact["id"];
73 if ($aliaslink != '') {
74 $condition = array("`uid` = ? AND `alias` = ? AND `network` != ?",
75 $importer["uid"], $aliaslink, NETWORK_STATUSNET);
76 $r = dba::select('contact', array(), $condition, array('limit' => 1));
78 if (DBM::is_result($r)) {
84 $author["contact-id"] = $r["id"];
88 if (!$found && ($author["author-link"] != "")) {
89 if ($aliaslink == "") {
90 $aliaslink = $author["author-link"];
93 $condition = array("`uid` = ? AND `nurl` IN (?, ?) AND `network` != ?", $importer["uid"],
94 normalise_link($author["author-link"]), normalise_link($aliaslink), NETWORK_STATUSNET);
95 $r = dba::select('contact', array(), $condition, array('limit' => 1));
97 if (DBM::is_result($r)) {
103 $author["contact-id"] = $r["id"];
107 if (!$found && ($addr != "")) {
108 $condition = array("`uid` = ? AND `addr` = ? AND `network` != ?",
109 $importer["uid"], $addr, NETWORK_STATUSNET);
110 $r = dba::select('contact', array(), $condition, array('limit' => 1));
112 if (DBM::is_result($r)) {
118 $author["contact-id"] = $r["id"];
122 $avatarlist = array();
123 $avatars = $xpath->query("atom:author/atom:link[@rel='avatar']", $context);
124 foreach ($avatars as $avatar) {
127 foreach ($avatar->attributes as $attributes) {
128 if ($attributes->name == "href") {
129 $href = $attributes->textContent;
131 if ($attributes->name == "width") {
132 $width = $attributes->textContent;
136 $avatarlist[$width] = $href;
139 if (count($avatarlist) > 0) {
141 $author["author-avatar"] = Probe::fixAvatar(current($avatarlist), $author["author-link"]);
144 $displayname = $xpath->evaluate('atom:author/poco:displayName/text()', $context)->item(0)->nodeValue;
145 if ($displayname != "") {
146 $author["author-name"] = $displayname;
149 $author["owner-name"] = $author["author-name"];
150 $author["owner-link"] = $author["author-link"];
151 $author["owner-avatar"] = $author["author-avatar"];
153 // Only update the contacts if it is an OStatus contact
154 if ($r && ($r['id'] > 0) && !$onlyfetch && ($contact["network"] == NETWORK_OSTATUS)) {
156 // Update contact data
158 unset($current['name-date']);
160 // This query doesn't seem to work
161 // $value = $xpath->query("atom:link[@rel='salmon']", $context)->item(0)->nodeValue;
163 // $contact["notify"] = $value;
165 // This query doesn't seem to work as well - I hate these queries
166 // $value = $xpath->query("atom:link[@rel='self' and @type='application/atom+xml']", $context)->item(0)->nodeValue;
168 // $contact["poll"] = $value;
170 $contact['url'] = $author["author-link"];
171 $contact['nurl'] = normalise_link($contact['url']);
173 $value = $xpath->evaluate('atom:author/atom:uri/text()', $context)->item(0)->nodeValue;
175 $contact["alias"] = $value;
178 $value = $xpath->evaluate('atom:author/poco:displayName/text()', $context)->item(0)->nodeValue;
180 $contact["name"] = $value;
183 $value = $xpath->evaluate('atom:author/poco:preferredUsername/text()', $context)->item(0)->nodeValue;
185 $contact["nick"] = $value;
188 $value = $xpath->evaluate('atom:author/poco:note/text()', $context)->item(0)->nodeValue;
190 $contact["about"] = html2bbcode($value);
193 $value = $xpath->evaluate('atom:author/poco:address/poco:formatted/text()', $context)->item(0)->nodeValue;
195 $contact["location"] = $value;
198 $contact['name-date'] = datetime_convert();
200 dba::update('contact', $contact, array('id' => $contact["id"]), $current);
202 if (!empty($author["author-avatar"]) && ($author["author-avatar"] != $current['avatar'])) {
203 logger("Update profile picture for contact ".$contact["id"], LOGGER_DEBUG);
204 Contact::updateAvatar($author["author-avatar"], $importer["uid"], $contact["id"]);
207 // Ensure that we are having this contact (with uid=0)
208 $cid = Contact::getIdForURL($aliaslink, 0);
211 $fields = array('url', 'nurl', 'name', 'nick', 'alias', 'about', 'location');
212 $old_contact = dba::select('contact', $fields, array('id' => $cid), array('limit' => 1));
214 // Update it with the current values
215 $fields = array('url' => $author["author-link"], 'name' => $contact["name"],
216 'nurl' => normalise_link($author["author-link"]),
217 'nick' => $contact["nick"], 'alias' => $contact["alias"],
218 'about' => $contact["about"], 'location' => $contact["location"],
219 'success_update' => datetime_convert(), 'last-update' => datetime_convert());
221 dba::update('contact', $fields, array('id' => $cid), $old_contact);
224 Contact::updateAvatar($author["author-avatar"], 0, $cid);
227 $contact["generation"] = 2;
228 $contact["hide"] = false; // OStatus contacts are never hidden
229 $contact["photo"] = $author["author-avatar"];
230 $gcid = GContact::update($contact);
232 GContact::link($gcid, $contact["uid"], $contact["id"]);
239 * @brief Fetches author data from a given XML string
241 * @param string $xml The XML
242 * @param array $importer user record of the importing user
244 * @return array Array of author related entries for the item
246 public static function salmonAuthor($xml, $importer)
252 $doc = new DOMDocument();
253 @$doc->loadXML($xml);
255 $xpath = new DOMXPath($doc);
256 $xpath->registerNamespace('atom', NAMESPACE_ATOM1);
257 $xpath->registerNamespace('thr', NAMESPACE_THREAD);
258 $xpath->registerNamespace('georss', NAMESPACE_GEORSS);
259 $xpath->registerNamespace('activity', NAMESPACE_ACTIVITY);
260 $xpath->registerNamespace('media', NAMESPACE_MEDIA);
261 $xpath->registerNamespace('poco', NAMESPACE_POCO);
262 $xpath->registerNamespace('ostatus', NAMESPACE_OSTATUS);
263 $xpath->registerNamespace('statusnet', NAMESPACE_STATUSNET);
265 $entries = $xpath->query('/atom:entry');
267 foreach ($entries as $entry) {
269 $author = self::fetchAuthor($xpath, $entry, $importer, $contact, true);
275 * @brief Read attributes from element
277 * @param object $element Element object
279 * @return array attributes
281 private static function readAttributes($element)
283 $attribute = array();
285 foreach ($element->attributes as $attributes) {
286 $attribute[$attributes->name] = $attributes->textContent;
293 * @brief Imports an XML string containing OStatus elements
295 * @param string $xml The XML
296 * @param array $importer user record of the importing user
297 * @param array $contact contact
298 * @param string $hub Called by reference, returns the fetched hub data
301 public static function import($xml, $importer, &$contact, &$hub)
303 self::process($xml, $importer, $contact, $hub);
307 * @brief Internal feed processing
309 * @param string $xml The XML
310 * @param array $importer user record of the importing user
311 * @param array $contact contact
312 * @param string $hub Called by reference, returns the fetched hub data
313 * @param boolean $stored Is the post fresh imported or from the database?
314 * @param boolean $initialize Is it the leading post so that data has to be initialized?
316 * @return boolean Could the XML be processed?
318 private static function process($xml, $importer, &$contact, &$hub, $stored = false, $initialize = true)
321 self::$itemlist = array();
322 self::$conv_list = array();
325 logger("Import OStatus message", LOGGER_DEBUG);
330 $doc = new DOMDocument();
331 @$doc->loadXML($xml);
333 $xpath = new DOMXPath($doc);
334 $xpath->registerNamespace('atom', NAMESPACE_ATOM1);
335 $xpath->registerNamespace('thr', NAMESPACE_THREAD);
336 $xpath->registerNamespace('georss', NAMESPACE_GEORSS);
337 $xpath->registerNamespace('activity', NAMESPACE_ACTIVITY);
338 $xpath->registerNamespace('media', NAMESPACE_MEDIA);
339 $xpath->registerNamespace('poco', NAMESPACE_POCO);
340 $xpath->registerNamespace('ostatus', NAMESPACE_OSTATUS);
341 $xpath->registerNamespace('statusnet', NAMESPACE_STATUSNET);
344 $hub_attributes = $xpath->query("/atom:feed/atom:link[@rel='hub']")->item(0)->attributes;
345 if (is_object($hub_attributes)) {
346 foreach ($hub_attributes as $hub_attribute) {
347 if ($hub_attribute->name == "href") {
348 $hub = $hub_attribute->textContent;
349 logger("Found hub ".$hub, LOGGER_DEBUG);
355 $header["uid"] = $importer["uid"];
356 $header["network"] = NETWORK_OSTATUS;
357 $header["type"] = "remote";
359 $header["origin"] = 0;
360 $header["gravity"] = GRAVITY_PARENT;
362 $first_child = $doc->firstChild->tagName;
364 if ($first_child == "feed") {
365 $entries = $xpath->query('/atom:feed/atom:entry');
367 $entries = $xpath->query('/atom:entry');
370 if ($entries->length == 1) {
371 // We reformat the XML to make it better readable
372 $doc2 = new DOMDocument();
373 $doc2->loadXML($xml);
374 $doc2->preserveWhiteSpace = false;
375 $doc2->formatOutput = true;
376 $xml2 = $doc2->saveXML();
378 $header["protocol"] = PROTOCOL_OSTATUS_SALMON;
379 $header["source"] = $xml2;
380 } elseif (!$initialize) {
384 // Fetch the first author
385 $authordata = $xpath->query('//author')->item(0);
386 $author = self::fetchAuthor($xpath, $authordata, $importer, $contact, $stored);
388 $entry = $xpath->query('/atom:entry');
390 // Reverse the order of the entries
391 $entrylist = array();
393 foreach ($entries as $entry) {
394 $entrylist[] = $entry;
397 foreach (array_reverse($entrylist) as $entry) {
399 $authorelement = $xpath->query('/atom:entry/atom:author', $entry);
401 if ($authorelement->length == 0) {
402 $authorelement = $xpath->query('atom:author', $entry);
405 if ($authorelement->length > 0) {
406 $author = self::fetchAuthor($xpath, $entry, $importer, $contact, $stored);
409 $value = $xpath->evaluate('atom:author/poco:preferredUsername/text()', $entry)->item(0)->nodeValue;
413 $nickname = $author["author-name"];
416 $item = array_merge($header, $author);
418 $item["uri"] = $xpath->query('atom:id/text()', $entry)->item(0)->nodeValue;
420 $item["verb"] = $xpath->query('activity:verb/text()', $entry)->item(0)->nodeValue;
423 if (in_array($item["verb"], array('qvitter-delete-notice', ACTIVITY_DELETE, 'delete'))) {
424 self::deleteNotice($item);
428 if (in_array($item["verb"], array(NAMESPACE_OSTATUS."/unfavorite", ACTIVITY_UNFAVORITE))) {
429 // Ignore "Unfavorite" message
430 logger("Ignore unfavorite message ".print_r($item, true), LOGGER_DEBUG);
434 // Deletions come with the same uri, so we check for duplicates after processing deletions
435 if (dba::exists('item', array('uid' => $importer["uid"], 'uri' => $item["uri"]))) {
436 logger('Post with URI '.$item["uri"].' already existed for user '.$importer["uid"].'.', LOGGER_DEBUG);
439 logger('Processing post with URI '.$item["uri"].' for user '.$importer["uid"].'.', LOGGER_DEBUG);
442 if ($item["verb"] == ACTIVITY_JOIN) {
443 // ignore "Join" messages
444 logger("Ignore join message ".print_r($item, true), LOGGER_DEBUG);
448 if ($item["verb"] == "http://mastodon.social/schema/1.0/block") {
449 // ignore mastodon "block" messages
450 logger("Ignore block message ".print_r($item, true), LOGGER_DEBUG);
454 if ($item["verb"] == ACTIVITY_FOLLOW) {
455 new_follower($importer, $contact, $item, $nickname);
459 if ($item["verb"] == NAMESPACE_OSTATUS."/unfollow") {
460 lose_follower($importer, $contact, $item, $dummy);
464 if ($item["verb"] == ACTIVITY_FAVORITE) {
465 $orig_uri = $xpath->query("activity:object/atom:id", $entry)->item(0)->nodeValue;
466 logger("Favorite ".$orig_uri." ".print_r($item, true));
468 $item["verb"] = ACTIVITY_LIKE;
469 $item["parent-uri"] = $orig_uri;
470 $item["gravity"] = GRAVITY_LIKE;
473 // http://activitystrea.ms/schema/1.0/rsvp-yes
474 if (!in_array($item["verb"], array(ACTIVITY_POST, ACTIVITY_LIKE, ACTIVITY_SHARE))) {
475 logger("Unhandled verb ".$item["verb"]." ".print_r($item, true), LOGGER_DEBUG);
478 self::processPost($xpath, $entry, $item, $importer);
480 if ($initialize && (count(self::$itemlist) > 0)) {
481 if (self::$itemlist[0]['uri'] == self::$itemlist[0]['parent-uri']) {
482 // We will import it everytime, when it is started by our contacts
483 $valid = !empty(self::$itemlist[0]['contact-id']);
485 // If not, then it depends on this setting
486 $valid = !Config::get('system', 'ostatus_full_threads');
489 // Never post a thread when the only interaction by our contact was a like
491 $verbs = array(ACTIVITY_POST, ACTIVITY_SHARE);
492 foreach (self::$itemlist as $item) {
493 if (!empty($item['contact-id']) && in_array($item['verb'], $verbs)) {
499 // But we will only import complete threads
500 $valid = dba::exists('item', array('uid' => $importer["uid"], 'uri' => self::$itemlist[0]['parent-uri']));
504 $default_contact = 0;
505 $key = count(self::$itemlist);
506 for ($key = count(self::$itemlist) - 1; $key >= 0; $key--) {
507 if (empty(self::$itemlist[$key]['contact-id'])) {
508 self::$itemlist[$key]['contact-id'] = $default_contact;
510 $default_contact = $item['contact-id'];
513 foreach (self::$itemlist as $item) {
514 $found = dba::exists('item', array('uid' => $importer["uid"], 'uri' => $item["uri"]));
516 logger("Item with uri ".$item["uri"]." for user ".$importer["uid"]." already exists.", LOGGER_DEBUG);
517 } elseif ($item['contact-id'] < 0) {
518 logger("Item with uri ".$item["uri"]." is from a blocked contact.", LOGGER_DEBUG);
520 // We are having duplicated entries. Hopefully this solves it.
521 if (Lock::set('ostatus_process_item_store')) {
522 $ret = item_store($item);
523 Lock::remove('ostatus_process_item_store');
524 logger("Item with uri ".$item["uri"]." for user ".$importer["uid"].' stored. Return value: '.$ret);
526 $ret = item_store($item);
527 logger("We couldn't lock - but tried to store the item anyway. Return value is ".$ret);
532 self::$itemlist = array();
534 logger('Processing done for post with URI '.$item["uri"].' for user '.$importer["uid"].'.', LOGGER_DEBUG);
540 * @param object $item item
543 private static function deleteNotice($item)
545 $condition = array('uid' => $item['uid'], 'author-link' => $item['author-link'], 'uri' => $item['uri']);
546 $deleted = dba::select('item', array('id', 'parent-uri'), $condition, array('limit' => 1));
547 if (!DBM::is_result($deleted)) {
548 logger('Item from '.$item['author-link'].' with uri '.$item['uri'].' for user '.$item['uid']." wasn't found. We don't delete it. ");
552 // Currently we don't have a central deletion function that we could use in this case
553 // The function "item_drop" doesn't work for that case
556 array('deleted' => true, 'title' => '', 'body' => '',
557 'edited' => datetime_convert(), 'changed' => datetime_convert()),
558 array('id' => $deleted["id"])
561 delete_thread($deleted["id"], $deleted["parent-uri"]);
563 logger('Deleted item with uri '.$item['uri'].' for user '.$item['uid']);
567 * @brief Processes the XML for a post
569 * @param object $xpath The xpath object
570 * @param object $entry The xml entry that is processed
571 * @param array $item The item array
572 * @param array $importer user record of the importing user
575 private static function processPost($xpath, $entry, &$item, $importer)
577 $item["body"] = html2bbcode($xpath->query('atom:content/text()', $entry)->item(0)->nodeValue);
578 $item["object-type"] = $xpath->query('activity:object-type/text()', $entry)->item(0)->nodeValue;
579 if (($item["object-type"] == ACTIVITY_OBJ_BOOKMARK) || ($item["object-type"] == ACTIVITY_OBJ_EVENT)) {
580 $item["title"] = $xpath->query('atom:title/text()', $entry)->item(0)->nodeValue;
581 $item["body"] = $xpath->query('atom:summary/text()', $entry)->item(0)->nodeValue;
582 } elseif ($item["object-type"] == ACTIVITY_OBJ_QUESTION) {
583 $item["title"] = $xpath->query('atom:title/text()', $entry)->item(0)->nodeValue;
586 $item["created"] = $xpath->query('atom:published/text()', $entry)->item(0)->nodeValue;
587 $item["edited"] = $xpath->query('atom:updated/text()', $entry)->item(0)->nodeValue;
588 $conversation = $xpath->query('ostatus:conversation/text()', $entry)->item(0)->nodeValue;
589 $item['conversation-uri'] = $conversation;
591 $conv = $xpath->query('ostatus:conversation', $entry);
592 if (is_object($conv->item(0))) {
593 foreach ($conv->item(0)->attributes as $attributes) {
594 if ($attributes->name == "ref") {
595 $item['conversation-uri'] = $attributes->textContent;
597 if ($attributes->name == "href") {
598 $item['conversation-href'] = $attributes->textContent;
605 $inreplyto = $xpath->query('thr:in-reply-to', $entry);
606 if (is_object($inreplyto->item(0))) {
607 foreach ($inreplyto->item(0)->attributes as $attributes) {
608 if ($attributes->name == "ref") {
609 $item["parent-uri"] = $attributes->textContent;
611 if ($attributes->name == "href") {
612 $related = $attributes->textContent;
617 $georsspoint = $xpath->query('georss:point', $entry);
618 if (!empty($georsspoint) && ($georsspoint->length > 0)) {
619 $item["coord"] = $georsspoint->item(0)->nodeValue;
622 $categories = $xpath->query('atom:category', $entry);
624 foreach ($categories as $category) {
625 foreach ($category->attributes as $attributes) {
626 if ($attributes->name == "term") {
627 $term = $attributes->textContent;
628 if (strlen($item["tag"])) {
631 $item["tag"] .= "#[url=".System::baseUrl()."/search?tag=".$term."]".$term."[/url]";
640 $links = $xpath->query('atom:link', $entry);
642 $link_data = self::processLinks($links, $item);
643 $self = $link_data['self'];
644 $add_body = $link_data['add_body'];
649 $notice_info = $xpath->query('statusnet:notice_info', $entry);
650 if ($notice_info && ($notice_info->length > 0)) {
651 foreach ($notice_info->item(0)->attributes as $attributes) {
652 if ($attributes->name == "source") {
653 $item["app"] = strip_tags($attributes->textContent);
655 if ($attributes->name == "repeat_of") {
656 $repeat_of = $attributes->textContent;
660 // Is it a repeated post?
661 if (($repeat_of != "") || ($item["verb"] == ACTIVITY_SHARE)) {
662 $link_data = self::processRepeatedItem($xpath, $entry, $item, $importer);
663 if (!empty($link_data['add_body'])) {
664 $add_body .= $link_data['add_body'];
668 $item["body"] .= $add_body;
670 // Only add additional data when there is no picture in the post
671 if (!strstr($item["body"], '[/img]')) {
672 $item["body"] = add_page_info_to_body($item["body"]);
675 // Mastodon Content Warning
676 if (($item["verb"] == ACTIVITY_POST) && $xpath->evaluate('boolean(atom:summary)', $entry)) {
677 $clear_text = $xpath->query('atom:summary/text()', $entry)->item(0)->nodeValue;
679 $item["body"] = html2bbcode($clear_text) . '[spoiler]' . $item["body"] . '[/spoiler]';
682 if (($self != '') && empty($item['protocol'])) {
683 self::fetchSelf($self, $item);
686 if (!empty($item["conversation-href"])) {
687 self::fetchConversation($item['conversation-href'], $item['conversation-uri']);
690 if (isset($item["parent-uri"]) && ($related != '')) {
691 if (!dba::exists('item', array('uid' => $importer["uid"], 'uri' => $item['parent-uri']))) {
692 self::fetchRelated($related, $item["parent-uri"], $importer);
694 logger('Reply with URI '.$item["uri"].' already existed for user '.$importer["uid"].'.', LOGGER_DEBUG);
697 $item["type"] = 'remote-comment';
698 $item["gravity"] = GRAVITY_COMMENT;
700 $item["parent-uri"] = $item["uri"];
703 if (($item['author-link'] != '') && !empty($item['protocol'])) {
704 $item = store_conversation($item);
707 self::$itemlist[] = $item;
711 * @brief Fetch the conversation for posts
713 * @param string $conversation The link to the conversation
714 * @param string $conversation_uri The conversation in "uri" format
717 private static function fetchConversation($conversation, $conversation_uri)
719 // Ensure that we only store a conversation once in a process
720 if (isset(self::$conv_list[$conversation])) {
724 self::$conv_list[$conversation] = true;
726 $conversation_data = z_fetch_url($conversation, false, $redirects, array('accept_content' => 'application/atom+xml, text/html'));
728 if (!$conversation_data['success']) {
734 if (stristr($conversation_data['header'], 'Content-Type: application/atom+xml')) {
735 $xml = $conversation_data['body'];
739 $doc = new DOMDocument();
740 if (!@$doc->loadHTML($conversation_data['body'])) {
743 $xpath = new DOMXPath($doc);
745 $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 = z_fetch_url($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;
796 $conv_data = array();
798 $conv_data['protocol'] = PROTOCOL_SPLITTED_CONV;
799 $conv_data['network'] = NETWORK_OSTATUS;
800 $conv_data['uri'] = $xpath->query('atom:id/text()', $entry)->item(0)->nodeValue;
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 = $xpath->query('ostatus:conversation/text()', $entry)->item(0)->nodeValue;
812 $conv_data['conversation-uri'] = $conv;
814 $conv = $xpath->query('ostatus:conversation', $entry);
815 if (is_object($conv->item(0))) {
816 foreach ($conv->item(0)->attributes as $attributes) {
817 if ($attributes->name == "ref") {
818 $conv_data['conversation-uri'] = $attributes->textContent;
820 if ($attributes->name == "href") {
821 $conv_data['conversation-href'] = $attributes->textContent;
826 if ($conversation != '') {
827 $conv_data['conversation-uri'] = $conversation;
830 if ($conversation_uri != '') {
831 $conv_data['conversation-uri'] = $conversation_uri;
834 $entry = $doc2->importNode($entry, true);
836 $doc2->appendChild($entry);
838 $conv_data['source'] = $doc2->saveXML();
840 $condition = array('item-uri' => $conv_data['uri'],'protocol' => PROTOCOL_OSTATUS_FEED);
841 if (dba::exists('conversation', $condition)) {
842 logger('Delete deprecated entry for URI '.$conv_data['uri'], LOGGER_DEBUG);
843 dba::delete('conversation', array('item-uri' => $conv_data['uri']));
846 logger('Store conversation data for uri '.$conv_data['uri'], LOGGER_DEBUG);
847 store_conversation($conv_data);
852 * @brief Fetch the own post so that it can be stored later
854 * We want to store the original data for later processing.
855 * This function is meant for cases where we process a feed with multiple entries.
856 * In that case we need to fetch the single posts here.
858 * @param string $self The link to the self item
859 * @param array $item The item array
862 private static function fetchSelf($self, &$item)
864 $condition = array('`item-uri` = ? AND `protocol` IN (?, ?)', $self, PROTOCOL_DFRN, PROTOCOL_OSTATUS_SALMON);
865 if (dba::exists('conversation', $condition)) {
866 logger('Conversation '.$item['uri'].' is already stored.', LOGGER_DEBUG);
870 $self_data = z_fetch_url($self);
872 if (!$self_data['success']) {
876 // We reformat the XML to make it better readable
877 $doc = new DOMDocument();
878 $doc->loadXML($self_data['body']);
879 $doc->preserveWhiteSpace = false;
880 $doc->formatOutput = true;
881 $xml = $doc->saveXML();
883 $item["protocol"] = PROTOCOL_OSTATUS_SALMON;
884 $item["source"] = $xml;
886 logger('Conversation '.$item['uri'].' is now fetched.', LOGGER_DEBUG);
890 * @brief Fetch related posts and processes them
892 * @param string $related The link to the related item
893 * @param string $related_uri The related item in "uri" format
894 * @param array $importer user record of the importing user
897 private static function fetchRelated($related, $related_uri, $importer)
899 $condition = array('`item-uri` = ? AND `protocol` IN (?, ?)', $related_uri, PROTOCOL_DFRN, PROTOCOL_OSTATUS_SALMON);
900 $conversation = dba::select('conversation', array('source', 'protocol'), $condition, array('limit' => 1));
901 if (DBM::is_result($conversation)) {
903 $xml = $conversation['source'];
904 if (self::process($xml, $importer, $contact, $hub, $stored, false)) {
905 logger('Got valid cached XML for URI '.$related_uri, LOGGER_DEBUG);
908 if ($conversation['protocol'] == PROTOCOL_OSTATUS_SALMON) {
909 logger('Delete invalid cached XML for URI '.$related_uri, LOGGER_DEBUG);
910 dba::delete('conversation', array('item-uri' => $related_uri));
915 $related_data = z_fetch_url($related, false, $redirects, array('accept_content' => 'application/atom+xml, text/html'));
917 if (!$related_data['success']) {
923 if (stristr($related_data['header'], 'Content-Type: application/atom+xml')) {
924 logger('Directly fetched XML for URI '.$related_uri, LOGGER_DEBUG);
925 $xml = $related_data['body'];
929 $doc = new DOMDocument();
930 if (!@$doc->loadHTML($related_data['body'])) {
933 $xpath = new DOMXPath($doc);
937 $links = $xpath->query('//link');
939 foreach ($links as $link) {
940 $attribute = self::readAttributes($link);
941 if (($attribute['rel'] == 'alternate') && ($attribute['type'] == 'application/atom+xml')) {
942 $atom_file = $attribute['href'];
945 if ($atom_file != '') {
946 $related_atom = z_fetch_url($atom_file);
948 if ($related_atom['success']) {
949 logger('Fetched XML for URI '.$related_uri, LOGGER_DEBUG);
950 $xml = $related_atom['body'];
956 // Workaround for older GNU Social servers
957 if (($xml == '') && strstr($related, '/notice/')) {
958 $related_atom = z_fetch_url(str_replace('/notice/', '/api/statuses/show/', $related).'.atom');
960 if ($related_atom['success']) {
961 logger('GNU Social workaround to fetch XML for URI '.$related_uri, LOGGER_DEBUG);
962 $xml = $related_atom['body'];
966 // Even more worse workaround for GNU Social ;-)
968 $related_guess = OStatus::convertHref($related_uri);
969 $related_atom = z_fetch_url(str_replace('/notice/', '/api/statuses/show/', $related_guess).'.atom');
971 if ($related_atom['success']) {
972 logger('GNU Social workaround 2 to fetch XML for URI '.$related_uri, LOGGER_DEBUG);
973 $xml = $related_atom['body'];
977 // Finally we take the data that we fetched from "ostatus:conversation"
979 $condition = array('item-uri' => $related_uri, 'protocol' => PROTOCOL_SPLITTED_CONV);
980 $conversation = dba::select('conversation', array('source'), $condition, array('limit' => 1));
981 if (DBM::is_result($conversation)) {
983 logger('Got cached XML from conversation for URI '.$related_uri, LOGGER_DEBUG);
984 $xml = $conversation['source'];
989 self::process($xml, $importer, $contact, $hub, $stored, false);
991 logger("XML couldn't be fetched for URI: ".$related_uri." - href: ".$related, LOGGER_DEBUG);
997 * @brief Processes the XML for a repeated post
999 * @param object $xpath The xpath object
1000 * @param object $entry The xml entry that is processed
1001 * @param array $item The item array
1002 * @param array $importer user record of the importing user
1004 * @return array with data from links
1006 private static function processRepeatedItem($xpath, $entry, &$item, $importer)
1008 $activityobjects = $xpath->query('activity:object', $entry)->item(0);
1010 if (!is_object($activityobjects)) {
1014 $link_data = array();
1016 $orig_uri = $xpath->query('atom:id/text()', $activityobjects)->item(0)->nodeValue;
1018 $links = $xpath->query("atom:link", $activityobjects);
1020 $link_data = self::processLinks($links, $item);
1023 $orig_body = $xpath->query('atom:content/text()', $activityobjects)->item(0)->nodeValue;
1024 $orig_created = $xpath->query('atom:published/text()', $activityobjects)->item(0)->nodeValue;
1025 $orig_edited = $xpath->query('atom:updated/text()', $activityobjects)->item(0)->nodeValue;
1027 $orig_author = self::fetchAuthor($xpath, $activityobjects, $importer, $dummy, false);
1029 $item["author-name"] = $orig_author["author-name"];
1030 $item["author-link"] = $orig_author["author-link"];
1031 $item["author-avatar"] = $orig_author["author-avatar"];
1033 $item["body"] = html2bbcode($orig_body);
1034 $item["created"] = $orig_created;
1035 $item["edited"] = $orig_edited;
1037 $item["uri"] = $orig_uri;
1039 $item["verb"] = $xpath->query('activity:verb/text()', $activityobjects)->item(0)->nodeValue;
1041 $item["object-type"] = $xpath->query('activity:object-type/text()', $activityobjects)->item(0)->nodeValue;
1043 $inreplyto = $xpath->query('thr:in-reply-to', $activityobjects);
1044 if (is_object($inreplyto->item(0))) {
1045 foreach ($inreplyto->item(0)->attributes as $attributes) {
1046 if ($attributes->name == "ref") {
1047 $item["parent-uri"] = $attributes->textContent;
1056 * @brief Processes links in the XML
1058 * @param object $links The xml data that contain links
1059 * @param array $item The item array
1061 * @return array with data from the links
1063 private static function processLinks($links, &$item)
1065 $link_data = array('add_body' => '', 'self' => '');
1067 foreach ($links as $link) {
1068 $attribute = self::readAttributes($link);
1070 if (($attribute['rel'] != "") && ($attribute['href'] != "")) {
1071 switch ($attribute['rel']) {
1073 $item["plink"] = $attribute['href'];
1074 if (($item["object-type"] == ACTIVITY_OBJ_QUESTION)
1075 || ($item["object-type"] == ACTIVITY_OBJ_EVENT)
1077 $item["body"] .= add_page_info($attribute['href']);
1080 case "ostatus:conversation":
1081 $link_data['conversation'] = $attribute['href'];
1082 $item['conversation-href'] = $link_data['conversation'];
1083 if (!isset($item['conversation-uri'])) {
1084 $item['conversation-uri'] = $item['conversation-href'];
1088 $filetype = strtolower(substr($attribute['type'], 0, strpos($attribute['type'], '/')));
1089 if ($filetype == 'image') {
1090 $link_data['add_body'] .= "\n[img]".$attribute['href'].'[/img]';
1092 if (strlen($item["attach"])) {
1093 $item["attach"] .= ',';
1095 if (!isset($attribute['length'])) {
1096 $attribute['length'] = "0";
1098 $item["attach"] .= '[attach]href="'.$attribute['href'].'" length="'.$attribute['length'].'" type="'.$attribute['type'].'" title="'.$attribute['title'].'"[/attach]';
1102 if ($item["object-type"] != ACTIVITY_OBJ_BOOKMARK) {
1103 if (!isset($item["parent-uri"])) {
1104 $item["parent-uri"] = $attribute['href'];
1106 $link_data['related'] = $attribute['href'];
1108 $item["body"] .= add_page_info($attribute['href']);
1112 if ($item["plink"] == '') {
1113 $item["plink"] = $attribute['href'];
1115 $link_data['self'] = $attribute['href'];
1124 * @brief Create an url out of an uri
1126 * @param string $href URI in the format "parameter1:parameter1:..."
1128 * @return string URL in the format http(s)://....
1130 public static function convertHref($href)
1132 $elements = explode(":", $href);
1134 if ((count($elements) <= 2) || ($elements[0] != "tag")) {
1138 $server = explode(",", $elements[1]);
1139 $conversation = explode("=", $elements[2]);
1141 if ((count($elements) == 4) && ($elements[2] == "post")) {
1142 return "http://".$server[0]."/notice/".$elements[3];
1145 if ((count($conversation) != 2) || ($conversation[1] =="")) {
1148 if ($elements[3] == "objectType=thread") {
1149 return "http://".$server[0]."/conversation/".$conversation[1];
1151 return "http://".$server[0]."/notice/".$conversation[1];
1157 * @brief Checks if the current post is a reshare
1159 * @param array $item The item array of thw post
1161 * @return string The guid if the post is a reshare
1163 private static function getResharedGuid($item)
1165 $body = trim($item["body"]);
1167 // Skip if it isn't a pure repeated messages
1168 // Does it start with a share?
1169 if (strpos($body, "[share") > 0) {
1173 // Does it end with a share?
1174 if (strlen($body) > (strrpos($body, "[/share]") + 8)) {
1178 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "$1", $body);
1179 // Skip if there is no shared message in there
1180 if ($body == $attributes) {
1185 preg_match("/guid='(.*?)'/ism", $attributes, $matches);
1186 if ($matches[1] != "") {
1187 $guid = $matches[1];
1190 preg_match('/guid="(.*?)"/ism', $attributes, $matches);
1191 if ($matches[1] != "") {
1192 $guid = $matches[1];
1199 * @brief Cleans the body of a post if it contains picture links
1201 * @param string $body The body
1203 * @return string The cleaned body
1205 private static function formatPicturePost($body)
1207 $siteinfo = get_attached_data($body);
1209 if (($siteinfo["type"] == "photo")) {
1210 if (isset($siteinfo["preview"])) {
1211 $preview = $siteinfo["preview"];
1213 $preview = $siteinfo["image"];
1216 // Is it a remote picture? Then make a smaller preview here
1217 $preview = proxy_url($preview, false, PROXY_SIZE_SMALL);
1219 // Is it a local picture? Then make it smaller here
1220 $preview = str_replace(array("-0.jpg", "-0.png"), array("-2.jpg", "-2.png"), $preview);
1221 $preview = str_replace(array("-1.jpg", "-1.png"), array("-2.jpg", "-2.png"), $preview);
1223 if (isset($siteinfo["url"])) {
1224 $url = $siteinfo["url"];
1226 $url = $siteinfo["image"];
1229 $body = trim($siteinfo["text"])." [url]".$url."[/url]\n[img]".$preview."[/img]";
1236 * @brief Adds the header elements to the XML document
1238 * @param object $doc XML document
1239 * @param array $owner Contact data of the poster
1240 * @param string $filter The related feed filter (activity, posts or comments)
1242 * @return object header root element
1244 private static function addHeader($doc, $owner, $filter)
1248 $root = $doc->createElementNS(NAMESPACE_ATOM1, 'feed');
1249 $doc->appendChild($root);
1251 $root->setAttribute("xmlns:thr", NAMESPACE_THREAD);
1252 $root->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
1253 $root->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
1254 $root->setAttribute("xmlns:media", NAMESPACE_MEDIA);
1255 $root->setAttribute("xmlns:poco", NAMESPACE_POCO);
1256 $root->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
1257 $root->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
1258 $root->setAttribute("xmlns:mastodon", NAMESPACE_MASTODON);
1261 case 'activity': $title = t('%s\'s timeline', $owner['name']); break;
1262 case 'posts' : $title = t('%s\'s posts' , $owner['name']); break;
1263 case 'comments': $title = t('%s\'s comments', $owner['name']); break;
1266 $attributes = array("uri" => "https://friendi.ca", "version" => FRIENDICA_VERSION . "-" . DB_UPDATE_VERSION);
1267 XML::addElement($doc, $root, "generator", FRIENDICA_PLATFORM, $attributes);
1268 XML::addElement($doc, $root, "id", System::baseUrl() . "/profile/" . $owner["nick"]);
1269 XML::addElement($doc, $root, "title", $title);
1270 XML::addElement($doc, $root, "subtitle", sprintf("Updates from %s on %s", $owner["name"], $a->config["sitename"]));
1271 XML::addElement($doc, $root, "logo", $owner["photo"]);
1272 XML::addElement($doc, $root, "updated", datetime_convert("UTC", "UTC", "now", ATOM_TIME));
1274 $author = self::addAuthor($doc, $owner);
1275 $root->appendChild($author);
1277 $attributes = array("href" => $owner["url"], "rel" => "alternate", "type" => "text/html");
1278 XML::addElement($doc, $root, "link", "", $attributes);
1280 /// @TODO We have to find out what this is
1281 /// $attributes = array("href" => System::baseUrl()."/sup",
1282 /// "rel" => "http://api.friendfeed.com/2008/03#sup",
1283 /// "type" => "application/json");
1284 /// XML::addElement($doc, $root, "link", "", $attributes);
1286 self::hublinks($doc, $root, $owner["nick"]);
1288 $attributes = array("href" => System::baseUrl() . "/salmon/" . $owner["nick"], "rel" => "salmon");
1289 XML::addElement($doc, $root, "link", "", $attributes);
1291 $attributes = array("href" => System::baseUrl() . "/salmon/" . $owner["nick"], "rel" => "http://salmon-protocol.org/ns/salmon-replies");
1292 XML::addElement($doc, $root, "link", "", $attributes);
1294 $attributes = array("href" => System::baseUrl() . "/salmon/" . $owner["nick"], "rel" => "http://salmon-protocol.org/ns/salmon-mention");
1295 XML::addElement($doc, $root, "link", "", $attributes);
1297 $attributes = array("href" => System::baseUrl() . "/api/statuses/user_timeline/" . $owner["nick"] . ".atom",
1298 "rel" => "self", "type" => "application/atom+xml");
1299 XML::addElement($doc, $root, "link", "", $attributes);
1305 * @brief Add the link to the push hubs to the XML document
1307 * @param object $doc XML document
1308 * @param object $root XML root element where the hub links are added
1309 * @param object $nick nick
1312 public static function hublinks($doc, $root, $nick)
1314 $h = System::baseUrl() . '/pubsubhubbub/'.$nick;
1315 XML::addElement($doc, $root, "link", "", array("href" => $h, "rel" => "hub"));
1319 * @brief Adds attachement data to the XML document
1321 * @param object $doc XML document
1322 * @param object $root XML root element where the hub links are added
1323 * @param array $item Data of the item that is to be posted
1326 private static function getAttachment($doc, $root, $item)
1329 $siteinfo = get_attached_data($item["body"]);
1331 switch ($siteinfo["type"]) {
1333 $imgdata = Image::getInfoFromURL($siteinfo["image"]);
1334 $attributes = array("rel" => "enclosure",
1335 "href" => $siteinfo["image"],
1336 "type" => $imgdata["mime"],
1337 "length" => intval($imgdata["size"]));
1338 XML::addElement($doc, $root, "link", "", $attributes);
1341 $attributes = array("rel" => "enclosure",
1342 "href" => $siteinfo["url"],
1343 "type" => "text/html; charset=UTF-8",
1345 "title" => $siteinfo["title"]);
1346 XML::addElement($doc, $root, "link", "", $attributes);
1352 if (!Config::get('system', 'ostatus_not_attach_preview') && ($siteinfo["type"] != "photo") && isset($siteinfo["image"])) {
1353 $imgdata = Image::getInfoFromURL($siteinfo["image"]);
1354 $attributes = array("rel" => "enclosure",
1355 "href" => $siteinfo["image"],
1356 "type" => $imgdata["mime"],
1357 "length" => intval($imgdata["size"]));
1359 XML::addElement($doc, $root, "link", "", $attributes);
1362 $arr = explode('[/attach],', $item['attach']);
1364 foreach ($arr as $r) {
1366 $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"|', $r, $matches);
1368 $attributes = array("rel" => "enclosure",
1369 "href" => $matches[1],
1370 "type" => $matches[3]);
1372 if (intval($matches[2])) {
1373 $attributes["length"] = intval($matches[2]);
1375 if (trim($matches[4]) != "") {
1376 $attributes["title"] = trim($matches[4]);
1378 XML::addElement($doc, $root, "link", "", $attributes);
1385 * @brief Adds the author element to the XML document
1387 * @param object $doc XML document
1388 * @param array $owner Contact data of the poster
1390 * @return object author element
1392 private static function addAuthor($doc, $owner)
1394 $r = q("SELECT `homepage`, `publish` FROM `profile` WHERE `uid` = %d AND `is-default` LIMIT 1", intval($owner["uid"]));
1395 if (DBM::is_result($r)) {
1398 $author = $doc->createElement("author");
1399 XML::addElement($doc, $author, "id", $owner["url"]);
1400 XML::addElement($doc, $author, "activity:object-type", ACTIVITY_OBJ_PERSON);
1401 XML::addElement($doc, $author, "uri", $owner["url"]);
1402 XML::addElement($doc, $author, "name", $owner["nick"]);
1403 XML::addElement($doc, $author, "email", $owner["addr"]);
1404 XML::addElement($doc, $author, "summary", bbcode($owner["about"], false, false, 7));
1406 $attributes = array("rel" => "alternate", "type" => "text/html", "href" => $owner["url"]);
1407 XML::addElement($doc, $author, "link", "", $attributes);
1409 $attributes = array(
1411 "type" => "image/jpeg", // To-Do?
1412 "media:width" => 175,
1413 "media:height" => 175,
1414 "href" => $owner["photo"]);
1415 XML::addElement($doc, $author, "link", "", $attributes);
1417 if (isset($owner["thumb"])) {
1418 $attributes = array(
1420 "type" => "image/jpeg", // To-Do?
1421 "media:width" => 80,
1422 "media:height" => 80,
1423 "href" => $owner["thumb"]);
1424 XML::addElement($doc, $author, "link", "", $attributes);
1427 XML::addElement($doc, $author, "poco:preferredUsername", $owner["nick"]);
1428 XML::addElement($doc, $author, "poco:displayName", $owner["name"]);
1429 XML::addElement($doc, $author, "poco:note", bbcode($owner["about"], false, false, 7));
1431 if (trim($owner["location"]) != "") {
1432 $element = $doc->createElement("poco:address");
1433 XML::addElement($doc, $element, "poco:formatted", $owner["location"]);
1434 $author->appendChild($element);
1437 if (trim($profile["homepage"]) != "") {
1438 $urls = $doc->createElement("poco:urls");
1439 XML::addElement($doc, $urls, "poco:type", "homepage");
1440 XML::addElement($doc, $urls, "poco:value", $profile["homepage"]);
1441 XML::addElement($doc, $urls, "poco:primary", "true");
1442 $author->appendChild($urls);
1445 if (count($profile)) {
1446 XML::addElement($doc, $author, "followers", "", array("url" => System::baseUrl()."/viewcontacts/".$owner["nick"]));
1447 XML::addElement($doc, $author, "statusnet:profile_info", "", array("local_id" => $owner["uid"]));
1450 if ($profile["publish"]) {
1451 XML::addElement($doc, $author, "mastodon:scope", "public");
1457 * @TODO Picture attachments should look like this:
1458 * <a href="https://status.pirati.ca/attachment/572819" title="https://status.pirati.ca/file/heluecht-20151202T222602-rd3u49p.gif"
1459 * class="attachment thumbnail" id="attachment-572819" rel="nofollow external">https://status.pirati.ca/attachment/572819</a>
1463 * @brief Returns the given activity if present - otherwise returns the "post" activity
1465 * @param array $item Data of the item that is to be posted
1467 * @return string activity
1469 private static function constructVerb($item)
1471 if ($item['verb']) {
1472 return $item['verb'];
1475 return ACTIVITY_POST;
1479 * @brief Returns the given object type if present - otherwise returns the "note" object type
1481 * @param array $item Data of the item that is to be posted
1483 * @return string Object type
1485 private static function constructObjecttype($item)
1487 if (in_array($item['object-type'], array(ACTIVITY_OBJ_NOTE, ACTIVITY_OBJ_COMMENT)))
1488 return $item['object-type'];
1489 return ACTIVITY_OBJ_NOTE;
1493 * @brief Adds an entry element to the XML document
1495 * @param object $doc XML document
1496 * @param array $item Data of the item that is to be posted
1497 * @param array $owner Contact data of the poster
1498 * @param bool $toplevel optional default false
1500 * @return object Entry element
1502 private static function entry($doc, $item, $owner, $toplevel = false)
1504 $repeated_guid = self::getResharedGuid($item);
1505 if ($repeated_guid != "") {
1506 $xml = self::reshareEntry($doc, $item, $owner, $repeated_guid, $toplevel);
1513 if ($item["verb"] == ACTIVITY_LIKE) {
1514 return self::likeEntry($doc, $item, $owner, $toplevel);
1515 } elseif (in_array($item["verb"], array(ACTIVITY_FOLLOW, NAMESPACE_OSTATUS."/unfollow"))) {
1516 return self::followEntry($doc, $item, $owner, $toplevel);
1518 return self::noteEntry($doc, $item, $owner, $toplevel);
1523 * @brief Adds a source entry to the XML document
1525 * @param object $doc XML document
1526 * @param array $contact Array of the contact that is added
1528 * @return object Source element
1530 private static function sourceEntry($doc, $contact)
1532 $source = $doc->createElement("source");
1533 XML::addElement($doc, $source, "id", $contact["poll"]);
1534 XML::addElement($doc, $source, "title", $contact["name"]);
1535 XML::addElement($doc, $source, "link", "", array("rel" => "alternate", "type" => "text/html", "href" => $contact["alias"]));
1536 XML::addElement($doc, $source, "link", "", array("rel" => "self", "type" => "application/atom+xml", "href" => $contact["poll"]));
1537 XML::addElement($doc, $source, "icon", $contact["photo"]);
1538 XML::addElement($doc, $source, "updated", datetime_convert("UTC", "UTC", $contact["success_update"]."+00:00", ATOM_TIME));
1544 * @brief Fetches contact data from the contact or the gcontact table
1546 * @param string $url URL of the contact
1547 * @param array $owner Contact data of the poster
1549 * @return array Contact array
1551 private static function contactEntry($url, $owner)
1554 "SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` IN (0, %d) ORDER BY `uid` DESC LIMIT 1",
1555 dbesc(normalise_link($url)),
1556 intval($owner["uid"])
1558 if (DBM::is_result($r)) {
1560 $contact["uid"] = -1;
1563 if (!DBM::is_result($r)) {
1565 "SELECT * FROM `gcontact` WHERE `nurl` = '%s' LIMIT 1",
1566 dbesc(normalise_link($url))
1568 if (DBM::is_result($r)) {
1570 $contact["uid"] = -1;
1571 $contact["success_update"] = $contact["updated"];
1575 if (!DBM::is_result($r)) {
1579 if (!isset($contact["poll"])) {
1580 $data = Probe::uri($url);
1581 $contact["poll"] = $data["poll"];
1583 if (!$contact["alias"]) {
1584 $contact["alias"] = $data["alias"];
1588 if (!isset($contact["alias"])) {
1589 $contact["alias"] = $contact["url"];
1596 * @brief Adds an entry element with reshared content
1598 * @param object $doc XML document
1599 * @param array $item Data of the item that is to be posted
1600 * @param array $owner Contact data of the poster
1601 * @param string $repeated_guid guid
1602 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1604 * @return object Entry element
1606 private static function reshareEntry($doc, $item, $owner, $repeated_guid, $toplevel)
1608 if (($item["id"] != $item["parent"]) && (normalise_link($item["author-link"]) != normalise_link($owner["url"]))) {
1609 logger("OStatus entry is from author ".$owner["url"]." - not from ".$item["author-link"].". Quitting.", LOGGER_DEBUG);
1612 $title = self::entryHeader($doc, $entry, $owner, $toplevel);
1615 "SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' AND NOT `private` AND `network` IN ('%s', '%s', '%s') LIMIT 1",
1616 intval($owner["uid"]),
1617 dbesc($repeated_guid),
1618 dbesc(NETWORK_DFRN),
1619 dbesc(NETWORK_DIASPORA),
1620 dbesc(NETWORK_OSTATUS)
1622 if (DBM::is_result($r)) {
1623 $repeated_item = $r[0];
1627 $contact = self::contactEntry($repeated_item['author-link'], $owner);
1629 $parent_item = (($item['thr-parent']) ? $item['thr-parent'] : $item['parent-uri']);
1631 $title = $owner["nick"]." repeated a notice by ".$contact["nick"];
1633 self::entryContent($doc, $entry, $item, $owner, $title, ACTIVITY_SHARE, false);
1635 $as_object = $doc->createElement("activity:object");
1637 XML::addElement($doc, $as_object, "activity:object-type", NAMESPACE_ACTIVITY_SCHEMA."activity");
1639 self::entryContent($doc, $as_object, $repeated_item, $owner, "", "", false);
1641 $author = self::addAuthor($doc, $contact);
1642 $as_object->appendChild($author);
1644 $as_object2 = $doc->createElement("activity:object");
1646 XML::addElement($doc, $as_object2, "activity:object-type", self::constructObjecttype($repeated_item));
1648 $title = sprintf("New comment by %s", $contact["nick"]);
1650 self::entryContent($doc, $as_object2, $repeated_item, $owner, $title);
1652 $as_object->appendChild($as_object2);
1654 self::entryFooter($doc, $as_object, $item, $owner, false);
1656 $source = self::sourceEntry($doc, $contact);
1658 $as_object->appendChild($source);
1660 $entry->appendChild($as_object);
1662 self::entryFooter($doc, $entry, $item, $owner);
1668 * @brief Adds an entry element with a "like"
1670 * @param object $doc XML document
1671 * @param array $item Data of the item that is to be posted
1672 * @param array $owner Contact data of the poster
1673 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1675 * @return object Entry element with "like"
1677 private static function likeEntry($doc, $item, $owner, $toplevel)
1679 if (($item["id"] != $item["parent"]) && (normalise_link($item["author-link"]) != normalise_link($owner["url"]))) {
1680 logger("OStatus entry is from author ".$owner["url"]." - not from ".$item["author-link"].". Quitting.", LOGGER_DEBUG);
1683 $title = self::entryHeader($doc, $entry, $owner, $toplevel);
1685 $verb = NAMESPACE_ACTIVITY_SCHEMA."favorite";
1686 self::entryContent($doc, $entry, $item, $owner, "Favorite", $verb, false);
1688 $as_object = $doc->createElement("activity:object");
1691 "SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d",
1692 dbesc($item["thr-parent"]),
1693 intval($item["uid"])
1695 $parent_item = (($item['thr-parent']) ? $item['thr-parent'] : $item['parent-uri']);
1697 XML::addElement($doc, $as_object, "activity:object-type", self::constructObjecttype($parent[0]));
1699 self::entryContent($doc, $as_object, $parent[0], $owner, "New entry");
1701 $entry->appendChild($as_object);
1703 self::entryFooter($doc, $entry, $item, $owner);
1709 * @brief Adds the person object element to the XML document
1711 * @param object $doc XML document
1712 * @param array $owner Contact data of the poster
1713 * @param array $contact Contact data of the target
1715 * @return object author element
1717 private static function addPersonObject($doc, $owner, $contact)
1719 $object = $doc->createElement("activity:object");
1720 XML::addElement($doc, $object, "activity:object-type", ACTIVITY_OBJ_PERSON);
1722 if ($contact['network'] == NETWORK_PHANTOM) {
1723 XML::addElement($doc, $object, "id", $contact['url']);
1727 XML::addElement($doc, $object, "id", $contact["alias"]);
1728 XML::addElement($doc, $object, "title", $contact["nick"]);
1730 $attributes = array("rel" => "alternate", "type" => "text/html", "href" => $contact["url"]);
1731 XML::addElement($doc, $object, "link", "", $attributes);
1733 $attributes = array(
1735 "type" => "image/jpeg", // To-Do?
1736 "media:width" => 175,
1737 "media:height" => 175,
1738 "href" => $contact["photo"]);
1739 XML::addElement($doc, $object, "link", "", $attributes);
1741 XML::addElement($doc, $object, "poco:preferredUsername", $contact["nick"]);
1742 XML::addElement($doc, $object, "poco:displayName", $contact["name"]);
1744 if (trim($contact["location"]) != "") {
1745 $element = $doc->createElement("poco:address");
1746 XML::addElement($doc, $element, "poco:formatted", $contact["location"]);
1747 $object->appendChild($element);
1754 * @brief Adds a follow/unfollow entry element
1756 * @param object $doc XML document
1757 * @param array $item Data of the follow/unfollow message
1758 * @param array $owner Contact data of the poster
1759 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1761 * @return object Entry element
1763 private static function followEntry($doc, $item, $owner, $toplevel)
1765 $item["id"] = $item["parent"] = 0;
1766 $item["created"] = $item["edited"] = date("c");
1767 $item["private"] = true;
1769 $contact = Probe::uri($item['follow']);
1771 if ($contact['alias'] == '') {
1772 $contact['alias'] = $contact["url"];
1774 $item['follow'] = $contact['alias'];
1778 "SELECT `id` FROM `contact` WHERE `uid` = %d AND `nurl` = '%s'",
1779 intval($owner['uid']),
1780 dbesc(normalise_link($contact["url"]))
1783 if (DBM::is_result($r)) {
1784 $connect_id = $r[0]['id'];
1789 if ($item['verb'] == ACTIVITY_FOLLOW) {
1790 $message = t('%s is now following %s.');
1791 $title = t('following');
1792 $action = "subscription";
1794 $message = t('%s stopped following %s.');
1795 $title = t('stopped following');
1796 $action = "unfollow";
1799 $item["uri"] = $item['parent-uri'] = $item['thr-parent']
1800 = 'tag:'.get_app()->get_hostname().
1801 ','.date('Y-m-d').':'.$action.':'.$owner['uid'].
1802 ':person:'.$connect_id.':'.$item['created'];
1804 $item["body"] = sprintf($message, $owner["nick"], $contact["nick"]);
1806 self::entryHeader($doc, $entry, $owner, $toplevel);
1808 self::entryContent($doc, $entry, $item, $owner, $title);
1810 $object = self::addPersonObject($doc, $owner, $contact);
1811 $entry->appendChild($object);
1813 self::entryFooter($doc, $entry, $item, $owner);
1819 * @brief Adds a regular entry element
1821 * @param object $doc XML document
1822 * @param array $item Data of the item that is to be posted
1823 * @param array $owner Contact data of the poster
1824 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1826 * @return object Entry element
1828 private static function noteEntry($doc, $item, $owner, $toplevel)
1830 if (($item["id"] != $item["parent"]) && (normalise_link($item["author-link"]) != normalise_link($owner["url"]))) {
1831 logger("OStatus entry is from author ".$owner["url"]." - not from ".$item["author-link"].". Quitting.", LOGGER_DEBUG);
1834 $title = self::entryHeader($doc, $entry, $owner, $toplevel);
1836 XML::addElement($doc, $entry, "activity:object-type", ACTIVITY_OBJ_NOTE);
1838 self::entryContent($doc, $entry, $item, $owner, $title);
1840 self::entryFooter($doc, $entry, $item, $owner);
1846 * @brief Adds a header element to the XML document
1848 * @param object $doc XML document
1849 * @param object $entry The entry element where the elements are added
1850 * @param array $owner Contact data of the poster
1851 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1853 * @return string The title for the element
1855 private static function entryHeader($doc, &$entry, $owner, $toplevel)
1857 /// @todo Check if this title stuff is really needed (I guess not)
1859 $entry = $doc->createElement("entry");
1860 $title = sprintf("New note by %s", $owner["nick"]);
1862 $entry = $doc->createElementNS(NAMESPACE_ATOM1, "entry");
1864 $entry->setAttribute("xmlns:thr", NAMESPACE_THREAD);
1865 $entry->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
1866 $entry->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
1867 $entry->setAttribute("xmlns:media", NAMESPACE_MEDIA);
1868 $entry->setAttribute("xmlns:poco", NAMESPACE_POCO);
1869 $entry->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
1870 $entry->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
1871 $entry->setAttribute("xmlns:mastodon", NAMESPACE_MASTODON);
1873 $author = self::addAuthor($doc, $owner);
1874 $entry->appendChild($author);
1876 $title = sprintf("New comment by %s", $owner["nick"]);
1882 * @brief Adds elements to the XML document
1884 * @param object $doc XML document
1885 * @param object $entry Entry element where the content is added
1886 * @param array $item Data of the item that is to be posted
1887 * @param array $owner Contact data of the poster
1888 * @param string $title Title for the post
1889 * @param string $verb The activity verb
1890 * @param bool $complete Add the "status_net" element?
1893 private static function entryContent($doc, $entry, $item, $owner, $title, $verb = "", $complete = true)
1896 $verb = self::constructVerb($item);
1899 XML::addElement($doc, $entry, "id", $item["uri"]);
1900 XML::addElement($doc, $entry, "title", $title);
1902 $body = self::formatPicturePost($item['body']);
1904 if ($item['title'] != "") {
1905 $body = "[b]".$item['title']."[/b]\n\n".$body;
1908 $body = bbcode($body, false, false, 7);
1910 XML::addElement($doc, $entry, "content", $body, array("type" => "html"));
1912 XML::addElement($doc, $entry, "link", "", array("rel" => "alternate", "type" => "text/html",
1913 "href" => System::baseUrl()."/display/".$item["guid"])
1916 if ($complete && ($item["id"] > 0)) {
1917 XML::addElement($doc, $entry, "status_net", "", array("notice_id" => $item["id"]));
1920 XML::addElement($doc, $entry, "activity:verb", $verb);
1922 XML::addElement($doc, $entry, "published", datetime_convert("UTC", "UTC", $item["created"]."+00:00", ATOM_TIME));
1923 XML::addElement($doc, $entry, "updated", datetime_convert("UTC", "UTC", $item["edited"]."+00:00", ATOM_TIME));
1927 * @brief Adds the elements at the foot of an entry to the XML document
1929 * @param object $doc XML document
1930 * @param object $entry The entry element where the elements are added
1931 * @param array $item Data of the item that is to be posted
1932 * @param array $owner Contact data of the poster
1933 * @param bool $complete default true
1936 private static function entryFooter($doc, $entry, $item, $owner, $complete = true)
1938 $mentioned = array();
1940 if (($item['parent'] != $item['id']) || ($item['parent-uri'] !== $item['uri']) || (($item['thr-parent'] !== '') && ($item['thr-parent'] !== $item['uri']))) {
1941 $parent = q("SELECT `guid`, `author-link`, `owner-link` FROM `item` WHERE `id` = %d", intval($item["parent"]));
1942 $parent_item = (($item['thr-parent']) ? $item['thr-parent'] : $item['parent-uri']);
1945 "SELECT `guid`, `author-link`, `owner-link`, `plink` FROM `item` WHERE `uid` = %d AND `uri` = '%s'",
1946 intval($owner["uid"]),
1950 $mentioned[$thrparent[0]["author-link"]] = $thrparent[0]["author-link"];
1951 $mentioned[$thrparent[0]["owner-link"]] = $thrparent[0]["owner-link"];
1952 $parent_plink = $thrparent[0]["plink"];
1954 $mentioned[$parent[0]["author-link"]] = $parent[0]["author-link"];
1955 $mentioned[$parent[0]["owner-link"]] = $parent[0]["owner-link"];
1956 $parent_plink = System::baseUrl()."/display/".$parent[0]["guid"];
1959 $attributes = array(
1960 "ref" => $parent_item,
1961 "href" => $parent_plink);
1962 XML::addElement($doc, $entry, "thr:in-reply-to", "", $attributes);
1964 $attributes = array(
1966 "href" => $parent_plink);
1967 XML::addElement($doc, $entry, "link", "", $attributes);
1970 if (intval($item["parent"]) > 0) {
1971 $conversation_href = System::baseUrl()."/display/".$owner["nick"]."/".$item["parent"];
1972 $conversation_uri = $conversation_href;
1974 if (isset($parent_item)) {
1975 $r = dba::fetch_first("SELECT `conversation-uri`, `conversation-href` FROM `conversation` WHERE `item-uri` = ?", $parent_item);
1976 if (DBM::is_result($r)) {
1977 if ($r['conversation-uri'] != '') {
1978 $conversation_uri = $r['conversation-uri'];
1980 if ($r['conversation-href'] != '') {
1981 $conversation_href = $r['conversation-href'];
1986 XML::addElement($doc, $entry, "link", "", array("rel" => "ostatus:conversation", "href" => $conversation_href));
1988 $attributes = array(
1989 "href" => $conversation_href,
1990 "local_id" => $item["parent"],
1991 "ref" => $conversation_uri);
1993 XML::addElement($doc, $entry, "ostatus:conversation", $conversation_uri, $attributes);
1996 $tags = item_getfeedtags($item);
1999 foreach ($tags as $t) {
2001 $mentioned[$t[1]] = $t[1];
2006 // Make sure that mentions are accepted (GNU Social has problems with mixing HTTP and HTTPS)
2007 $newmentions = array();
2008 foreach ($mentioned as $mention) {
2009 $newmentions[str_replace("http://", "https://", $mention)] = str_replace("http://", "https://", $mention);
2010 $newmentions[str_replace("https://", "http://", $mention)] = str_replace("https://", "http://", $mention);
2012 $mentioned = $newmentions;
2014 foreach ($mentioned as $mention) {
2016 "SELECT `forum`, `prv` FROM `contact` WHERE `uid` = %d AND `nurl` = '%s'",
2017 intval($owner["uid"]),
2018 dbesc(normalise_link($mention))
2020 if ($r[0]["forum"] || $r[0]["prv"]) {
2021 XML::addElement($doc, $entry, "link", "",
2023 "rel" => "mentioned",
2024 "ostatus:object-type" => ACTIVITY_OBJ_GROUP,
2028 XML::addElement($doc, $entry, "link", "",
2030 "rel" => "mentioned",
2031 "ostatus:object-type" => ACTIVITY_OBJ_PERSON,
2037 if (!$item["private"]) {
2038 XML::addElement($doc, $entry, "link", "", array("rel" => "ostatus:attention",
2039 "href" => "http://activityschema.org/collection/public"));
2040 XML::addElement($doc, $entry, "link", "", array("rel" => "mentioned",
2041 "ostatus:object-type" => "http://activitystrea.ms/schema/1.0/collection",
2042 "href" => "http://activityschema.org/collection/public"));
2043 XML::addElement($doc, $entry, "mastodon:scope", "public");
2047 foreach ($tags as $t) {
2049 XML::addElement($doc, $entry, "category", "", array("term" => $t[2]));
2054 self::getAttachment($doc, $entry, $item);
2056 if ($complete && ($item["id"] > 0)) {
2057 $app = $item["app"];
2062 $attributes = array("local_id" => $item["id"], "source" => $app);
2064 if (isset($parent["id"])) {
2065 $attributes["repeat_of"] = $parent["id"];
2068 if ($item["coord"] != "") {
2069 XML::addElement($doc, $entry, "georss:point", $item["coord"]);
2072 XML::addElement($doc, $entry, "statusnet:notice_info", "", $attributes);
2077 * Creates the XML feed for a given nickname
2079 * Supported filters:
2080 * - activity (default): all the public posts
2081 * - posts: all the public top-level posts
2082 * - comments: all the public replies
2084 * Updates the provided last_update parameter if the result comes from the
2085 * cache or it is empty
2087 * @brief Creates the XML feed for a given nickname
2089 * @param string $owner_nick Nickname of the feed owner
2090 * @param string $last_update Date of the last update
2091 * @param integer $max_items Number of maximum items to fetch
2092 * @param string $filter Feed items filter (activity, posts or comments)
2093 * @param boolean $nocache Wether to bypass caching
2095 * @return string XML feed
2097 public static function feed($owner_nick, &$last_update, $max_items = 300, $filter = 'activity', $nocache = false)
2099 $stamp = microtime(true);
2101 $cachekey = "ostatus:feed:" . $owner_nick . ":" . $filter . ":" . $last_update;
2103 $previous_created = $last_update;
2105 $result = Cache::get($cachekey);
2106 if (!$nocache && !is_null($result)) {
2107 logger('Feed duration: ' . number_format(microtime(true) - $stamp, 3) . ' - ' . $owner_nick . ' - ' . $filter . ' - ' . $previous_created . ' (cached)', LOGGER_DEBUG);
2108 $last_update = $result['last_update'];
2109 return $result['feed'];
2112 $owner = dba::fetch_first(
2113 "SELECT `contact`.*, `user`.`nickname`, `user`.`timezone`, `user`.`page-flags`
2114 FROM `contact` INNER JOIN `user` ON `user`.`uid` = `contact`.`uid`
2115 WHERE `contact`.`self` AND `user`.`nickname` = ? LIMIT 1",
2118 if (!DBM::is_result($owner)) {
2122 if (!strlen($last_update)) {
2123 $last_update = 'now -30 days';
2126 $check_date = datetime_convert('UTC', 'UTC', $last_update, 'Y-m-d H:i:s');
2127 $authorid = Contact::getIdForURL($owner["url"], 0);
2130 if ($filter === 'posts') {
2131 $sql_extra .= ' AND `item`.`id` = `item`.`parent` ';
2134 if ($filter === 'comments') {
2135 $sql_extra .= sprintf(" AND `item`.`object-type` = '%s' ", dbesc(ACTIVITY_OBJ_COMMENT));
2139 "SELECT `item`.*, `item`.`id` AS `item_id` FROM `item` USE INDEX (`uid_contactid_created`)
2140 STRAIGHT_JOIN `thread` ON `thread`.`iid` = `item`.`parent`
2141 WHERE `item`.`uid` = %d
2142 AND `item`.`contact-id` = %d
2143 AND `item`.`author-id` = %d
2144 AND `item`.`created` > '%s'
2145 AND NOT `item`.`deleted`
2146 AND NOT `item`.`private`
2147 AND `thread`.`network` IN ('%s', '%s')
2149 ORDER BY `item`.`created` DESC LIMIT %d",
2150 intval($owner["uid"]),
2151 intval($owner["id"]),
2154 dbesc(NETWORK_OSTATUS),
2155 dbesc(NETWORK_DFRN),
2159 $doc = new DOMDocument('1.0', 'utf-8');
2160 $doc->formatOutput = true;
2162 $root = self::addHeader($doc, $owner, $filter);
2164 foreach ($items as $item) {
2165 if (Config::get('system', 'ostatus_debug')) {
2166 $item['body'] .= '🍼';
2168 $entry = self::entry($doc, $item, $owner);
2169 $root->appendChild($entry);
2171 if ($last_update < $item['created']) {
2172 $last_update = $item['created'];
2176 $feeddata = trim($doc->saveXML());
2178 $msg = array('feed' => $feeddata, 'last_update' => $last_update);
2179 Cache::set($cachekey, $msg, CACHE_QUARTER_HOUR);
2181 logger('Feed duration: ' . number_format(microtime(true) - $stamp, 3) . ' - ' . $owner_nick . ' - ' . $filter . ' - ' . $previous_created, LOGGER_DEBUG);
2187 * @brief Creates the XML for a salmon message
2189 * @param array $item Data of the item that is to be posted
2190 * @param array $owner Contact data of the poster
2192 * @return string XML for the salmon
2194 public static function salmon($item, $owner)
2196 $doc = new DOMDocument('1.0', 'utf-8');
2197 $doc->formatOutput = true;
2199 if (Config::get('system', 'ostatus_debug')) {
2200 $item['body'] .= '🐟';
2203 $entry = self::entry($doc, $item, $owner, true);
2205 $doc->appendChild($entry);
2207 return trim($doc->saveXML());