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\GlobalContact;
13 use Friendica\Network\Probe;
14 use Friendica\Object\Contact;
15 use Friendica\Object\Photo;
16 use Friendica\Util\Lock;
17 use Friendica\Util\XML;
22 require_once 'include/threads.php';
23 require_once 'include/html2bbcode.php';
24 require_once 'include/bbcode.php';
25 require_once 'include/items.php';
26 require_once 'mod/share.php';
27 require_once 'include/enotify.php';
28 require_once 'include/follow.php';
29 require_once 'include/api.php';
30 require_once 'mod/proxy.php';
33 * @brief This class contain functions for the OStatus protocol
37 private static $itemlist;
38 private static $conv_list = array();
41 * @brief Fetches author data
43 * @param object $xpath The xpath object
44 * @param object $context The xml context of the author details
45 * @param array $importer user record of the importing user
46 * @param array $contact Called by reference, will contain the fetched contact
47 * @param bool $onlyfetch Only fetch the header without updating the contact entries
49 * @return array Array of author related entries for the item
51 private static function fetchAuthor($xpath, $context, $importer, &$contact, $onlyfetch)
54 $author["author-link"] = $xpath->evaluate('atom:author/atom:uri/text()', $context)->item(0)->nodeValue;
55 $author["author-name"] = $xpath->evaluate('atom:author/atom:name/text()', $context)->item(0)->nodeValue;
56 $addr = $xpath->evaluate('atom:author/atom:email/text()', $context)->item(0)->nodeValue;
58 $aliaslink = $author["author-link"];
60 $alternate = $xpath->query("atom:author/atom:link[@rel='alternate']", $context)->item(0)->attributes;
61 if (is_object($alternate)) {
62 foreach ($alternate as $attributes) {
63 if (($attributes->name == "href") && ($attributes->textContent != "")) {
64 $author["author-link"] = $attributes->textContent;
68 $author["contact-id"] = $contact["id"];
72 if ($aliaslink != '') {
73 $condition = array("`uid` = ? AND `alias` = ? AND `network` != ?",
74 $importer["uid"], $aliaslink, NETWORK_STATUSNET);
75 $r = dba::select('contact', array(), $condition, array('limit' => 1));
77 if (DBM::is_result($r)) {
83 $author["contact-id"] = $r["id"];
87 if (!$found && ($author["author-link"] != "")) {
88 if ($aliaslink == "") {
89 $aliaslink = $author["author-link"];
92 $condition = array("`uid` = ? AND `nurl` IN (?, ?) AND `network` != ?", $importer["uid"],
93 normalise_link($author["author-link"]), normalise_link($aliaslink), NETWORK_STATUSNET);
94 $r = dba::select('contact', array(), $condition, array('limit' => 1));
96 if (DBM::is_result($r)) {
102 $author["contact-id"] = $r["id"];
106 if (!$found && ($addr != "")) {
107 $condition = array("`uid` = ? AND `addr` = ? AND `network` != ?",
108 $importer["uid"], $addr, NETWORK_STATUSNET);
109 $r = dba::select('contact', array(), $condition, array('limit' => 1));
111 if (DBM::is_result($r)) {
117 $author["contact-id"] = $r["id"];
121 $avatarlist = array();
122 $avatars = $xpath->query("atom:author/atom:link[@rel='avatar']", $context);
123 foreach ($avatars as $avatar) {
126 foreach ($avatar->attributes as $attributes) {
127 if ($attributes->name == "href") {
128 $href = $attributes->textContent;
130 if ($attributes->name == "width") {
131 $width = $attributes->textContent;
135 $avatarlist[$width] = $href;
138 if (count($avatarlist) > 0) {
140 $author["author-avatar"] = Probe::fixAvatar(current($avatarlist), $author["author-link"]);
143 $displayname = $xpath->evaluate('atom:author/poco:displayName/text()', $context)->item(0)->nodeValue;
144 if ($displayname != "") {
145 $author["author-name"] = $displayname;
148 $author["owner-name"] = $author["author-name"];
149 $author["owner-link"] = $author["author-link"];
150 $author["owner-avatar"] = $author["author-avatar"];
152 // Only update the contacts if it is an OStatus contact
153 if ($r && ($r['id'] > 0) && !$onlyfetch && ($contact["network"] == NETWORK_OSTATUS)) {
154 // This contact is vital, so we awake it from the dead
155 Contact::unmarkForArchival($contact);
157 // Update contact data
160 unset($current['name-date']);
162 // This query doesn't seem to work
163 // $value = $xpath->query("atom:link[@rel='salmon']", $context)->item(0)->nodeValue;
165 // $contact["notify"] = $value;
167 // This query doesn't seem to work as well - I hate these queries
168 // $value = $xpath->query("atom:link[@rel='self' and @type='application/atom+xml']", $context)->item(0)->nodeValue;
170 // $contact["poll"] = $value;
172 $contact['url'] = $author["author-link"];
173 $contact['nurl'] = normalise_link($contact['url']);
175 $value = $xpath->evaluate('atom:author/atom:uri/text()', $context)->item(0)->nodeValue;
177 $contact["alias"] = $value;
180 $value = $xpath->evaluate('atom:author/poco:displayName/text()', $context)->item(0)->nodeValue;
182 $contact["name"] = $value;
185 $value = $xpath->evaluate('atom:author/poco:preferredUsername/text()', $context)->item(0)->nodeValue;
187 $contact["nick"] = $value;
190 $value = $xpath->evaluate('atom:author/poco:note/text()', $context)->item(0)->nodeValue;
192 $contact["about"] = html2bbcode($value);
195 $value = $xpath->evaluate('atom:author/poco:address/poco:formatted/text()', $context)->item(0)->nodeValue;
197 $contact["location"] = $value;
200 $contact['name-date'] = datetime_convert();
202 dba::update('contact', $contact, array('id' => $contact["id"]), $current);
204 if (!empty($author["author-avatar"]) && ($author["author-avatar"] != $current['avatar'])) {
205 logger("Update profile picture for contact ".$contact["id"], LOGGER_DEBUG);
206 update_contact_avatar($author["author-avatar"], $importer["uid"], $contact["id"]);
209 // Ensure that we are having this contact (with uid=0)
210 $cid = Contact::getIdForURL($aliaslink, 0);
213 $fields = array('url', 'nurl', 'name', 'nick', 'alias', 'about', 'location');
214 $old_contact = dba::select('contact', $fields, array('id' => $cid), array('limit' => 1));
216 // Update it with the current values
217 $fields = array('url' => $author["author-link"], 'name' => $contact["name"],
218 'nurl' => normalise_link($author["author-link"]),
219 'nick' => $contact["nick"], 'alias' => $contact["alias"],
220 'about' => $contact["about"], 'location' => $contact["location"],
221 'success_update' => datetime_convert(), 'last-update' => datetime_convert());
223 dba::update('contact', $fields, array('id' => $cid), $old_contact);
226 update_contact_avatar($author["author-avatar"], 0, $cid);
229 $contact["generation"] = 2;
230 $contact["hide"] = false; // OStatus contacts are never hidden
231 $contact["photo"] = $author["author-avatar"];
232 $gcid = GlobalContact::update($contact);
234 GlobalContact::link($gcid, $contact["uid"], $contact["id"]);
241 * @brief Fetches author data from a given XML string
243 * @param string $xml The XML
244 * @param array $importer user record of the importing user
246 * @return array Array of author related entries for the item
248 public static function salmonAuthor($xml, $importer)
254 $doc = new DOMDocument();
255 @$doc->loadXML($xml);
257 $xpath = new DomXPath($doc);
258 $xpath->registerNamespace('atom', NAMESPACE_ATOM1);
259 $xpath->registerNamespace('thr', NAMESPACE_THREAD);
260 $xpath->registerNamespace('georss', NAMESPACE_GEORSS);
261 $xpath->registerNamespace('activity', NAMESPACE_ACTIVITY);
262 $xpath->registerNamespace('media', NAMESPACE_MEDIA);
263 $xpath->registerNamespace('poco', NAMESPACE_POCO);
264 $xpath->registerNamespace('ostatus', NAMESPACE_OSTATUS);
265 $xpath->registerNamespace('statusnet', NAMESPACE_STATUSNET);
267 $entries = $xpath->query('/atom:entry');
269 foreach ($entries as $entry) {
271 $author = self::fetchAuthor($xpath, $entry, $importer, $contact, true);
277 * @brief Read attributes from element
279 * @param object $element Element object
281 * @return array attributes
283 private static function readAttributes($element)
285 $attribute = array();
287 foreach ($element->attributes as $attributes) {
288 $attribute[$attributes->name] = $attributes->textContent;
295 * @brief Imports an XML string containing OStatus elements
297 * @param string $xml The XML
298 * @param array $importer user record of the importing user
299 * @param array $contact contact
300 * @param string $hub Called by reference, returns the fetched hub data
303 public static function import($xml, $importer, &$contact, &$hub)
305 self::process($xml, $importer, $contact, $hub);
309 * @brief Internal feed processing
311 * @param string $xml The XML
312 * @param array $importer user record of the importing user
313 * @param array $contact contact
314 * @param string $hub Called by reference, returns the fetched hub data
315 * @param boolean $stored Is the post fresh imported or from the database?
316 * @param boolean $initialize Is it the leading post so that data has to be initialized?
318 * @return boolean Could the XML be processed?
320 private static function process($xml, $importer, &$contact, &$hub, $stored = false, $initialize = true)
323 self::$itemlist = array();
324 self::$conv_list = array();
327 logger("Import OStatus message", LOGGER_DEBUG);
332 $doc = new DOMDocument();
333 @$doc->loadXML($xml);
335 $xpath = new DomXPath($doc);
336 $xpath->registerNamespace('atom', NAMESPACE_ATOM1);
337 $xpath->registerNamespace('thr', NAMESPACE_THREAD);
338 $xpath->registerNamespace('georss', NAMESPACE_GEORSS);
339 $xpath->registerNamespace('activity', NAMESPACE_ACTIVITY);
340 $xpath->registerNamespace('media', NAMESPACE_MEDIA);
341 $xpath->registerNamespace('poco', NAMESPACE_POCO);
342 $xpath->registerNamespace('ostatus', NAMESPACE_OSTATUS);
343 $xpath->registerNamespace('statusnet', NAMESPACE_STATUSNET);
346 $hub_attributes = $xpath->query("/atom:feed/atom:link[@rel='hub']")->item(0)->attributes;
347 if (is_object($hub_attributes)) {
348 foreach ($hub_attributes as $hub_attribute) {
349 if ($hub_attribute->name == "href") {
350 $hub = $hub_attribute->textContent;
351 logger("Found hub ".$hub, LOGGER_DEBUG);
357 $header["uid"] = $importer["uid"];
358 $header["network"] = NETWORK_OSTATUS;
359 $header["type"] = "remote";
361 $header["origin"] = 0;
362 $header["gravity"] = GRAVITY_PARENT;
364 $first_child = $doc->firstChild->tagName;
366 if ($first_child == "feed") {
367 $entries = $xpath->query('/atom:feed/atom:entry');
369 $entries = $xpath->query('/atom:entry');
372 if ($entries->length == 1) {
373 // We reformat the XML to make it better readable
374 $doc2 = new DOMDocument();
375 $doc2->loadXML($xml);
376 $doc2->preserveWhiteSpace = false;
377 $doc2->formatOutput = true;
378 $xml2 = $doc2->saveXML();
380 $header["protocol"] = PROTOCOL_OSTATUS_SALMON;
381 $header["source"] = $xml2;
382 } elseif (!$initialize) {
386 // Fetch the first author
387 $authordata = $xpath->query('//author')->item(0);
388 $author = self::fetchAuthor($xpath, $authordata, $importer, $contact, $stored);
390 $entry = $xpath->query('/atom:entry');
392 // Reverse the order of the entries
393 $entrylist = array();
395 foreach ($entries as $entry) {
396 $entrylist[] = $entry;
399 foreach (array_reverse($entrylist) as $entry) {
401 $authorelement = $xpath->query('/atom:entry/atom:author', $entry);
403 if ($authorelement->length == 0) {
404 $authorelement = $xpath->query('atom:author', $entry);
407 if ($authorelement->length > 0) {
408 $author = self::fetchAuthor($xpath, $entry, $importer, $contact, $stored);
411 $value = $xpath->evaluate('atom:author/poco:preferredUsername/text()', $entry)->item(0)->nodeValue;
415 $nickname = $author["author-name"];
418 $item = array_merge($header, $author);
420 $item["uri"] = $xpath->query('atom:id/text()', $entry)->item(0)->nodeValue;
422 $item["verb"] = $xpath->query('activity:verb/text()', $entry)->item(0)->nodeValue;
425 if (in_array($item["verb"], array('qvitter-delete-notice', ACTIVITY_DELETE, 'delete'))) {
426 self::deleteNotice($item);
430 if (in_array($item["verb"], array(NAMESPACE_OSTATUS."/unfavorite", ACTIVITY_UNFAVORITE))) {
431 // Ignore "Unfavorite" message
432 logger("Ignore unfavorite message ".print_r($item, true), LOGGER_DEBUG);
436 // Deletions come with the same uri, so we check for duplicates after processing deletions
437 if (dba::exists('item', array('uid' => $importer["uid"], 'uri' => $item["uri"]))) {
438 logger('Post with URI '.$item["uri"].' already existed for user '.$importer["uid"].'.', LOGGER_DEBUG);
441 logger('Processing post with URI '.$item["uri"].' for user '.$importer["uid"].'.', LOGGER_DEBUG);
444 if ($item["verb"] == ACTIVITY_JOIN) {
445 // ignore "Join" messages
446 logger("Ignore join message ".print_r($item, true), LOGGER_DEBUG);
450 if ($item["verb"] == "http://mastodon.social/schema/1.0/block") {
451 // ignore mastodon "block" messages
452 logger("Ignore block message ".print_r($item, true), LOGGER_DEBUG);
456 if ($item["verb"] == ACTIVITY_FOLLOW) {
457 new_follower($importer, $contact, $item, $nickname);
461 if ($item["verb"] == NAMESPACE_OSTATUS."/unfollow") {
462 lose_follower($importer, $contact, $item, $dummy);
466 if ($item["verb"] == ACTIVITY_FAVORITE) {
467 $orig_uri = $xpath->query("activity:object/atom:id", $entry)->item(0)->nodeValue;
468 logger("Favorite ".$orig_uri." ".print_r($item, true));
470 $item["verb"] = ACTIVITY_LIKE;
471 $item["parent-uri"] = $orig_uri;
472 $item["gravity"] = GRAVITY_LIKE;
475 // http://activitystrea.ms/schema/1.0/rsvp-yes
476 if (!in_array($item["verb"], array(ACTIVITY_POST, ACTIVITY_LIKE, ACTIVITY_SHARE))) {
477 logger("Unhandled verb ".$item["verb"]." ".print_r($item, true), LOGGER_DEBUG);
480 self::processPost($xpath, $entry, $item, $importer);
482 if ($initialize && (count(self::$itemlist) > 0)) {
483 if (self::$itemlist[0]['uri'] == self::$itemlist[0]['parent-uri']) {
484 // We will import it everytime, when it is started by our contacts
485 $valid = !empty(self::$itemlist[0]['contact-id']);
487 // If not, then it depends on this setting
488 $valid = !Config::get('system', 'ostatus_full_threads');
491 // Never post a thread when the only interaction by our contact was a like
493 $verbs = array(ACTIVITY_POST, ACTIVITY_SHARE);
494 foreach (self::$itemlist as $item) {
495 if (!empty($item['contact-id']) && in_array($item['verb'], $verbs)) {
501 // But we will only import complete threads
502 $valid = dba::exists('item', array('uid' => $importer["uid"], 'uri' => self::$itemlist[0]['parent-uri']));
506 $default_contact = 0;
507 $key = count(self::$itemlist);
508 for ($key = count(self::$itemlist) - 1; $key >= 0; $key--) {
509 if (empty(self::$itemlist[$key]['contact-id'])) {
510 self::$itemlist[$key]['contact-id'] = $default_contact;
512 $default_contact = $item['contact-id'];
515 foreach (self::$itemlist as $item) {
516 $found = dba::exists('item', array('uid' => $importer["uid"], 'uri' => $item["uri"]));
518 logger("Item with uri ".$item["uri"]." for user ".$importer["uid"]." already exists.", LOGGER_DEBUG);
519 } elseif ($item['contact-id'] < 0) {
520 logger("Item with uri ".$item["uri"]." is from a blocked contact.", LOGGER_DEBUG);
522 // We are having duplicated entries. Hopefully this solves it.
523 if (Lock::set('ostatus_process_item_store')) {
524 $ret = item_store($item);
525 Lock::remove('ostatus_process_item_store');
526 logger("Item with uri ".$item["uri"]." for user ".$importer["uid"].' stored. Return value: '.$ret);
528 $ret = item_store($item);
529 logger("We couldn't lock - but tried to store the item anyway. Return value is ".$ret);
534 self::$itemlist = array();
536 logger('Processing done for post with URI '.$item["uri"].' for user '.$importer["uid"].'.', LOGGER_DEBUG);
542 * @param object $item item
545 private static function deleteNotice($item)
547 $condition = array('uid' => $item['uid'], 'author-link' => $item['author-link'], 'uri' => $item['uri']);
548 $deleted = dba::select('item', array('id', 'parent-uri'), $condition, array('limit' => 1));
549 if (!DBM::is_result($deleted)) {
550 logger('Item from '.$item['author-link'].' with uri '.$item['uri'].' for user '.$item['uid']." wasn't found. We don't delete it. ");
554 // Currently we don't have a central deletion function that we could use in this case
555 // The function "item_drop" doesn't work for that case
558 array('deleted' => true, 'title' => '', 'body' => '',
559 'edited' => datetime_convert(), 'changed' => datetime_convert()),
560 array('id' => $deleted["id"])
563 delete_thread($deleted["id"], $deleted["parent-uri"]);
565 logger('Deleted item with uri '.$item['uri'].' for user '.$item['uid']);
569 * @brief Processes the XML for a post
571 * @param object $xpath The xpath object
572 * @param object $entry The xml entry that is processed
573 * @param array $item The item array
574 * @param array $importer user record of the importing user
577 private static function processPost($xpath, $entry, &$item, $importer)
579 $item["body"] = html2bbcode($xpath->query('atom:content/text()', $entry)->item(0)->nodeValue);
580 $item["object-type"] = $xpath->query('activity:object-type/text()', $entry)->item(0)->nodeValue;
581 if (($item["object-type"] == ACTIVITY_OBJ_BOOKMARK) || ($item["object-type"] == ACTIVITY_OBJ_EVENT)) {
582 $item["title"] = $xpath->query('atom:title/text()', $entry)->item(0)->nodeValue;
583 $item["body"] = $xpath->query('atom:summary/text()', $entry)->item(0)->nodeValue;
584 } elseif ($item["object-type"] == ACTIVITY_OBJ_QUESTION) {
585 $item["title"] = $xpath->query('atom:title/text()', $entry)->item(0)->nodeValue;
588 $item["created"] = $xpath->query('atom:published/text()', $entry)->item(0)->nodeValue;
589 $item["edited"] = $xpath->query('atom:updated/text()', $entry)->item(0)->nodeValue;
590 $conversation = $xpath->query('ostatus:conversation/text()', $entry)->item(0)->nodeValue;
591 $item['conversation-uri'] = $conversation;
593 $conv = $xpath->query('ostatus:conversation', $entry);
594 if (is_object($conv->item(0))) {
595 foreach ($conv->item(0)->attributes as $attributes) {
596 if ($attributes->name == "ref") {
597 $item['conversation-uri'] = $attributes->textContent;
599 if ($attributes->name == "href") {
600 $item['conversation-href'] = $attributes->textContent;
607 $inreplyto = $xpath->query('thr:in-reply-to', $entry);
608 if (is_object($inreplyto->item(0))) {
609 foreach ($inreplyto->item(0)->attributes as $attributes) {
610 if ($attributes->name == "ref") {
611 $item["parent-uri"] = $attributes->textContent;
613 if ($attributes->name == "href") {
614 $related = $attributes->textContent;
619 $georsspoint = $xpath->query('georss:point', $entry);
620 if (!empty($georsspoint) && ($georsspoint->length > 0)) {
621 $item["coord"] = $georsspoint->item(0)->nodeValue;
624 $categories = $xpath->query('atom:category', $entry);
626 foreach ($categories as $category) {
627 foreach ($category->attributes as $attributes) {
628 if ($attributes->name == "term") {
629 $term = $attributes->textContent;
630 if (strlen($item["tag"])) {
633 $item["tag"] .= "#[url=".System::baseUrl()."/search?tag=".$term."]".$term."[/url]";
642 $links = $xpath->query('atom:link', $entry);
644 $link_data = self::processLinks($links, $item);
645 $self = $link_data['self'];
646 $add_body = $link_data['add_body'];
651 $notice_info = $xpath->query('statusnet:notice_info', $entry);
652 if ($notice_info && ($notice_info->length > 0)) {
653 foreach ($notice_info->item(0)->attributes as $attributes) {
654 if ($attributes->name == "source") {
655 $item["app"] = strip_tags($attributes->textContent);
657 if ($attributes->name == "repeat_of") {
658 $repeat_of = $attributes->textContent;
662 // Is it a repeated post?
663 if (($repeat_of != "") || ($item["verb"] == ACTIVITY_SHARE)) {
664 $link_data = self::processRepeatedItem($xpath, $entry, $item, $importer);
665 if (!empty($link_data['add_body'])) {
666 $add_body .= $link_data['add_body'];
670 $item["body"] .= $add_body;
672 // Only add additional data when there is no picture in the post
673 if (!strstr($item["body"], '[/img]')) {
674 $item["body"] = add_page_info_to_body($item["body"]);
677 // Mastodon Content Warning
678 if (($item["verb"] == ACTIVITY_POST) && $xpath->evaluate('boolean(atom:summary)', $entry)) {
679 $clear_text = $xpath->query('atom:summary/text()', $entry)->item(0)->nodeValue;
681 $item["body"] = html2bbcode($clear_text) . '[spoiler]' . $item["body"] . '[/spoiler]';
684 if (($self != '') && empty($item['protocol'])) {
685 self::fetchSelf($self, $item);
688 if (!empty($item["conversation-href"])) {
689 self::fetchConversation($item['conversation-href'], $item['conversation-uri']);
692 if (isset($item["parent-uri"]) && ($related != '')) {
693 if (!dba::exists('item', array('uid' => $importer["uid"], 'uri' => $item['parent-uri']))) {
694 self::fetchRelated($related, $item["parent-uri"], $importer);
696 logger('Reply with URI '.$item["uri"].' already existed for user '.$importer["uid"].'.', LOGGER_DEBUG);
699 $item["type"] = 'remote-comment';
700 $item["gravity"] = GRAVITY_COMMENT;
702 $item["parent-uri"] = $item["uri"];
705 if (($item['author-link'] != '') && !empty($item['protocol'])) {
706 $item = store_conversation($item);
709 self::$itemlist[] = $item;
713 * @brief Fetch the conversation for posts
715 * @param string $conversation The link to the conversation
716 * @param string $conversation_uri The conversation in "uri" format
719 private static function fetchConversation($conversation, $conversation_uri)
721 // Ensure that we only store a conversation once in a process
722 if (isset(self::$conv_list[$conversation])) {
726 self::$conv_list[$conversation] = true;
728 $conversation_data = z_fetch_url($conversation, false, $redirects, array('accept_content' => 'application/atom+xml, text/html'));
730 if (!$conversation_data['success']) {
736 if (stristr($conversation_data['header'], 'Content-Type: application/atom+xml')) {
737 $xml = $conversation_data['body'];
741 $doc = new DOMDocument();
742 if (!@$doc->loadHTML($conversation_data['body'])) {
745 $xpath = new DomXPath($doc);
747 $links = $xpath->query('//link');
749 foreach ($links as $link) {
750 $attribute = self::readAttributes($link);
751 if (($attribute['rel'] == 'alternate') && ($attribute['type'] == 'application/atom+xml')) {
752 $file = $attribute['href'];
756 $conversation_atom = z_fetch_url($attribute['href']);
758 if ($conversation_atom['success']) {
759 $xml = $conversation_atom['body'];
769 self::storeConversation($xml, $conversation, $conversation_uri);
773 * @brief Store a feed in several conversation entries
775 * @param string $xml The feed
776 * @param string $conversation conversation
777 * @param string $conversation_uri conversation uri
780 private static function storeConversation($xml, $conversation = '', $conversation_uri = '')
782 $doc = new DOMDocument();
783 @$doc->loadXML($xml);
785 $xpath = new DomXPath($doc);
786 $xpath->registerNamespace('atom', NAMESPACE_ATOM1);
787 $xpath->registerNamespace('thr', NAMESPACE_THREAD);
788 $xpath->registerNamespace('ostatus', NAMESPACE_OSTATUS);
790 $entries = $xpath->query('/atom:feed/atom:entry');
792 // Now store the entries
793 foreach ($entries as $entry) {
794 $doc2 = new DOMDocument();
795 $doc2->preserveWhiteSpace = false;
796 $doc2->formatOutput = true;
798 $conv_data = array();
800 $conv_data['protocol'] = PROTOCOL_SPLITTED_CONV;
801 $conv_data['network'] = NETWORK_OSTATUS;
802 $conv_data['uri'] = $xpath->query('atom:id/text()', $entry)->item(0)->nodeValue;
804 $inreplyto = $xpath->query('thr:in-reply-to', $entry);
805 if (is_object($inreplyto->item(0))) {
806 foreach ($inreplyto->item(0)->attributes as $attributes) {
807 if ($attributes->name == "ref") {
808 $conv_data['reply-to-uri'] = $attributes->textContent;
813 $conv = $xpath->query('ostatus:conversation/text()', $entry)->item(0)->nodeValue;
814 $conv_data['conversation-uri'] = $conv;
816 $conv = $xpath->query('ostatus:conversation', $entry);
817 if (is_object($conv->item(0))) {
818 foreach ($conv->item(0)->attributes as $attributes) {
819 if ($attributes->name == "ref") {
820 $conv_data['conversation-uri'] = $attributes->textContent;
822 if ($attributes->name == "href") {
823 $conv_data['conversation-href'] = $attributes->textContent;
828 if ($conversation != '') {
829 $conv_data['conversation-uri'] = $conversation;
832 if ($conversation_uri != '') {
833 $conv_data['conversation-uri'] = $conversation_uri;
836 $entry = $doc2->importNode($entry, true);
838 $doc2->appendChild($entry);
840 $conv_data['source'] = $doc2->saveXML();
842 $condition = array('item-uri' => $conv_data['uri'],'protocol' => PROTOCOL_OSTATUS_FEED);
843 if (dba::exists('conversation', $condition)) {
844 logger('Delete deprecated entry for URI '.$conv_data['uri'], LOGGER_DEBUG);
845 dba::delete('conversation', array('item-uri' => $conv_data['uri']));
848 logger('Store conversation data for uri '.$conv_data['uri'], LOGGER_DEBUG);
849 store_conversation($conv_data);
854 * @brief Fetch the own post so that it can be stored later
856 * We want to store the original data for later processing.
857 * This function is meant for cases where we process a feed with multiple entries.
858 * In that case we need to fetch the single posts here.
860 * @param string $self The link to the self item
861 * @param array $item The item array
864 private static function fetchSelf($self, &$item)
866 $condition = array('`item-uri` = ? AND `protocol` IN (?, ?)', $self, PROTOCOL_DFRN, PROTOCOL_OSTATUS_SALMON);
867 if (dba::exists('conversation', $condition)) {
868 logger('Conversation '.$item['uri'].' is already stored.', LOGGER_DEBUG);
872 $self_data = z_fetch_url($self);
874 if (!$self_data['success']) {
878 // We reformat the XML to make it better readable
879 $doc = new DOMDocument();
880 $doc->loadXML($self_data['body']);
881 $doc->preserveWhiteSpace = false;
882 $doc->formatOutput = true;
883 $xml = $doc->saveXML();
885 $item["protocol"] = PROTOCOL_OSTATUS_SALMON;
886 $item["source"] = $xml;
888 logger('Conversation '.$item['uri'].' is now fetched.', LOGGER_DEBUG);
892 * @brief Fetch related posts and processes them
894 * @param string $related The link to the related item
895 * @param string $related_uri The related item in "uri" format
896 * @param array $importer user record of the importing user
899 private static function fetchRelated($related, $related_uri, $importer)
901 $condition = array('`item-uri` = ? AND `protocol` IN (?, ?)', $related_uri, PROTOCOL_DFRN, PROTOCOL_OSTATUS_SALMON);
902 $conversation = dba::select('conversation', array('source', 'protocol'), $condition, array('limit' => 1));
903 if (DBM::is_result($conversation)) {
905 $xml = $conversation['source'];
906 if (self::process($xml, $importer, $contact, $hub, $stored, false)) {
907 logger('Got valid cached XML for URI '.$related_uri, LOGGER_DEBUG);
910 if ($conversation['protocol'] == PROTOCOL_OSTATUS_SALMON) {
911 logger('Delete invalid cached XML for URI '.$related_uri, LOGGER_DEBUG);
912 dba::delete('conversation', array('item-uri' => $related_uri));
917 $related_data = z_fetch_url($related, false, $redirects, array('accept_content' => 'application/atom+xml, text/html'));
919 if (!$related_data['success']) {
925 if (stristr($related_data['header'], 'Content-Type: application/atom+xml')) {
926 logger('Directly fetched XML for URI '.$related_uri, LOGGER_DEBUG);
927 $xml = $related_data['body'];
931 $doc = new DOMDocument();
932 if (!@$doc->loadHTML($related_data['body'])) {
935 $xpath = new DomXPath($doc);
939 $links = $xpath->query('//link');
941 foreach ($links as $link) {
942 $attribute = self::readAttributes($link);
943 if (($attribute['rel'] == 'alternate') && ($attribute['type'] == 'application/atom+xml')) {
944 $atom_file = $attribute['href'];
947 if ($atom_file != '') {
948 $related_atom = z_fetch_url($atom_file);
950 if ($related_atom['success']) {
951 logger('Fetched XML for URI '.$related_uri, LOGGER_DEBUG);
952 $xml = $related_atom['body'];
958 // Workaround for older GNU Social servers
959 if (($xml == '') && strstr($related, '/notice/')) {
960 $related_atom = z_fetch_url(str_replace('/notice/', '/api/statuses/show/', $related).'.atom');
962 if ($related_atom['success']) {
963 logger('GNU Social workaround to fetch XML for URI '.$related_uri, LOGGER_DEBUG);
964 $xml = $related_atom['body'];
968 // Even more worse workaround for GNU Social ;-)
970 $related_guess = OStatus::convertHref($related_uri);
971 $related_atom = z_fetch_url(str_replace('/notice/', '/api/statuses/show/', $related_guess).'.atom');
973 if ($related_atom['success']) {
974 logger('GNU Social workaround 2 to fetch XML for URI '.$related_uri, LOGGER_DEBUG);
975 $xml = $related_atom['body'];
979 // Finally we take the data that we fetched from "ostatus:conversation"
981 $condition = array('item-uri' => $related_uri, 'protocol' => PROTOCOL_SPLITTED_CONV);
982 $conversation = dba::select('conversation', array('source'), $condition, array('limit' => 1));
983 if (DBM::is_result($conversation)) {
985 logger('Got cached XML from conversation for URI '.$related_uri, LOGGER_DEBUG);
986 $xml = $conversation['source'];
991 self::process($xml, $importer, $contact, $hub, $stored, false);
993 logger("XML couldn't be fetched for URI: ".$related_uri." - href: ".$related, LOGGER_DEBUG);
999 * @brief Processes the XML for a repeated post
1001 * @param object $xpath The xpath object
1002 * @param object $entry The xml entry that is processed
1003 * @param array $item The item array
1004 * @param array $importer user record of the importing user
1006 * @return array with data from links
1008 private static function processRepeatedItem($xpath, $entry, &$item, $importer)
1010 $activityobjects = $xpath->query('activity:object', $entry)->item(0);
1012 if (!is_object($activityobjects)) {
1016 $link_data = array();
1018 $orig_uri = $xpath->query('atom:id/text()', $activityobjects)->item(0)->nodeValue;
1020 $links = $xpath->query("atom:link", $activityobjects);
1022 $link_data = self::processLinks($links, $item);
1025 $orig_body = $xpath->query('atom:content/text()', $activityobjects)->item(0)->nodeValue;
1026 $orig_created = $xpath->query('atom:published/text()', $activityobjects)->item(0)->nodeValue;
1027 $orig_edited = $xpath->query('atom:updated/text()', $activityobjects)->item(0)->nodeValue;
1029 $orig_contact = $contact;
1030 $orig_author = self::fetchAuthor($xpath, $activityobjects, $importer, $orig_contact, false);
1032 $item["author-name"] = $orig_author["author-name"];
1033 $item["author-link"] = $orig_author["author-link"];
1034 $item["author-avatar"] = $orig_author["author-avatar"];
1036 $item["body"] = html2bbcode($orig_body);
1037 $item["created"] = $orig_created;
1038 $item["edited"] = $orig_edited;
1040 $item["uri"] = $orig_uri;
1042 $item["verb"] = $xpath->query('activity:verb/text()', $activityobjects)->item(0)->nodeValue;
1044 $item["object-type"] = $xpath->query('activity:object-type/text()', $activityobjects)->item(0)->nodeValue;
1046 $inreplyto = $xpath->query('thr:in-reply-to', $activityobjects);
1047 if (is_object($inreplyto->item(0))) {
1048 foreach ($inreplyto->item(0)->attributes as $attributes) {
1049 if ($attributes->name == "ref") {
1050 $item["parent-uri"] = $attributes->textContent;
1059 * @brief Processes links in the XML
1061 * @param object $links The xml data that contain links
1062 * @param array $item The item array
1064 * @return array with data from the links
1066 private static function processLinks($links, &$item)
1068 $link_data = array('add_body' => '', 'self' => '');
1070 foreach ($links as $link) {
1071 $attribute = self::readAttributes($link);
1073 if (($attribute['rel'] != "") && ($attribute['href'] != "")) {
1074 switch ($attribute['rel']) {
1076 $item["plink"] = $attribute['href'];
1077 if (($item["object-type"] == ACTIVITY_OBJ_QUESTION)
1078 || ($item["object-type"] == ACTIVITY_OBJ_EVENT)
1080 $item["body"] .= add_page_info($attribute['href']);
1083 case "ostatus:conversation":
1084 $link_data['conversation'] = $attribute['href'];
1085 $item['conversation-href'] = $link_data['conversation'];
1086 if (!isset($item['conversation-uri'])) {
1087 $item['conversation-uri'] = $item['conversation-href'];
1091 $filetype = strtolower(substr($attribute['type'], 0, strpos($attribute['type'], '/')));
1092 if ($filetype == 'image') {
1093 $link_data['add_body'] .= "\n[img]".$attribute['href'].'[/img]';
1095 if (strlen($item["attach"])) {
1096 $item["attach"] .= ',';
1098 if (!isset($attribute['length'])) {
1099 $attribute['length'] = "0";
1101 $item["attach"] .= '[attach]href="'.$attribute['href'].'" length="'.$attribute['length'].'" type="'.$attribute['type'].'" title="'.$attribute['title'].'"[/attach]';
1105 if ($item["object-type"] != ACTIVITY_OBJ_BOOKMARK) {
1106 if (!isset($item["parent-uri"])) {
1107 $item["parent-uri"] = $attribute['href'];
1109 $link_data['related'] = $attribute['href'];
1111 $item["body"] .= add_page_info($attribute['href']);
1115 if ($item["plink"] == '') {
1116 $item["plink"] = $attribute['href'];
1118 $link_data['self'] = $attribute['href'];
1127 * @brief Create an url out of an uri
1129 * @param string $href URI in the format "parameter1:parameter1:..."
1131 * @return string URL in the format http(s)://....
1133 public static function convertHref($href)
1135 $elements = explode(":", $href);
1137 if ((count($elements) <= 2) || ($elements[0] != "tag")) {
1141 $server = explode(",", $elements[1]);
1142 $conversation = explode("=", $elements[2]);
1144 if ((count($elements) == 4) && ($elements[2] == "post")) {
1145 return "http://".$server[0]."/notice/".$elements[3];
1148 if ((count($conversation) != 2) || ($conversation[1] =="")) {
1151 if ($elements[3] == "objectType=thread") {
1152 return "http://".$server[0]."/conversation/".$conversation[1];
1154 return "http://".$server[0]."/notice/".$conversation[1];
1160 * @brief Checks if the current post is a reshare
1162 * @param array $item The item array of thw post
1164 * @return string The guid if the post is a reshare
1166 private static function getResharedGuid($item)
1168 $body = trim($item["body"]);
1170 // Skip if it isn't a pure repeated messages
1171 // Does it start with a share?
1172 if (strpos($body, "[share") > 0) {
1176 // Does it end with a share?
1177 if (strlen($body) > (strrpos($body, "[/share]") + 8)) {
1181 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "$1", $body);
1182 // Skip if there is no shared message in there
1183 if ($body == $attributes) {
1188 preg_match("/guid='(.*?)'/ism", $attributes, $matches);
1189 if ($matches[1] != "") {
1190 $guid = $matches[1];
1193 preg_match('/guid="(.*?)"/ism', $attributes, $matches);
1194 if ($matches[1] != "") {
1195 $guid = $matches[1];
1202 * @brief Cleans the body of a post if it contains picture links
1204 * @param string $body The body
1206 * @return string The cleaned body
1208 private static function formatPicturePost($body)
1210 $siteinfo = get_attached_data($body);
1212 if (($siteinfo["type"] == "photo")) {
1213 if (isset($siteinfo["preview"])) {
1214 $preview = $siteinfo["preview"];
1216 $preview = $siteinfo["image"];
1219 // Is it a remote picture? Then make a smaller preview here
1220 $preview = proxy_url($preview, false, PROXY_SIZE_SMALL);
1222 // Is it a local picture? Then make it smaller here
1223 $preview = str_replace(array("-0.jpg", "-0.png"), array("-2.jpg", "-2.png"), $preview);
1224 $preview = str_replace(array("-1.jpg", "-1.png"), array("-2.jpg", "-2.png"), $preview);
1226 if (isset($siteinfo["url"])) {
1227 $url = $siteinfo["url"];
1229 $url = $siteinfo["image"];
1232 $body = trim($siteinfo["text"])." [url]".$url."[/url]\n[img]".$preview."[/img]";
1239 * @brief Adds the header elements to the XML document
1241 * @param object $doc XML document
1242 * @param array $owner Contact data of the poster
1244 * @return object header root element
1246 private static function addHeader($doc, $owner)
1250 $root = $doc->createElementNS(NAMESPACE_ATOM1, 'feed');
1251 $doc->appendChild($root);
1253 $root->setAttribute("xmlns:thr", NAMESPACE_THREAD);
1254 $root->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
1255 $root->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
1256 $root->setAttribute("xmlns:media", NAMESPACE_MEDIA);
1257 $root->setAttribute("xmlns:poco", NAMESPACE_POCO);
1258 $root->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
1259 $root->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
1260 $root->setAttribute("xmlns:mastodon", NAMESPACE_MASTODON);
1262 $attributes = array("uri" => "https://friendi.ca", "version" => FRIENDICA_VERSION."-".DB_UPDATE_VERSION);
1263 XML::addElement($doc, $root, "generator", FRIENDICA_PLATFORM, $attributes);
1264 XML::addElement($doc, $root, "id", System::baseUrl()."/profile/".$owner["nick"]);
1265 XML::addElement($doc, $root, "title", sprintf("%s timeline", $owner["name"]));
1266 XML::addElement($doc, $root, "subtitle", sprintf("Updates from %s on %s", $owner["name"], $a->config["sitename"]));
1267 XML::addElement($doc, $root, "logo", $owner["photo"]);
1268 XML::addElement($doc, $root, "updated", datetime_convert("UTC", "UTC", "now", ATOM_TIME));
1270 $author = self::addAuthor($doc, $owner);
1271 $root->appendChild($author);
1273 $attributes = array("href" => $owner["url"], "rel" => "alternate", "type" => "text/html");
1274 XML::addElement($doc, $root, "link", "", $attributes);
1276 /// @TODO We have to find out what this is
1277 /// $attributes = array("href" => System::baseUrl()."/sup",
1278 /// "rel" => "http://api.friendfeed.com/2008/03#sup",
1279 /// "type" => "application/json");
1280 /// XML::addElement($doc, $root, "link", "", $attributes);
1282 self::hublinks($doc, $root, $owner["nick"]);
1284 $attributes = array("href" => System::baseUrl()."/salmon/".$owner["nick"], "rel" => "salmon");
1285 XML::addElement($doc, $root, "link", "", $attributes);
1287 $attributes = array("href" => System::baseUrl()."/salmon/".$owner["nick"], "rel" => "http://salmon-protocol.org/ns/salmon-replies");
1288 XML::addElement($doc, $root, "link", "", $attributes);
1290 $attributes = array("href" => System::baseUrl()."/salmon/".$owner["nick"], "rel" => "http://salmon-protocol.org/ns/salmon-mention");
1291 XML::addElement($doc, $root, "link", "", $attributes);
1293 $attributes = array("href" => System::baseUrl()."/api/statuses/user_timeline/".$owner["nick"].".atom",
1294 "rel" => "self", "type" => "application/atom+xml");
1295 XML::addElement($doc, $root, "link", "", $attributes);
1301 * @brief Add the link to the push hubs to the XML document
1303 * @param object $doc XML document
1304 * @param object $root XML root element where the hub links are added
1305 * @param object $nick nick
1308 public static function hublinks($doc, $root, $nick)
1310 $h = System::baseUrl() . '/pubsubhubbub/'.$nick;
1311 XML::addElement($doc, $root, "link", "", array("href" => $h, "rel" => "hub"));
1315 * @brief Adds attachement data to the XML document
1317 * @param object $doc XML document
1318 * @param object $root XML root element where the hub links are added
1319 * @param array $item Data of the item that is to be posted
1322 private static function getAttachment($doc, $root, $item)
1325 $siteinfo = get_attached_data($item["body"]);
1327 switch ($siteinfo["type"]) {
1329 $imgdata = get_photo_info($siteinfo["image"]);
1330 $attributes = array("rel" => "enclosure",
1331 "href" => $siteinfo["image"],
1332 "type" => $imgdata["mime"],
1333 "length" => intval($imgdata["size"]));
1334 XML::addElement($doc, $root, "link", "", $attributes);
1337 $attributes = array("rel" => "enclosure",
1338 "href" => $siteinfo["url"],
1339 "type" => "text/html; charset=UTF-8",
1341 "title" => $siteinfo["title"]);
1342 XML::addElement($doc, $root, "link", "", $attributes);
1348 if (!Config::get('system', 'ostatus_not_attach_preview') && ($siteinfo["type"] != "photo") && isset($siteinfo["image"])) {
1349 $imgdata = get_photo_info($siteinfo["image"]);
1350 $attributes = array("rel" => "enclosure",
1351 "href" => $siteinfo["image"],
1352 "type" => $imgdata["mime"],
1353 "length" => intval($imgdata["size"]));
1355 XML::addElement($doc, $root, "link", "", $attributes);
1358 $arr = explode('[/attach],', $item['attach']);
1360 foreach ($arr as $r) {
1362 $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"|', $r, $matches);
1364 $attributes = array("rel" => "enclosure",
1365 "href" => $matches[1],
1366 "type" => $matches[3]);
1368 if (intval($matches[2])) {
1369 $attributes["length"] = intval($matches[2]);
1371 if (trim($matches[4]) != "") {
1372 $attributes["title"] = trim($matches[4]);
1374 XML::addElement($doc, $root, "link", "", $attributes);
1381 * @brief Adds the author element to the XML document
1383 * @param object $doc XML document
1384 * @param array $owner Contact data of the poster
1386 * @return object author element
1388 private static function addAuthor($doc, $owner)
1390 $r = q("SELECT `homepage`, `publish` FROM `profile` WHERE `uid` = %d AND `is-default` LIMIT 1", intval($owner["uid"]));
1391 if (DBM::is_result($r)) {
1394 $author = $doc->createElement("author");
1395 XML::addElement($doc, $author, "id", $owner["url"]);
1396 XML::addElement($doc, $author, "activity:object-type", ACTIVITY_OBJ_PERSON);
1397 XML::addElement($doc, $author, "uri", $owner["url"]);
1398 XML::addElement($doc, $author, "name", $owner["nick"]);
1399 XML::addElement($doc, $author, "email", $owner["addr"]);
1400 XML::addElement($doc, $author, "summary", bbcode($owner["about"], false, false, 7));
1402 $attributes = array("rel" => "alternate", "type" => "text/html", "href" => $owner["url"]);
1403 XML::addElement($doc, $author, "link", "", $attributes);
1405 $attributes = array(
1407 "type" => "image/jpeg", // To-Do?
1408 "media:width" => 175,
1409 "media:height" => 175,
1410 "href" => $owner["photo"]);
1411 XML::addElement($doc, $author, "link", "", $attributes);
1413 if (isset($owner["thumb"])) {
1414 $attributes = array(
1416 "type" => "image/jpeg", // To-Do?
1417 "media:width" => 80,
1418 "media:height" => 80,
1419 "href" => $owner["thumb"]);
1420 XML::addElement($doc, $author, "link", "", $attributes);
1423 XML::addElement($doc, $author, "poco:preferredUsername", $owner["nick"]);
1424 XML::addElement($doc, $author, "poco:displayName", $owner["name"]);
1425 XML::addElement($doc, $author, "poco:note", bbcode($owner["about"], false, false, 7));
1427 if (trim($owner["location"]) != "") {
1428 $element = $doc->createElement("poco:address");
1429 XML::addElement($doc, $element, "poco:formatted", $owner["location"]);
1430 $author->appendChild($element);
1433 if (trim($profile["homepage"]) != "") {
1434 $urls = $doc->createElement("poco:urls");
1435 XML::addElement($doc, $urls, "poco:type", "homepage");
1436 XML::addElement($doc, $urls, "poco:value", $profile["homepage"]);
1437 XML::addElement($doc, $urls, "poco:primary", "true");
1438 $author->appendChild($urls);
1441 if (count($profile)) {
1442 XML::addElement($doc, $author, "followers", "", array("url" => System::baseUrl()."/viewcontacts/".$owner["nick"]));
1443 XML::addElement($doc, $author, "statusnet:profile_info", "", array("local_id" => $owner["uid"]));
1446 if ($profile["publish"]) {
1447 XML::addElement($doc, $author, "mastodon:scope", "public");
1453 * @TODO Picture attachments should look like this:
1454 * <a href="https://status.pirati.ca/attachment/572819" title="https://status.pirati.ca/file/heluecht-20151202T222602-rd3u49p.gif"
1455 * class="attachment thumbnail" id="attachment-572819" rel="nofollow external">https://status.pirati.ca/attachment/572819</a>
1459 * @brief Returns the given activity if present - otherwise returns the "post" activity
1461 * @param array $item Data of the item that is to be posted
1463 * @return string activity
1465 private static function constructVerb($item)
1467 if ($item['verb']) {
1468 return $item['verb'];
1471 return ACTIVITY_POST;
1475 * @brief Returns the given object type if present - otherwise returns the "note" object type
1477 * @param array $item Data of the item that is to be posted
1479 * @return string Object type
1481 private static function constructObjecttype($item)
1483 if (in_array($item['object-type'], array(ACTIVITY_OBJ_NOTE, ACTIVITY_OBJ_COMMENT)))
1484 return $item['object-type'];
1485 return ACTIVITY_OBJ_NOTE;
1489 * @brief Adds an entry element to the XML document
1491 * @param object $doc XML document
1492 * @param array $item Data of the item that is to be posted
1493 * @param array $owner Contact data of the poster
1494 * @param bool $toplevel optional default false
1496 * @return object Entry element
1498 private static function entry($doc, $item, $owner, $toplevel = false)
1500 $repeated_guid = self::getResharedGuid($item);
1501 if ($repeated_guid != "") {
1502 $xml = self::reshareEntry($doc, $item, $owner, $repeated_guid, $toplevel);
1509 if ($item["verb"] == ACTIVITY_LIKE) {
1510 return self::likeEntry($doc, $item, $owner, $toplevel);
1511 } elseif (in_array($item["verb"], array(ACTIVITY_FOLLOW, NAMESPACE_OSTATUS."/unfollow"))) {
1512 return self::followEntry($doc, $item, $owner, $toplevel);
1514 return self::noteEntry($doc, $item, $owner, $toplevel);
1519 * @brief Adds a source entry to the XML document
1521 * @param object $doc XML document
1522 * @param array $contact Array of the contact that is added
1524 * @return object Source element
1526 private static function sourceEntry($doc, $contact)
1528 $source = $doc->createElement("source");
1529 XML::addElement($doc, $source, "id", $contact["poll"]);
1530 XML::addElement($doc, $source, "title", $contact["name"]);
1531 XML::addElement($doc, $source, "link", "", array("rel" => "alternate", "type" => "text/html", "href" => $contact["alias"]));
1532 XML::addElement($doc, $source, "link", "", array("rel" => "self", "type" => "application/atom+xml", "href" => $contact["poll"]));
1533 XML::addElement($doc, $source, "icon", $contact["photo"]);
1534 XML::addElement($doc, $source, "updated", datetime_convert("UTC", "UTC", $contact["success_update"]."+00:00", ATOM_TIME));
1540 * @brief Fetches contact data from the contact or the gcontact table
1542 * @param string $url URL of the contact
1543 * @param array $owner Contact data of the poster
1545 * @return array Contact array
1547 private static function contactEntry($url, $owner)
1550 "SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` IN (0, %d) ORDER BY `uid` DESC LIMIT 1",
1551 dbesc(normalise_link($url)),
1552 intval($owner["uid"])
1554 if (DBM::is_result($r)) {
1556 $contact["uid"] = -1;
1559 if (!DBM::is_result($r)) {
1561 "SELECT * FROM `gcontact` WHERE `nurl` = '%s' LIMIT 1",
1562 dbesc(normalise_link($url))
1564 if (DBM::is_result($r)) {
1566 $contact["uid"] = -1;
1567 $contact["success_update"] = $contact["updated"];
1571 if (!DBM::is_result($r)) {
1575 if (!isset($contact["poll"])) {
1576 $data = Probe::uri($url);
1577 $contact["poll"] = $data["poll"];
1579 if (!$contact["alias"]) {
1580 $contact["alias"] = $data["alias"];
1584 if (!isset($contact["alias"])) {
1585 $contact["alias"] = $contact["url"];
1592 * @brief Adds an entry element with reshared content
1594 * @param object $doc XML document
1595 * @param array $item Data of the item that is to be posted
1596 * @param array $owner Contact data of the poster
1597 * @param string $repeated_guid guid
1598 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1600 * @return object Entry element
1602 private static function reshareEntry($doc, $item, $owner, $repeated_guid, $toplevel)
1604 if (($item["id"] != $item["parent"]) && (normalise_link($item["author-link"]) != normalise_link($owner["url"]))) {
1605 logger("OStatus entry is from author ".$owner["url"]." - not from ".$item["author-link"].". Quitting.", LOGGER_DEBUG);
1608 $title = self::entryHeader($doc, $entry, $owner, $toplevel);
1611 "SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' AND NOT `private` AND `network` IN ('%s', '%s', '%s') LIMIT 1",
1612 intval($owner["uid"]),
1613 dbesc($repeated_guid),
1614 dbesc(NETWORK_DFRN),
1615 dbesc(NETWORK_DIASPORA),
1616 dbesc(NETWORK_OSTATUS)
1618 if (DBM::is_result($r)) {
1619 $repeated_item = $r[0];
1623 $contact = self::contactEntry($repeated_item['author-link'], $owner);
1625 $parent_item = (($item['thr-parent']) ? $item['thr-parent'] : $item['parent-uri']);
1627 $title = $owner["nick"]." repeated a notice by ".$contact["nick"];
1629 self::entryContent($doc, $entry, $item, $owner, $title, ACTIVITY_SHARE, false);
1631 $as_object = $doc->createElement("activity:object");
1633 XML::addElement($doc, $as_object, "activity:object-type", NAMESPACE_ACTIVITY_SCHEMA."activity");
1635 self::entryContent($doc, $as_object, $repeated_item, $owner, "", "", false);
1637 $author = self::addAuthor($doc, $contact);
1638 $as_object->appendChild($author);
1640 $as_object2 = $doc->createElement("activity:object");
1642 XML::addElement($doc, $as_object2, "activity:object-type", self::constructObjecttype($repeated_item));
1644 $title = sprintf("New comment by %s", $contact["nick"]);
1646 self::entryContent($doc, $as_object2, $repeated_item, $owner, $title);
1648 $as_object->appendChild($as_object2);
1650 self::entryFooter($doc, $as_object, $item, $owner, false);
1652 $source = self::sourceEntry($doc, $contact);
1654 $as_object->appendChild($source);
1656 $entry->appendChild($as_object);
1658 self::entryFooter($doc, $entry, $item, $owner);
1664 * @brief Adds an entry element with a "like"
1666 * @param object $doc XML document
1667 * @param array $item Data of the item that is to be posted
1668 * @param array $owner Contact data of the poster
1669 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1671 * @return object Entry element with "like"
1673 private static function likeEntry($doc, $item, $owner, $toplevel)
1675 if (($item["id"] != $item["parent"]) && (normalise_link($item["author-link"]) != normalise_link($owner["url"]))) {
1676 logger("OStatus entry is from author ".$owner["url"]." - not from ".$item["author-link"].". Quitting.", LOGGER_DEBUG);
1679 $title = self::entryHeader($doc, $entry, $owner, $toplevel);
1681 $verb = NAMESPACE_ACTIVITY_SCHEMA."favorite";
1682 self::entryContent($doc, $entry, $item, $owner, "Favorite", $verb, false);
1684 $as_object = $doc->createElement("activity:object");
1687 "SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d",
1688 dbesc($item["thr-parent"]),
1689 intval($item["uid"])
1691 $parent_item = (($item['thr-parent']) ? $item['thr-parent'] : $item['parent-uri']);
1693 XML::addElement($doc, $as_object, "activity:object-type", self::constructObjecttype($parent[0]));
1695 self::entryContent($doc, $as_object, $parent[0], $owner, "New entry");
1697 $entry->appendChild($as_object);
1699 self::entryFooter($doc, $entry, $item, $owner);
1705 * @brief Adds the person object element to the XML document
1707 * @param object $doc XML document
1708 * @param array $owner Contact data of the poster
1709 * @param array $contact Contact data of the target
1711 * @return object author element
1713 private static function addPersonObject($doc, $owner, $contact)
1715 $object = $doc->createElement("activity:object");
1716 XML::addElement($doc, $object, "activity:object-type", ACTIVITY_OBJ_PERSON);
1718 if ($contact['network'] == NETWORK_PHANTOM) {
1719 XML::addElement($doc, $object, "id", $contact['url']);
1723 XML::addElement($doc, $object, "id", $contact["alias"]);
1724 XML::addElement($doc, $object, "title", $contact["nick"]);
1726 $attributes = array("rel" => "alternate", "type" => "text/html", "href" => $contact["url"]);
1727 XML::addElement($doc, $object, "link", "", $attributes);
1729 $attributes = array(
1731 "type" => "image/jpeg", // To-Do?
1732 "media:width" => 175,
1733 "media:height" => 175,
1734 "href" => $contact["photo"]);
1735 XML::addElement($doc, $object, "link", "", $attributes);
1737 XML::addElement($doc, $object, "poco:preferredUsername", $contact["nick"]);
1738 XML::addElement($doc, $object, "poco:displayName", $contact["name"]);
1740 if (trim($contact["location"]) != "") {
1741 $element = $doc->createElement("poco:address");
1742 XML::addElement($doc, $element, "poco:formatted", $contact["location"]);
1743 $object->appendChild($element);
1750 * @brief Adds a follow/unfollow entry element
1752 * @param object $doc XML document
1753 * @param array $item Data of the follow/unfollow message
1754 * @param array $owner Contact data of the poster
1755 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1757 * @return object Entry element
1759 private static function followEntry($doc, $item, $owner, $toplevel)
1761 $item["id"] = $item["parent"] = 0;
1762 $item["created"] = $item["edited"] = date("c");
1763 $item["private"] = true;
1765 $contact = Probe::uri($item['follow']);
1767 if ($contact['alias'] == '') {
1768 $contact['alias'] = $contact["url"];
1770 $item['follow'] = $contact['alias'];
1774 "SELECT `id` FROM `contact` WHERE `uid` = %d AND `nurl` = '%s'",
1775 intval($owner['uid']),
1776 dbesc(normalise_link($contact["url"]))
1779 if (DBM::is_result($r)) {
1780 $connect_id = $r[0]['id'];
1785 if ($item['verb'] == ACTIVITY_FOLLOW) {
1786 $message = t('%s is now following %s.');
1787 $title = t('following');
1788 $action = "subscription";
1790 $message = t('%s stopped following %s.');
1791 $title = t('stopped following');
1792 $action = "unfollow";
1795 $item["uri"] = $item['parent-uri'] = $item['thr-parent']
1796 = 'tag:'.get_app()->get_hostname().
1797 ','.date('Y-m-d').':'.$action.':'.$owner['uid'].
1798 ':person:'.$connect_id.':'.$item['created'];
1800 $item["body"] = sprintf($message, $owner["nick"], $contact["nick"]);
1802 self::entryHeader($doc, $entry, $owner, $toplevel);
1804 self::entryContent($doc, $entry, $item, $owner, $title);
1806 $object = self::addPersonObject($doc, $owner, $contact);
1807 $entry->appendChild($object);
1809 self::entryFooter($doc, $entry, $item, $owner);
1815 * @brief Adds a regular entry element
1817 * @param object $doc XML document
1818 * @param array $item Data of the item that is to be posted
1819 * @param array $owner Contact data of the poster
1820 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1822 * @return object Entry element
1824 private static function noteEntry($doc, $item, $owner, $toplevel)
1826 if (($item["id"] != $item["parent"]) && (normalise_link($item["author-link"]) != normalise_link($owner["url"]))) {
1827 logger("OStatus entry is from author ".$owner["url"]." - not from ".$item["author-link"].". Quitting.", LOGGER_DEBUG);
1830 $title = self::entryHeader($doc, $entry, $owner, $toplevel);
1832 XML::addElement($doc, $entry, "activity:object-type", ACTIVITY_OBJ_NOTE);
1834 self::entryContent($doc, $entry, $item, $owner, $title);
1836 self::entryFooter($doc, $entry, $item, $owner);
1842 * @brief Adds a header element to the XML document
1844 * @param object $doc XML document
1845 * @param object $entry The entry element where the elements are added
1846 * @param array $owner Contact data of the poster
1847 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1849 * @return string The title for the element
1851 private static function entryHeader($doc, &$entry, $owner, $toplevel)
1853 /// @todo Check if this title stuff is really needed (I guess not)
1855 $entry = $doc->createElement("entry");
1856 $title = sprintf("New note by %s", $owner["nick"]);
1858 $entry = $doc->createElementNS(NAMESPACE_ATOM1, "entry");
1860 $entry->setAttribute("xmlns:thr", NAMESPACE_THREAD);
1861 $entry->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
1862 $entry->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
1863 $entry->setAttribute("xmlns:media", NAMESPACE_MEDIA);
1864 $entry->setAttribute("xmlns:poco", NAMESPACE_POCO);
1865 $entry->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
1866 $entry->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
1867 $entry->setAttribute("xmlns:mastodon", NAMESPACE_MASTODON);
1869 $author = self::addAuthor($doc, $owner);
1870 $entry->appendChild($author);
1872 $title = sprintf("New comment by %s", $owner["nick"]);
1878 * @brief Adds elements to the XML document
1880 * @param object $doc XML document
1881 * @param object $entry Entry element where the content is added
1882 * @param array $item Data of the item that is to be posted
1883 * @param array $owner Contact data of the poster
1884 * @param string $title Title for the post
1885 * @param string $verb The activity verb
1886 * @param bool $complete Add the "status_net" element?
1889 private static function entryContent($doc, $entry, $item, $owner, $title, $verb = "", $complete = true)
1892 $verb = self::constructVerb($item);
1895 XML::addElement($doc, $entry, "id", $item["uri"]);
1896 XML::addElement($doc, $entry, "title", $title);
1898 $body = self::formatPicturePost($item['body']);
1900 if ($item['title'] != "") {
1901 $body = "[b]".$item['title']."[/b]\n\n".$body;
1904 $body = bbcode($body, false, false, 7);
1906 XML::addElement($doc, $entry, "content", $body, array("type" => "html"));
1908 XML::addElement($doc, $entry, "link", "", array("rel" => "alternate", "type" => "text/html",
1909 "href" => System::baseUrl()."/display/".$item["guid"])
1912 if ($complete && ($item["id"] > 0)) {
1913 XML::addElement($doc, $entry, "status_net", "", array("notice_id" => $item["id"]));
1916 XML::addElement($doc, $entry, "activity:verb", $verb);
1918 XML::addElement($doc, $entry, "published", datetime_convert("UTC", "UTC", $item["created"]."+00:00", ATOM_TIME));
1919 XML::addElement($doc, $entry, "updated", datetime_convert("UTC", "UTC", $item["edited"]."+00:00", ATOM_TIME));
1923 * @brief Adds the elements at the foot of an entry to the XML document
1925 * @param object $doc XML document
1926 * @param object $entry The entry element where the elements are added
1927 * @param array $item Data of the item that is to be posted
1928 * @param array $owner Contact data of the poster
1929 * @param bool $complete default true
1932 private static function entryFooter($doc, $entry, $item, $owner, $complete = true)
1934 $mentioned = array();
1936 if (($item['parent'] != $item['id']) || ($item['parent-uri'] !== $item['uri']) || (($item['thr-parent'] !== '') && ($item['thr-parent'] !== $item['uri']))) {
1937 $parent = q("SELECT `guid`, `author-link`, `owner-link` FROM `item` WHERE `id` = %d", intval($item["parent"]));
1938 $parent_item = (($item['thr-parent']) ? $item['thr-parent'] : $item['parent-uri']);
1941 "SELECT `guid`, `author-link`, `owner-link`, `plink` FROM `item` WHERE `uid` = %d AND `uri` = '%s'",
1942 intval($owner["uid"]),
1946 $mentioned[$thrparent[0]["author-link"]] = $thrparent[0]["author-link"];
1947 $mentioned[$thrparent[0]["owner-link"]] = $thrparent[0]["owner-link"];
1948 $parent_plink = $thrparent[0]["plink"];
1950 $mentioned[$parent[0]["author-link"]] = $parent[0]["author-link"];
1951 $mentioned[$parent[0]["owner-link"]] = $parent[0]["owner-link"];
1952 $parent_plink = System::baseUrl()."/display/".$parent[0]["guid"];
1955 $attributes = array(
1956 "ref" => $parent_item,
1957 "href" => $parent_plink);
1958 XML::addElement($doc, $entry, "thr:in-reply-to", "", $attributes);
1960 $attributes = array(
1962 "href" => $parent_plink);
1963 XML::addElement($doc, $entry, "link", "", $attributes);
1966 if (intval($item["parent"]) > 0) {
1967 $conversation_href = System::baseUrl()."/display/".$owner["nick"]."/".$item["parent"];
1968 $conversation_uri = $conversation_href;
1970 if (isset($parent_item)) {
1971 $r = dba::fetch_first("SELECT `conversation-uri`, `conversation-href` FROM `conversation` WHERE `item-uri` = ?", $parent_item);
1972 if (DBM::is_result($r)) {
1973 if ($r['conversation-uri'] != '') {
1974 $conversation_uri = $r['conversation-uri'];
1976 if ($r['conversation-href'] != '') {
1977 $conversation_href = $r['conversation-href'];
1982 XML::addElement($doc, $entry, "link", "", array("rel" => "ostatus:conversation", "href" => $conversation_href));
1984 $attributes = array(
1985 "href" => $conversation_href,
1986 "local_id" => $item["parent"],
1987 "ref" => $conversation_uri);
1989 XML::addElement($doc, $entry, "ostatus:conversation", $conversation_uri, $attributes);
1992 $tags = item_getfeedtags($item);
1995 foreach ($tags as $t) {
1997 $mentioned[$t[1]] = $t[1];
2002 // Make sure that mentions are accepted (GNU Social has problems with mixing HTTP and HTTPS)
2003 $newmentions = array();
2004 foreach ($mentioned as $mention) {
2005 $newmentions[str_replace("http://", "https://", $mention)] = str_replace("http://", "https://", $mention);
2006 $newmentions[str_replace("https://", "http://", $mention)] = str_replace("https://", "http://", $mention);
2008 $mentioned = $newmentions;
2010 foreach ($mentioned as $mention) {
2012 "SELECT `forum`, `prv` FROM `contact` WHERE `uid` = %d AND `nurl` = '%s'",
2013 intval($owner["uid"]),
2014 dbesc(normalise_link($mention))
2016 if ($r[0]["forum"] || $r[0]["prv"]) {
2017 XML::addElement($doc, $entry, "link", "",
2019 "rel" => "mentioned",
2020 "ostatus:object-type" => ACTIVITY_OBJ_GROUP,
2024 XML::addElement($doc, $entry, "link", "",
2026 "rel" => "mentioned",
2027 "ostatus:object-type" => ACTIVITY_OBJ_PERSON,
2033 if (!$item["private"]) {
2034 XML::addElement($doc, $entry, "link", "", array("rel" => "ostatus:attention",
2035 "href" => "http://activityschema.org/collection/public"));
2036 XML::addElement($doc, $entry, "link", "", array("rel" => "mentioned",
2037 "ostatus:object-type" => "http://activitystrea.ms/schema/1.0/collection",
2038 "href" => "http://activityschema.org/collection/public"));
2039 XML::addElement($doc, $entry, "mastodon:scope", "public");
2043 foreach ($tags as $t) {
2045 XML::addElement($doc, $entry, "category", "", array("term" => $t[2]));
2050 self::getAttachment($doc, $entry, $item);
2052 if ($complete && ($item["id"] > 0)) {
2053 $app = $item["app"];
2058 $attributes = array("local_id" => $item["id"], "source" => $app);
2060 if (isset($parent["id"])) {
2061 $attributes["repeat_of"] = $parent["id"];
2064 if ($item["coord"] != "") {
2065 XML::addElement($doc, $entry, "georss:point", $item["coord"]);
2068 XML::addElement($doc, $entry, "statusnet:notice_info", "", $attributes);
2073 * @brief Creates the XML feed for a given nickname
2075 * @param object $a The application class
2076 * @param string $owner_nick Nickname of the feed owner
2077 * @param string $last_update Date of the last update
2078 * @param integer $max_items Number of maximum items to fetch
2080 * @return string XML feed
2082 public static function feed(App $a, $owner_nick, &$last_update, $max_items = 300)
2084 $stamp = microtime(true);
2086 $cachekey = "ostatus:feed:".$owner_nick.":".$last_update;
2088 $previous_created = $last_update;
2090 $result = Cache::get($cachekey);
2091 if (!is_null($result)) {
2092 logger('Feed duration: '.number_format(microtime(true) - $stamp, 3).' - '.$owner_nick.' - '.$previous_created.' (cached)', LOGGER_DEBUG);
2093 $last_update = $result['last_update'];
2094 return $result['feed'];
2098 "SELECT `contact`.*, `user`.`nickname`, `user`.`timezone`, `user`.`page-flags`
2099 FROM `contact` INNER JOIN `user` ON `user`.`uid` = `contact`.`uid`
2100 WHERE `contact`.`self` AND `user`.`nickname` = '%s' LIMIT 1",
2103 if (!DBM::is_result($r)) {
2109 if (!strlen($last_update)) {
2110 $last_update = 'now -30 days';
2113 $check_date = datetime_convert('UTC', 'UTC', $last_update, 'Y-m-d H:i:s');
2114 $authorid = Contact::getIdForURL($owner["url"], 0);
2117 "SELECT `item`.*, `item`.`id` AS `item_id` FROM `item` USE INDEX (`uid_contactid_created`)
2118 STRAIGHT_JOIN `thread` ON `thread`.`iid` = `item`.`parent`
2119 WHERE `item`.`uid` = %d AND `item`.`contact-id` = %d AND
2120 `item`.`author-id` = %d AND `item`.`created` > '%s' AND
2121 NOT `item`.`deleted` AND NOT `item`.`private` AND
2122 `thread`.`network` IN ('%s', '%s')
2123 ORDER BY `item`.`created` DESC LIMIT %d",
2124 intval($owner["uid"]), intval($owner["id"]),
2125 intval($authorid), dbesc($check_date),
2126 dbesc(NETWORK_OSTATUS), dbesc(NETWORK_DFRN), intval($max_items)
2129 $doc = new DOMDocument('1.0', 'utf-8');
2130 $doc->formatOutput = true;
2132 $root = self::addHeader($doc, $owner);
2134 foreach ($items as $item) {
2135 if (Config::get('system', 'ostatus_debug')) {
2136 $item['body'] .= '🍼';
2138 $entry = self::entry($doc, $item, $owner);
2139 $root->appendChild($entry);
2141 if ($last_update < $item['created']) {
2142 $last_update = $item['created'];
2146 $feeddata = trim($doc->saveXML());
2148 $msg = array('feed' => $feeddata, 'last_update' => $last_update);
2149 Cache::set($cachekey, $msg, CACHE_QUARTER_HOUR);
2151 logger('Feed duration: '.number_format(microtime(true) - $stamp, 3).' - '.$owner_nick.' - '.$previous_created, LOGGER_DEBUG);
2157 * @brief Creates the XML for a salmon message
2159 * @param array $item Data of the item that is to be posted
2160 * @param array $owner Contact data of the poster
2162 * @return string XML for the salmon
2164 public static function salmon($item, $owner)
2166 $doc = new DOMDocument('1.0', 'utf-8');
2167 $doc->formatOutput = true;
2169 if (Config::get('system', 'ostatus_debug')) {
2170 $item['body'] .= '🐟';
2173 $entry = self::entry($doc, $item, $owner, true);
2175 $doc->appendChild($entry);
2177 return trim($doc->saveXML());