3 * @file include/ostatus.php
7 use Friendica\Core\System;
8 use Friendica\Core\Config;
9 use Friendica\Network\Probe;
10 use Friendica\Util\Lock;
12 require_once 'include/Contact.php';
13 require_once 'include/threads.php';
14 require_once 'include/html2bbcode.php';
15 require_once 'include/bbcode.php';
16 require_once 'include/items.php';
17 require_once 'mod/share.php';
18 require_once 'include/enotify.php';
19 require_once 'include/socgraph.php';
20 require_once 'include/Photo.php';
21 require_once 'include/probe.php';
22 require_once 'include/follow.php';
23 require_once 'include/api.php';
24 require_once 'mod/proxy.php';
25 require_once 'include/xml.php';
26 require_once 'include/cache.php';
29 * @brief This class contain functions for the OStatus protocol
34 private static $itemlist;
35 private static $conv_list = array();
38 * @brief Fetches author data
40 * @param object $xpath The xpath object
41 * @param object $context The xml context of the author details
42 * @param array $importer user record of the importing user
43 * @param array $contact Called by reference, will contain the fetched contact
44 * @param bool $onlyfetch Only fetch the header without updating the contact entries
46 * @return array Array of author related entries for the item
48 private static function fetchauthor($xpath, $context, $importer, &$contact, $onlyfetch) {
51 $author["author-link"] = $xpath->evaluate('atom:author/atom:uri/text()', $context)->item(0)->nodeValue;
52 $author["author-name"] = $xpath->evaluate('atom:author/atom:name/text()', $context)->item(0)->nodeValue;
53 $addr = $xpath->evaluate('atom:author/atom:email/text()', $context)->item(0)->nodeValue;
55 $aliaslink = $author["author-link"];
57 $alternate = $xpath->query("atom:author/atom:link[@rel='alternate']", $context)->item(0)->attributes;
58 if (is_object($alternate)) {
59 foreach ($alternate AS $attributes) {
60 if (($attributes->name == "href") && ($attributes->textContent != "")) {
61 $author["author-link"] = $attributes->textContent;
65 $author["contact-id"] = $contact["id"];
69 if ($aliaslink != '') {
70 $condition = array("`uid` = ? AND `alias` = ? AND `network` != ?",
71 $importer["uid"], $aliaslink, NETWORK_STATUSNET);
72 $r = dba::select('contact', array(), $condition, array('limit' => 1));
74 if (dbm::is_result($r)) {
80 $author["contact-id"] = $r["id"];
84 if (!$found && ($author["author-link"] != "")) {
85 if ($aliaslink == "") {
86 $aliaslink = $author["author-link"];
89 $condition = array("`uid` = ? AND `nurl` IN (?, ?) AND `network` != ?", $importer["uid"],
90 normalise_link($author["author-link"]), normalise_link($aliaslink), NETWORK_STATUSNET);
91 $r = dba::select('contact', array(), $condition, array('limit' => 1));
93 if (dbm::is_result($r)) {
99 $author["contact-id"] = $r["id"];
103 if (!$found && ($addr != "")) {
104 $condition = array("`uid` = ? AND `addr` = ? AND `network` != ?",
105 $importer["uid"], $addr, NETWORK_STATUSNET);
106 $r = dba::select('contact', array(), $condition, array('limit' => 1));
108 if (dbm::is_result($r)) {
114 $author["contact-id"] = $r["id"];
118 $avatarlist = array();
119 $avatars = $xpath->query("atom:author/atom:link[@rel='avatar']", $context);
120 foreach ($avatars AS $avatar) {
123 foreach ($avatar->attributes AS $attributes) {
124 if ($attributes->name == "href") {
125 $href = $attributes->textContent;
127 if ($attributes->name == "width") {
128 $width = $attributes->textContent;
132 $avatarlist[$width] = $href;
135 if (count($avatarlist) > 0) {
137 $author["author-avatar"] = Probe::fixAvatar(current($avatarlist), $author["author-link"]);
140 $displayname = $xpath->evaluate('atom:author/poco:displayName/text()', $context)->item(0)->nodeValue;
141 if ($displayname != "") {
142 $author["author-name"] = $displayname;
145 $author["owner-name"] = $author["author-name"];
146 $author["owner-link"] = $author["author-link"];
147 $author["owner-avatar"] = $author["author-avatar"];
149 // Only update the contacts if it is an OStatus contact
150 if ($r && ($r['id'] > 0) && !$onlyfetch && ($contact["network"] == NETWORK_OSTATUS)) {
152 // Update contact data
155 unset($current['name-date']);
157 // This query doesn't seem to work
158 // $value = $xpath->query("atom:link[@rel='salmon']", $context)->item(0)->nodeValue;
160 // $contact["notify"] = $value;
162 // This query doesn't seem to work as well - I hate these queries
163 // $value = $xpath->query("atom:link[@rel='self' and @type='application/atom+xml']", $context)->item(0)->nodeValue;
165 // $contact["poll"] = $value;
167 $contact['url'] = $author["author-link"];
168 $contact['nurl'] = normalise_link($contact['url']);
170 $value = $xpath->evaluate('atom:author/atom:uri/text()', $context)->item(0)->nodeValue;
172 $contact["alias"] = $value;
174 $value = $xpath->evaluate('atom:author/poco:displayName/text()', $context)->item(0)->nodeValue;
176 $contact["name"] = $value;
178 $value = $xpath->evaluate('atom:author/poco:preferredUsername/text()', $context)->item(0)->nodeValue;
180 $contact["nick"] = $value;
182 $value = $xpath->evaluate('atom:author/poco:note/text()', $context)->item(0)->nodeValue;
184 $contact["about"] = html2bbcode($value);
186 $value = $xpath->evaluate('atom:author/poco:address/poco:formatted/text()', $context)->item(0)->nodeValue;
188 $contact["location"] = $value;
190 $contact['name-date'] = datetime_convert();
192 dba::update('contact', $contact, array('id' => $contact["id"]), $current);
194 if (!empty($author["author-avatar"]) && ($author["author-avatar"] != $current['avatar'])) {
195 logger("Update profile picture for contact ".$contact["id"], LOGGER_DEBUG);
196 update_contact_avatar($author["author-avatar"], $importer["uid"], $contact["id"]);
199 // Ensure that we are having this contact (with uid=0)
200 $cid = get_contact($aliaslink, 0);
203 $fields = array('url', 'nurl', 'name', 'nick', 'alias', 'about', 'location');
204 $old_contact = dba::select('contact', $fields, array('id' => $cid), array('limit' => 1));
206 // Update it with the current values
207 $fields = array('url' => $author["author-link"], 'name' => $contact["name"],
208 'nurl' => normalise_link($author["author-link"]),
209 'nick' => $contact["nick"], 'alias' => $contact["alias"],
210 'about' => $contact["about"], 'location' => $contact["location"],
211 'success_update' => datetime_convert(), 'last-update' => datetime_convert());
213 dba::update('contact', $fields, array('id' => $cid), $old_contact);
216 update_contact_avatar($author["author-avatar"], 0, $cid);
219 $contact["generation"] = 2;
220 $contact["hide"] = false; // OStatus contacts are never hidden
221 $contact["photo"] = $author["author-avatar"];
222 $gcid = update_gcontact($contact);
224 link_gcontact($gcid, $contact["uid"], $contact["id"]);
231 * @brief Fetches author data from a given XML string
233 * @param string $xml The XML
234 * @param array $importer user record of the importing user
236 * @return array Array of author related entries for the item
238 public static function salmon_author($xml, $importer) {
243 $doc = new DOMDocument();
244 @$doc->loadXML($xml);
246 $xpath = new DomXPath($doc);
247 $xpath->registerNamespace('atom', NAMESPACE_ATOM1);
248 $xpath->registerNamespace('thr', NAMESPACE_THREAD);
249 $xpath->registerNamespace('georss', NAMESPACE_GEORSS);
250 $xpath->registerNamespace('activity', NAMESPACE_ACTIVITY);
251 $xpath->registerNamespace('media', NAMESPACE_MEDIA);
252 $xpath->registerNamespace('poco', NAMESPACE_POCO);
253 $xpath->registerNamespace('ostatus', NAMESPACE_OSTATUS);
254 $xpath->registerNamespace('statusnet', NAMESPACE_STATUSNET);
256 $entries = $xpath->query('/atom:entry');
258 foreach ($entries AS $entry) {
260 $author = self::fetchauthor($xpath, $entry, $importer, $contact, true);
266 * @brief Read attributes from element
268 * @param object $element Element object
270 * @return array attributes
272 private static function read_attributes($element) {
273 $attribute = array();
275 foreach ($element->attributes AS $attributes) {
276 $attribute[$attributes->name] = $attributes->textContent;
283 * @brief Imports an XML string containing OStatus elements
285 * @param string $xml The XML
286 * @param array $importer user record of the importing user
287 * @param array $contact
288 * @param string $hub Called by reference, returns the fetched hub data
290 public static function import($xml, $importer, &$contact, &$hub) {
291 self::process($xml, $importer, $contact, $hub);
295 * @brief Internal feed processing
297 * @param string $xml The XML
298 * @param array $importer user record of the importing user
299 * @param array $contact
300 * @param string $hub Called by reference, returns the fetched hub data
301 * @param boolean $stored Is the post fresh imported or from the database?
302 * @param boolean $initialize Is it the leading post so that data has to be initialized?
304 * @return boolean Could the XML be processed?
306 private static function process($xml, $importer, &$contact, &$hub, $stored = false, $initialize = true) {
308 self::$itemlist = array();
309 self::$conv_list = array();
312 logger("Import OStatus message", LOGGER_DEBUG);
317 $doc = new DOMDocument();
318 @$doc->loadXML($xml);
320 $xpath = new DomXPath($doc);
321 $xpath->registerNamespace('atom', NAMESPACE_ATOM1);
322 $xpath->registerNamespace('thr', NAMESPACE_THREAD);
323 $xpath->registerNamespace('georss', NAMESPACE_GEORSS);
324 $xpath->registerNamespace('activity', NAMESPACE_ACTIVITY);
325 $xpath->registerNamespace('media', NAMESPACE_MEDIA);
326 $xpath->registerNamespace('poco', NAMESPACE_POCO);
327 $xpath->registerNamespace('ostatus', NAMESPACE_OSTATUS);
328 $xpath->registerNamespace('statusnet', NAMESPACE_STATUSNET);
331 $hub_attributes = $xpath->query("/atom:feed/atom:link[@rel='hub']")->item(0)->attributes;
332 if (is_object($hub_attributes)) {
333 foreach ($hub_attributes AS $hub_attribute) {
334 if ($hub_attribute->name == "href") {
335 $hub = $hub_attribute->textContent;
336 logger("Found hub ".$hub, LOGGER_DEBUG);
342 $header["uid"] = $importer["uid"];
343 $header["network"] = NETWORK_OSTATUS;
344 $header["type"] = "remote";
346 $header["origin"] = 0;
347 $header["gravity"] = GRAVITY_PARENT;
349 $first_child = $doc->firstChild->tagName;
351 if ($first_child == "feed") {
352 $entries = $xpath->query('/atom:feed/atom:entry');
354 $entries = $xpath->query('/atom:entry');
357 if ($entries->length == 1) {
358 // We reformat the XML to make it better readable
359 $doc2 = new DOMDocument();
360 $doc2->loadXML($xml);
361 $doc2->preserveWhiteSpace = false;
362 $doc2->formatOutput = true;
363 $xml2 = $doc2->saveXML();
365 $header["protocol"] = PROTOCOL_OSTATUS_SALMON;
366 $header["source"] = $xml2;
367 } elseif (!$initialize) {
371 // Fetch the first author
372 $authordata = $xpath->query('//author')->item(0);
373 $author = self::fetchauthor($xpath, $authordata, $importer, $contact, $stored);
375 $entry = $xpath->query('/atom:entry');
377 // Reverse the order of the entries
378 $entrylist = array();
380 foreach ($entries AS $entry) {
381 $entrylist[] = $entry;
384 foreach (array_reverse($entrylist) AS $entry) {
386 $authorelement = $xpath->query('/atom:entry/atom:author', $entry);
388 if ($authorelement->length == 0) {
389 $authorelement = $xpath->query('atom:author', $entry);
392 if ($authorelement->length > 0) {
393 $author = self::fetchauthor($xpath, $entry, $importer, $contact, $stored);
396 $value = $xpath->evaluate('atom:author/poco:preferredUsername/text()', $entry)->item(0)->nodeValue;
400 $nickname = $author["author-name"];
403 $item = array_merge($header, $author);
405 $item["uri"] = $xpath->query('atom:id/text()', $entry)->item(0)->nodeValue;
407 $item["verb"] = $xpath->query('activity:verb/text()', $entry)->item(0)->nodeValue;
410 if (in_array($item["verb"], array('qvitter-delete-notice', ACTIVITY_DELETE, 'delete'))) {
411 self::deleteNotice($item);
415 if (in_array($item["verb"], array(NAMESPACE_OSTATUS."/unfavorite", ACTIVITY_UNFAVORITE))) {
416 // Ignore "Unfavorite" message
417 logger("Ignore unfavorite message ".print_r($item, true), LOGGER_DEBUG);
421 // Deletions come with the same uri, so we check for duplicates after processing deletions
422 if (dba::exists('item', array('uid' => $importer["uid"], 'uri' => $item["uri"]))) {
423 logger('Post with URI '.$item["uri"].' already existed for user '.$importer["uid"].'.', LOGGER_DEBUG);
426 logger('Processing post with URI '.$item["uri"].' for user '.$importer["uid"].'.', LOGGER_DEBUG);
429 if ($item["verb"] == ACTIVITY_JOIN) {
430 // ignore "Join" messages
431 logger("Ignore join message ".print_r($item, true), LOGGER_DEBUG);
435 if ($item["verb"] == "http://mastodon.social/schema/1.0/block") {
436 // ignore mastodon "block" messages
437 logger("Ignore block message ".print_r($item, true), LOGGER_DEBUG);
441 if ($item["verb"] == ACTIVITY_FOLLOW) {
442 new_follower($importer, $contact, $item, $nickname);
446 if ($item["verb"] == NAMESPACE_OSTATUS."/unfollow") {
447 lose_follower($importer, $contact, $item, $dummy);
451 if ($item["verb"] == ACTIVITY_FAVORITE) {
452 $orig_uri = $xpath->query("activity:object/atom:id", $entry)->item(0)->nodeValue;
453 logger("Favorite ".$orig_uri." ".print_r($item, true));
455 $item["verb"] = ACTIVITY_LIKE;
456 $item["parent-uri"] = $orig_uri;
457 $item["gravity"] = GRAVITY_LIKE;
460 // http://activitystrea.ms/schema/1.0/rsvp-yes
461 if (!in_array($item["verb"], array(ACTIVITY_POST, ACTIVITY_LIKE, ACTIVITY_SHARE))) {
462 logger("Unhandled verb ".$item["verb"]." ".print_r($item, true), LOGGER_DEBUG);
465 self::processPost($xpath, $entry, $item, $importer);
467 if ($initialize && (count(self::$itemlist) > 0)) {
468 if (self::$itemlist[0]['uri'] == self::$itemlist[0]['parent-uri']) {
469 // We will import it everytime, when it is started by our contacts
470 $valid = !empty(self::$itemlist[0]['contact-id']);
472 // If not, then it depends on this setting
473 $valid = !Config::get('system','ostatus_full_threads');
476 // Never post a thread when the only interaction by our contact was a like
478 $verbs = array(ACTIVITY_POST, ACTIVITY_SHARE);
479 foreach (self::$itemlist AS $item) {
480 if (!empty($item['contact-id']) && in_array($item['verb'], $verbs)) {
486 // But we will only import complete threads
487 $valid = dba::exists('item', array('uid' => $importer["uid"], 'uri' => self::$itemlist[0]['parent-uri']));
491 $default_contact = 0;
492 $key = count(self::$itemlist);
493 for ($key = count(self::$itemlist) - 1; $key >= 0; $key--) {
494 if (empty(self::$itemlist[$key]['contact-id'])) {
495 self::$itemlist[$key]['contact-id'] = $default_contact;
497 $default_contact = $item['contact-id'];
500 foreach (self::$itemlist AS $item) {
501 $found = dba::exists('item', array('uid' => $importer["uid"], 'uri' => $item["uri"]));
503 logger("Item with uri ".$item["uri"]." for user ".$importer["uid"]." already exists.", LOGGER_DEBUG);
504 } elseif ($item['contact-id'] < 0) {
505 logger("Item with uri ".$item["uri"]." is from a blocked contact.", LOGGER_DEBUG);
507 // We are having duplicated entries. Hopefully this solves it.
508 if (Lock::set('ostatus_process_item_store')) {
509 $ret = item_store($item);
510 Lock::remove('ostatus_process_item_store');
511 logger("Item with uri ".$item["uri"]." for user ".$importer["uid"].' stored. Return value: '.$ret);
513 $ret = item_store($item);
514 logger("We couldn't lock - but tried to store the item anyway. Return value is ".$ret);
519 self::$itemlist = array();
521 logger('Processing done for post with URI '.$item["uri"].' for user '.$importer["uid"].'.', LOGGER_DEBUG);
526 private static function deleteNotice($item) {
528 $condition = array('uid' => $item['uid'], 'author-link' => $item['author-link'], 'uri' => $item['uri']);
529 $deleted = dba::select('item', array('id', 'parent-uri'), $condition, array('limit' => 1));
530 if (!dbm::is_result($deleted)) {
531 logger('Item from '.$item['author-link'].' with uri '.$item['uri'].' for user '.$item['uid']." wasn't found. We don't delete it. ");
535 // Currently we don't have a central deletion function that we could use in this case. The function "item_drop" doesn't work for that case
536 dba::update('item', array('deleted' => true, 'title' => '', 'body' => '',
537 'edited' => datetime_convert(), 'changed' => datetime_convert()),
538 array('id' => $deleted["id"]));
540 delete_thread($deleted["id"], $deleted["parent-uri"]);
542 logger('Deleted item with uri '.$item['uri'].' for user '.$item['uid']);
546 * @brief Processes the XML for a post
548 * @param object $xpath The xpath object
549 * @param object $entry The xml entry that is processed
550 * @param array $item The item array
551 * @param array $importer user record of the importing user
553 private static function processPost($xpath, $entry, &$item, $importer) {
554 $item["body"] = html2bbcode($xpath->query('atom:content/text()', $entry)->item(0)->nodeValue);
555 $item["object-type"] = $xpath->query('activity:object-type/text()', $entry)->item(0)->nodeValue;
556 if (($item["object-type"] == ACTIVITY_OBJ_BOOKMARK) || ($item["object-type"] == ACTIVITY_OBJ_EVENT)) {
557 $item["title"] = $xpath->query('atom:title/text()', $entry)->item(0)->nodeValue;
558 $item["body"] = $xpath->query('atom:summary/text()', $entry)->item(0)->nodeValue;
559 } elseif ($item["object-type"] == ACTIVITY_OBJ_QUESTION) {
560 $item["title"] = $xpath->query('atom:title/text()', $entry)->item(0)->nodeValue;
563 $item["created"] = $xpath->query('atom:published/text()', $entry)->item(0)->nodeValue;
564 $item["edited"] = $xpath->query('atom:updated/text()', $entry)->item(0)->nodeValue;
565 $conversation = $xpath->query('ostatus:conversation/text()', $entry)->item(0)->nodeValue;
566 $item['conversation-uri'] = $conversation;
568 $conv = $xpath->query('ostatus:conversation', $entry);
569 if (is_object($conv->item(0))) {
570 foreach ($conv->item(0)->attributes AS $attributes) {
571 if ($attributes->name == "ref") {
572 $item['conversation-uri'] = $attributes->textContent;
574 if ($attributes->name == "href") {
575 $item['conversation-href'] = $attributes->textContent;
582 $inreplyto = $xpath->query('thr:in-reply-to', $entry);
583 if (is_object($inreplyto->item(0))) {
584 foreach ($inreplyto->item(0)->attributes AS $attributes) {
585 if ($attributes->name == "ref") {
586 $item["parent-uri"] = $attributes->textContent;
588 if ($attributes->name == "href") {
589 $related = $attributes->textContent;
594 $georsspoint = $xpath->query('georss:point', $entry);
595 if (!empty($georsspoint) && ($georsspoint->length > 0)) {
596 $item["coord"] = $georsspoint->item(0)->nodeValue;
599 $categories = $xpath->query('atom:category', $entry);
601 foreach ($categories AS $category) {
602 foreach ($category->attributes AS $attributes) {
603 if ($attributes->name == "term") {
604 $term = $attributes->textContent;
605 if (strlen($item["tag"])) {
608 $item["tag"] .= "#[url=".System::baseUrl()."/search?tag=".$term."]".$term."[/url]";
617 $links = $xpath->query('atom:link', $entry);
619 $link_data = self::processLinks($links, $item);
620 $self = $link_data['self'];
621 $add_body = $link_data['add_body'];
626 $notice_info = $xpath->query('statusnet:notice_info', $entry);
627 if ($notice_info && ($notice_info->length > 0)) {
628 foreach ($notice_info->item(0)->attributes AS $attributes) {
629 if ($attributes->name == "source") {
630 $item["app"] = strip_tags($attributes->textContent);
632 if ($attributes->name == "repeat_of") {
633 $repeat_of = $attributes->textContent;
637 // Is it a repeated post?
638 if (($repeat_of != "") || ($item["verb"] == ACTIVITY_SHARE)) {
639 $link_data = self::processRepeatedItem($xpath, $entry, $item, $importer);
640 if (!empty($link_data['add_body'])) {
641 $add_body .= $link_data['add_body'];
645 $item["body"] .= $add_body;
647 // Only add additional data when there is no picture in the post
648 if (!strstr($item["body"],'[/img]')) {
649 $item["body"] = add_page_info_to_body($item["body"]);
652 // Mastodon Content Warning
653 if (($item["verb"] == ACTIVITY_POST) && $xpath->evaluate('boolean(atom:summary)', $entry)) {
654 $clear_text = $xpath->query('atom:summary/text()', $entry)->item(0)->nodeValue;
656 $item["body"] = html2bbcode($clear_text) . '[spoiler]' . $item["body"] . '[/spoiler]';
659 if (($self != '') && empty($item['protocol'])) {
660 self::fetchSelf($self, $item);
663 if (!empty($item["conversation-href"])) {
664 self::fetchConversation($item['conversation-href'], $item['conversation-uri']);
667 if (isset($item["parent-uri"]) && ($related != '')) {
668 if (!dba::exists('item', array('uid' => $importer["uid"], 'uri' => $item['parent-uri']))) {
669 self::fetchRelated($related, $item["parent-uri"], $importer);
671 logger('Reply with URI '.$item["uri"].' already existed for user '.$importer["uid"].'.', LOGGER_DEBUG);
674 $item["type"] = 'remote-comment';
675 $item["gravity"] = GRAVITY_COMMENT;
677 $item["parent-uri"] = $item["uri"];
680 if (($item['author-link'] != '') && !empty($item['protocol'])) {
681 $item = store_conversation($item);
684 self::$itemlist[] = $item;
688 * @brief Fetch the conversation for posts
690 * @param string $conversation The link to the conversation
691 * @param string $conversation_uri The conversation in "uri" format
693 private static function fetchConversation($conversation, $conversation_uri) {
695 // Ensure that we only store a conversation once in a process
696 if (isset(self::$conv_list[$conversation])) {
700 self::$conv_list[$conversation] = true;
702 $conversation_data = z_fetch_url($conversation, false, $redirects, array('accept_content' => 'application/atom+xml, text/html'));
704 if (!$conversation_data['success']) {
710 if (stristr($conversation_data['header'], 'Content-Type: application/atom+xml')) {
711 $xml = $conversation_data['body'];
715 $doc = new DOMDocument();
716 if (!@$doc->loadHTML($conversation_data['body'])) {
719 $xpath = new DomXPath($doc);
721 $links = $xpath->query('//link');
723 foreach ($links AS $link) {
724 $attribute = ostatus::read_attributes($link);
725 if (($attribute['rel'] == 'alternate') && ($attribute['type'] == 'application/atom+xml')) {
726 $file = $attribute['href'];
730 $conversation_atom = z_fetch_url($attribute['href']);
732 if ($conversation_atom['success']) {
733 $xml = $conversation_atom['body'];
743 self::storeConversation($xml, $conversation, $conversation_uri);
747 * @brief Store a feed in several conversation entries
749 * @param string $xml The feed
751 private static function storeConversation($xml, $conversation = '', $conversation_uri = '') {
752 $doc = new DOMDocument();
753 @$doc->loadXML($xml);
755 $xpath = new DomXPath($doc);
756 $xpath->registerNamespace('atom', NAMESPACE_ATOM1);
757 $xpath->registerNamespace('thr', NAMESPACE_THREAD);
758 $xpath->registerNamespace('ostatus', NAMESPACE_OSTATUS);
760 $entries = $xpath->query('/atom:feed/atom:entry');
762 // Now store the entries
763 foreach ($entries AS $entry) {
764 $doc2 = new DOMDocument();
765 $doc2->preserveWhiteSpace = false;
766 $doc2->formatOutput = true;
768 $conv_data = array();
770 $conv_data['protocol'] = PROTOCOL_SPLITTED_CONV;
771 $conv_data['network'] = NETWORK_OSTATUS;
772 $conv_data['uri'] = $xpath->query('atom:id/text()', $entry)->item(0)->nodeValue;
774 $inreplyto = $xpath->query('thr:in-reply-to', $entry);
775 if (is_object($inreplyto->item(0))) {
776 foreach ($inreplyto->item(0)->attributes AS $attributes) {
777 if ($attributes->name == "ref") {
778 $conv_data['reply-to-uri'] = $attributes->textContent;
783 $conv = $xpath->query('ostatus:conversation/text()', $entry)->item(0)->nodeValue;
784 $conv_data['conversation-uri'] = $conv;
786 $conv = $xpath->query('ostatus:conversation', $entry);
787 if (is_object($conv->item(0))) {
788 foreach ($conv->item(0)->attributes AS $attributes) {
789 if ($attributes->name == "ref") {
790 $conv_data['conversation-uri'] = $attributes->textContent;
792 if ($attributes->name == "href") {
793 $conv_data['conversation-href'] = $attributes->textContent;
798 if ($conversation != '') {
799 $conv_data['conversation-uri'] = $conversation;
802 if ($conversation_uri != '') {
803 $conv_data['conversation-uri'] = $conversation_uri;
806 $entry = $doc2->importNode($entry, true);
808 $doc2->appendChild($entry);
810 $conv_data['source'] = $doc2->saveXML();
812 $condition = array('item-uri' => $conv_data['uri'],'protocol' => PROTOCOL_OSTATUS_FEED);
813 if (dba::exists('conversation', $condition)) {
814 logger('Delete deprecated entry for URI '.$conv_data['uri'], LOGGER_DEBUG);
815 dba::delete('conversation', array('item-uri' => $conv_data['uri']));
818 logger('Store conversation data for uri '.$conv_data['uri'], LOGGER_DEBUG);
819 store_conversation($conv_data);
824 * @brief Fetch the own post so that it can be stored later
825 * @param array $item The item array
827 * We want to store the original data for later processing.
828 * This function is meant for cases where we process a feed with multiple entries.
829 * In that case we need to fetch the single posts here.
831 * @param string $self The link to the self item
833 private static function fetchSelf($self, &$item) {
834 $condition = array('`item-uri` = ? AND `protocol` IN (?, ?)', $self, PROTOCOL_DFRN, PROTOCOL_OSTATUS_SALMON);
835 if (dba::exists('conversation', $condition)) {
836 logger('Conversation '.$item['uri'].' is already stored.', LOGGER_DEBUG);
840 $self_data = z_fetch_url($self);
842 if (!$self_data['success']) {
846 // We reformat the XML to make it better readable
847 $doc = new DOMDocument();
848 $doc->loadXML($self_data['body']);
849 $doc->preserveWhiteSpace = false;
850 $doc->formatOutput = true;
851 $xml = $doc->saveXML();
853 $item["protocol"] = PROTOCOL_OSTATUS_SALMON;
854 $item["source"] = $xml;
856 logger('Conversation '.$item['uri'].' is now fetched.', LOGGER_DEBUG);
860 * @brief Fetch related posts and processes them
862 * @param string $related The link to the related item
863 * @param string $related_uri The related item in "uri" format
864 * @param array $importer user record of the importing user
866 private static function fetchRelated($related, $related_uri, $importer) {
867 $condition = array('`item-uri` = ? AND `protocol` IN (?, ?)', $related_uri, PROTOCOL_DFRN, PROTOCOL_OSTATUS_SALMON);
868 $conversation = dba::select('conversation', array('source', 'protocol'), $condition, array('limit' => 1));
869 if (dbm::is_result($conversation)) {
871 $xml = $conversation['source'];
872 if (self::process($xml, $importer, $contact, $hub, $stored, false)) {
873 logger('Got valid cached XML for URI '.$related_uri, LOGGER_DEBUG);
876 if ($conversation['protocol'] == PROTOCOL_OSTATUS_SALMON) {
877 logger('Delete invalid cached XML for URI '.$related_uri, LOGGER_DEBUG);
878 dba::delete('conversation', array('item-uri' => $related_uri));
883 $related_data = z_fetch_url($related, false, $redirects, array('accept_content' => 'application/atom+xml, text/html'));
885 if (!$related_data['success']) {
891 if (stristr($related_data['header'], 'Content-Type: application/atom+xml')) {
892 logger('Directly fetched XML for URI '.$related_uri, LOGGER_DEBUG);
893 $xml = $related_data['body'];
897 $doc = new DOMDocument();
898 if (!@$doc->loadHTML($related_data['body'])) {
901 $xpath = new DomXPath($doc);
905 $links = $xpath->query('//link');
907 foreach ($links AS $link) {
908 $attribute = self::read_attributes($link);
909 if (($attribute['rel'] == 'alternate') && ($attribute['type'] == 'application/atom+xml')) {
910 $atom_file = $attribute['href'];
913 if ($atom_file != '') {
914 $related_atom = z_fetch_url($atom_file);
916 if ($related_atom['success']) {
917 logger('Fetched XML for URI '.$related_uri, LOGGER_DEBUG);
918 $xml = $related_atom['body'];
924 // Workaround for older GNU Social servers
925 if (($xml == '') && strstr($related, '/notice/')) {
926 $related_atom = z_fetch_url(str_replace('/notice/', '/api/statuses/show/', $related).'.atom');
928 if ($related_atom['success']) {
929 logger('GNU Social workaround to fetch XML for URI '.$related_uri, LOGGER_DEBUG);
930 $xml = $related_atom['body'];
934 // Even more worse workaround for GNU Social ;-)
936 $related_guess = ostatus::convert_href($related_uri);
937 $related_atom = z_fetch_url(str_replace('/notice/', '/api/statuses/show/', $related_guess).'.atom');
939 if ($related_atom['success']) {
940 logger('GNU Social workaround 2 to fetch XML for URI '.$related_uri, LOGGER_DEBUG);
941 $xml = $related_atom['body'];
945 // Finally we take the data that we fetched from "ostatus:conversation"
947 $condition = array('item-uri' => $related_uri, 'protocol' => PROTOCOL_SPLITTED_CONV);
948 $conversation = dba::select('conversation', array('source'), $condition, array('limit' => 1));
949 if (dbm::is_result($conversation)) {
951 logger('Got cached XML from conversation for URI '.$related_uri, LOGGER_DEBUG);
952 $xml = $conversation['source'];
957 self::process($xml, $importer, $contact, $hub, $stored, false);
959 logger("XML couldn't be fetched for URI: ".$related_uri." - href: ".$related, LOGGER_DEBUG);
965 * @brief Processes the XML for a repeated post
967 * @param object $xpath The xpath object
968 * @param object $entry The xml entry that is processed
969 * @param array $item The item array
970 * @param array $importer user record of the importing user
972 * @return array with data from links
974 private static function processRepeatedItem($xpath, $entry, &$item, $importer) {
975 $activityobjects = $xpath->query('activity:object', $entry)->item(0);
977 if (!is_object($activityobjects)) {
981 $link_data = array();
983 $orig_uri = $xpath->query('atom:id/text()', $activityobjects)->item(0)->nodeValue;
985 $links = $xpath->query("atom:link", $activityobjects);
987 $link_data = self::processLinks($links, $item);
990 $orig_body = $xpath->query('atom:content/text()', $activityobjects)->item(0)->nodeValue;
991 $orig_created = $xpath->query('atom:published/text()', $activityobjects)->item(0)->nodeValue;
992 $orig_edited = $xpath->query('atom:updated/text()', $activityobjects)->item(0)->nodeValue;
994 $orig_contact = $contact;
995 $orig_author = self::fetchauthor($xpath, $activityobjects, $importer, $orig_contact, false);
997 $item["author-name"] = $orig_author["author-name"];
998 $item["author-link"] = $orig_author["author-link"];
999 $item["author-avatar"] = $orig_author["author-avatar"];
1001 $item["body"] = html2bbcode($orig_body);
1002 $item["created"] = $orig_created;
1003 $item["edited"] = $orig_edited;
1005 $item["uri"] = $orig_uri;
1007 $item["verb"] = $xpath->query('activity:verb/text()', $activityobjects)->item(0)->nodeValue;
1009 $item["object-type"] = $xpath->query('activity:object-type/text()', $activityobjects)->item(0)->nodeValue;
1011 $inreplyto = $xpath->query('thr:in-reply-to', $activityobjects);
1012 if (is_object($inreplyto->item(0))) {
1013 foreach ($inreplyto->item(0)->attributes AS $attributes) {
1014 if ($attributes->name == "ref") {
1015 $item["parent-uri"] = $attributes->textContent;
1024 * @brief Processes links in the XML
1026 * @param object $links The xml data that contain links
1027 * @param array $item The item array
1029 * @return array with data from the links
1031 private static function processLinks($links, &$item) {
1032 $link_data = array('add_body' => '', 'self' => '');
1034 foreach ($links AS $link) {
1035 $attribute = self::read_attributes($link);
1037 if (($attribute['rel'] != "") && ($attribute['href'] != "")) {
1038 switch ($attribute['rel']) {
1040 $item["plink"] = $attribute['href'];
1041 if (($item["object-type"] == ACTIVITY_OBJ_QUESTION) ||
1042 ($item["object-type"] == ACTIVITY_OBJ_EVENT)) {
1043 $item["body"] .= add_page_info($attribute['href']);
1046 case "ostatus:conversation":
1047 $link_data['conversation'] = $attribute['href'];
1048 $item['conversation-href'] = $link_data['conversation'];
1049 if (!isset($item['conversation-uri'])) {
1050 $item['conversation-uri'] = $item['conversation-href'];
1054 $filetype = strtolower(substr($attribute['type'], 0, strpos($attribute['type'],'/')));
1055 if ($filetype == 'image') {
1056 $link_data['add_body'] .= "\n[img]".$attribute['href'].'[/img]';
1058 if (strlen($item["attach"])) {
1059 $item["attach"] .= ',';
1061 if (!isset($attribute['length'])) {
1062 $attribute['length'] = "0";
1064 $item["attach"] .= '[attach]href="'.$attribute['href'].'" length="'.$attribute['length'].'" type="'.$attribute['type'].'" title="'.$attribute['title'].'"[/attach]';
1068 if ($item["object-type"] != ACTIVITY_OBJ_BOOKMARK) {
1069 if (!isset($item["parent-uri"])) {
1070 $item["parent-uri"] = $attribute['href'];
1072 $link_data['related'] = $attribute['href'];
1074 $item["body"] .= add_page_info($attribute['href']);
1078 if ($item["plink"] == '') {
1079 $item["plink"] = $attribute['href'];
1081 $link_data['self'] = $attribute['href'];
1090 * @brief Create an url out of an uri
1092 * @param string $href URI in the format "parameter1:parameter1:..."
1094 * @return string URL in the format http(s)://....
1096 public static function convert_href($href) {
1097 $elements = explode(":",$href);
1099 if ((count($elements) <= 2) || ($elements[0] != "tag"))
1102 $server = explode(",", $elements[1]);
1103 $conversation = explode("=", $elements[2]);
1105 if ((count($elements) == 4) && ($elements[2] == "post"))
1106 return "http://".$server[0]."/notice/".$elements[3];
1108 if ((count($conversation) != 2) || ($conversation[1] =="")) {
1111 if ($elements[3] == "objectType=thread") {
1112 return "http://".$server[0]."/conversation/".$conversation[1];
1114 return "http://".$server[0]."/notice/".$conversation[1];
1120 * @brief Checks if the current post is a reshare
1122 * @param array $item The item array of thw post
1124 * @return string The guid if the post is a reshare
1126 private static function get_reshared_guid($item) {
1127 $body = trim($item["body"]);
1129 // Skip if it isn't a pure repeated messages
1130 // Does it start with a share?
1131 if (strpos($body, "[share") > 0)
1134 // Does it end with a share?
1135 if (strlen($body) > (strrpos($body, "[/share]") + 8))
1138 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$1",$body);
1139 // Skip if there is no shared message in there
1140 if ($body == $attributes)
1144 preg_match("/guid='(.*?)'/ism", $attributes, $matches);
1145 if ($matches[1] != "")
1146 $guid = $matches[1];
1148 preg_match('/guid="(.*?)"/ism', $attributes, $matches);
1149 if ($matches[1] != "")
1150 $guid = $matches[1];
1156 * @brief Cleans the body of a post if it contains picture links
1158 * @param string $body The body
1160 * @return string The cleaned body
1162 private static function format_picture_post($body) {
1163 $siteinfo = get_attached_data($body);
1165 if (($siteinfo["type"] == "photo")) {
1166 if (isset($siteinfo["preview"]))
1167 $preview = $siteinfo["preview"];
1169 $preview = $siteinfo["image"];
1171 // Is it a remote picture? Then make a smaller preview here
1172 $preview = proxy_url($preview, false, PROXY_SIZE_SMALL);
1174 // Is it a local picture? Then make it smaller here
1175 $preview = str_replace(array("-0.jpg", "-0.png"), array("-2.jpg", "-2.png"), $preview);
1176 $preview = str_replace(array("-1.jpg", "-1.png"), array("-2.jpg", "-2.png"), $preview);
1178 if (isset($siteinfo["url"]))
1179 $url = $siteinfo["url"];
1181 $url = $siteinfo["image"];
1183 $body = trim($siteinfo["text"])." [url]".$url."[/url]\n[img]".$preview."[/img]";
1190 * @brief Adds the header elements to the XML document
1192 * @param object $doc XML document
1193 * @param array $owner Contact data of the poster
1195 * @return object header root element
1197 private static function add_header($doc, $owner) {
1201 $root = $doc->createElementNS(NAMESPACE_ATOM1, 'feed');
1202 $doc->appendChild($root);
1204 $root->setAttribute("xmlns:thr", NAMESPACE_THREAD);
1205 $root->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
1206 $root->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
1207 $root->setAttribute("xmlns:media", NAMESPACE_MEDIA);
1208 $root->setAttribute("xmlns:poco", NAMESPACE_POCO);
1209 $root->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
1210 $root->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
1211 $root->setAttribute("xmlns:mastodon", NAMESPACE_MASTODON);
1213 $attributes = array("uri" => "https://friendi.ca", "version" => FRIENDICA_VERSION."-".DB_UPDATE_VERSION);
1214 xml::add_element($doc, $root, "generator", FRIENDICA_PLATFORM, $attributes);
1215 xml::add_element($doc, $root, "id", System::baseUrl()."/profile/".$owner["nick"]);
1216 xml::add_element($doc, $root, "title", sprintf("%s timeline", $owner["name"]));
1217 xml::add_element($doc, $root, "subtitle", sprintf("Updates from %s on %s", $owner["name"], $a->config["sitename"]));
1218 xml::add_element($doc, $root, "logo", $owner["photo"]);
1219 xml::add_element($doc, $root, "updated", datetime_convert("UTC", "UTC", "now", ATOM_TIME));
1221 $author = self::add_author($doc, $owner);
1222 $root->appendChild($author);
1224 $attributes = array("href" => $owner["url"], "rel" => "alternate", "type" => "text/html");
1225 xml::add_element($doc, $root, "link", "", $attributes);
1227 /// @TODO We have to find out what this is
1228 /// $attributes = array("href" => System::baseUrl()."/sup",
1229 /// "rel" => "http://api.friendfeed.com/2008/03#sup",
1230 /// "type" => "application/json");
1231 /// xml::add_element($doc, $root, "link", "", $attributes);
1233 self::hublinks($doc, $root, $owner["nick"]);
1235 $attributes = array("href" => System::baseUrl()."/salmon/".$owner["nick"], "rel" => "salmon");
1236 xml::add_element($doc, $root, "link", "", $attributes);
1238 $attributes = array("href" => System::baseUrl()."/salmon/".$owner["nick"], "rel" => "http://salmon-protocol.org/ns/salmon-replies");
1239 xml::add_element($doc, $root, "link", "", $attributes);
1241 $attributes = array("href" => System::baseUrl()."/salmon/".$owner["nick"], "rel" => "http://salmon-protocol.org/ns/salmon-mention");
1242 xml::add_element($doc, $root, "link", "", $attributes);
1244 $attributes = array("href" => System::baseUrl()."/api/statuses/user_timeline/".$owner["nick"].".atom",
1245 "rel" => "self", "type" => "application/atom+xml");
1246 xml::add_element($doc, $root, "link", "", $attributes);
1252 * @brief Add the link to the push hubs to the XML document
1254 * @param object $doc XML document
1255 * @param object $root XML root element where the hub links are added
1257 public static function hublinks($doc, $root, $nick) {
1258 $h = System::baseUrl() . '/pubsubhubbub/'.$nick;
1259 xml::add_element($doc, $root, "link", "", array("href" => $h, "rel" => "hub"));
1263 * @brief Adds attachement data to the XML document
1265 * @param object $doc XML document
1266 * @param object $root XML root element where the hub links are added
1267 * @param array $item Data of the item that is to be posted
1269 private static function get_attachment($doc, $root, $item) {
1271 $siteinfo = get_attached_data($item["body"]);
1273 switch ($siteinfo["type"]) {
1275 $imgdata = get_photo_info($siteinfo["image"]);
1276 $attributes = array("rel" => "enclosure",
1277 "href" => $siteinfo["image"],
1278 "type" => $imgdata["mime"],
1279 "length" => intval($imgdata["size"]));
1280 xml::add_element($doc, $root, "link", "", $attributes);
1283 $attributes = array("rel" => "enclosure",
1284 "href" => $siteinfo["url"],
1285 "type" => "text/html; charset=UTF-8",
1287 "title" => $siteinfo["title"]);
1288 xml::add_element($doc, $root, "link", "", $attributes);
1294 if (!Config::get('system', 'ostatus_not_attach_preview') && ($siteinfo["type"] != "photo") && isset($siteinfo["image"])) {
1295 $imgdata = get_photo_info($siteinfo["image"]);
1296 $attributes = array("rel" => "enclosure",
1297 "href" => $siteinfo["image"],
1298 "type" => $imgdata["mime"],
1299 "length" => intval($imgdata["size"]));
1301 xml::add_element($doc, $root, "link", "", $attributes);
1304 $arr = explode('[/attach],', $item['attach']);
1306 foreach ($arr as $r) {
1308 $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"|', $r, $matches);
1310 $attributes = array("rel" => "enclosure",
1311 "href" => $matches[1],
1312 "type" => $matches[3]);
1314 if (intval($matches[2])) {
1315 $attributes["length"] = intval($matches[2]);
1317 if (trim($matches[4]) != "") {
1318 $attributes["title"] = trim($matches[4]);
1320 xml::add_element($doc, $root, "link", "", $attributes);
1327 * @brief Adds the author element to the XML document
1329 * @param object $doc XML document
1330 * @param array $owner Contact data of the poster
1332 * @return object author element
1334 private static function add_author($doc, $owner) {
1336 $r = q("SELECT `homepage`, `publish` FROM `profile` WHERE `uid` = %d AND `is-default` LIMIT 1", intval($owner["uid"]));
1337 if (dbm::is_result($r)) {
1340 $author = $doc->createElement("author");
1341 xml::add_element($doc, $author, "id", $owner["url"]);
1342 xml::add_element($doc, $author, "activity:object-type", ACTIVITY_OBJ_PERSON);
1343 xml::add_element($doc, $author, "uri", $owner["url"]);
1344 xml::add_element($doc, $author, "name", $owner["nick"]);
1345 xml::add_element($doc, $author, "email", $owner["addr"]);
1346 xml::add_element($doc, $author, "summary", bbcode($owner["about"], false, false, 7));
1348 $attributes = array("rel" => "alternate", "type" => "text/html", "href" => $owner["url"]);
1349 xml::add_element($doc, $author, "link", "", $attributes);
1351 $attributes = array(
1353 "type" => "image/jpeg", // To-Do?
1354 "media:width" => 175,
1355 "media:height" => 175,
1356 "href" => $owner["photo"]);
1357 xml::add_element($doc, $author, "link", "", $attributes);
1359 if (isset($owner["thumb"])) {
1360 $attributes = array(
1362 "type" => "image/jpeg", // To-Do?
1363 "media:width" => 80,
1364 "media:height" => 80,
1365 "href" => $owner["thumb"]);
1366 xml::add_element($doc, $author, "link", "", $attributes);
1369 xml::add_element($doc, $author, "poco:preferredUsername", $owner["nick"]);
1370 xml::add_element($doc, $author, "poco:displayName", $owner["name"]);
1371 xml::add_element($doc, $author, "poco:note", bbcode($owner["about"], false, false, 7));
1373 if (trim($owner["location"]) != "") {
1374 $element = $doc->createElement("poco:address");
1375 xml::add_element($doc, $element, "poco:formatted", $owner["location"]);
1376 $author->appendChild($element);
1379 if (trim($profile["homepage"]) != "") {
1380 $urls = $doc->createElement("poco:urls");
1381 xml::add_element($doc, $urls, "poco:type", "homepage");
1382 xml::add_element($doc, $urls, "poco:value", $profile["homepage"]);
1383 xml::add_element($doc, $urls, "poco:primary", "true");
1384 $author->appendChild($urls);
1387 if (count($profile)) {
1388 xml::add_element($doc, $author, "followers", "", array("url" => System::baseUrl()."/viewcontacts/".$owner["nick"]));
1389 xml::add_element($doc, $author, "statusnet:profile_info", "", array("local_id" => $owner["uid"]));
1392 if ($profile["publish"]) {
1393 xml::add_element($doc, $author, "mastodon:scope", "public");
1399 * @TODO Picture attachments should look like this:
1400 * <a href="https://status.pirati.ca/attachment/572819" title="https://status.pirati.ca/file/heluecht-20151202T222602-rd3u49p.gif"
1401 * class="attachment thumbnail" id="attachment-572819" rel="nofollow external">https://status.pirati.ca/attachment/572819</a>
1406 * @brief Returns the given activity if present - otherwise returns the "post" activity
1408 * @param array $item Data of the item that is to be posted
1410 * @return string activity
1412 private static function construct_verb($item) {
1414 return $item['verb'];
1415 return ACTIVITY_POST;
1419 * @brief Returns the given object type if present - otherwise returns the "note" object type
1421 * @param array $item Data of the item that is to be posted
1423 * @return string Object type
1425 private static function construct_objecttype($item) {
1426 if (in_array($item['object-type'], array(ACTIVITY_OBJ_NOTE, ACTIVITY_OBJ_COMMENT)))
1427 return $item['object-type'];
1428 return ACTIVITY_OBJ_NOTE;
1432 * @brief Adds an entry element to the XML document
1434 * @param object $doc XML document
1435 * @param array $item Data of the item that is to be posted
1436 * @param array $owner Contact data of the poster
1437 * @param bool $toplevel
1439 * @return object Entry element
1441 private static function entry($doc, $item, $owner, $toplevel = false) {
1442 $repeated_guid = self::get_reshared_guid($item);
1443 if ($repeated_guid != "")
1444 $xml = self::reshare_entry($doc, $item, $owner, $repeated_guid, $toplevel);
1449 if ($item["verb"] == ACTIVITY_LIKE) {
1450 return self::like_entry($doc, $item, $owner, $toplevel);
1451 } elseif (in_array($item["verb"], array(ACTIVITY_FOLLOW, NAMESPACE_OSTATUS."/unfollow"))) {
1452 return self::follow_entry($doc, $item, $owner, $toplevel);
1454 return self::note_entry($doc, $item, $owner, $toplevel);
1459 * @brief Adds a source entry to the XML document
1461 * @param object $doc XML document
1462 * @param array $contact Array of the contact that is added
1464 * @return object Source element
1466 private static function source_entry($doc, $contact) {
1467 $source = $doc->createElement("source");
1468 xml::add_element($doc, $source, "id", $contact["poll"]);
1469 xml::add_element($doc, $source, "title", $contact["name"]);
1470 xml::add_element($doc, $source, "link", "", array("rel" => "alternate",
1471 "type" => "text/html",
1472 "href" => $contact["alias"]));
1473 xml::add_element($doc, $source, "link", "", array("rel" => "self",
1474 "type" => "application/atom+xml",
1475 "href" => $contact["poll"]));
1476 xml::add_element($doc, $source, "icon", $contact["photo"]);
1477 xml::add_element($doc, $source, "updated", datetime_convert("UTC","UTC",$contact["success_update"]."+00:00",ATOM_TIME));
1483 * @brief Fetches contact data from the contact or the gcontact table
1485 * @param string $url URL of the contact
1486 * @param array $owner Contact data of the poster
1488 * @return array Contact array
1490 private static function contact_entry($url, $owner) {
1492 $r = q("SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` IN (0, %d) ORDER BY `uid` DESC LIMIT 1",
1493 dbesc(normalise_link($url)), intval($owner["uid"]));
1494 if (dbm::is_result($r)) {
1496 $contact["uid"] = -1;
1499 if (!dbm::is_result($r)) {
1500 $r = q("SELECT * FROM `gcontact` WHERE `nurl` = '%s' LIMIT 1",
1501 dbesc(normalise_link($url)));
1502 if (dbm::is_result($r)) {
1504 $contact["uid"] = -1;
1505 $contact["success_update"] = $contact["updated"];
1509 if (!dbm::is_result($r))
1512 if (!isset($contact["poll"])) {
1513 $data = probe_url($url);
1514 $contact["poll"] = $data["poll"];
1516 if (!$contact["alias"])
1517 $contact["alias"] = $data["alias"];
1520 if (!isset($contact["alias"]))
1521 $contact["alias"] = $contact["url"];
1527 * @brief Adds an entry element with reshared content
1529 * @param object $doc XML document
1530 * @param array $item Data of the item that is to be posted
1531 * @param array $owner Contact data of the poster
1532 * @param $repeated_guid
1533 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1535 * @return object Entry element
1537 private static function reshare_entry($doc, $item, $owner, $repeated_guid, $toplevel) {
1539 if (($item["id"] != $item["parent"]) && (normalise_link($item["author-link"]) != normalise_link($owner["url"]))) {
1540 logger("OStatus entry is from author ".$owner["url"]." - not from ".$item["author-link"].". Quitting.", LOGGER_DEBUG);
1543 $title = self::entry_header($doc, $entry, $owner, $toplevel);
1545 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' AND NOT `private` AND `network` IN ('%s', '%s', '%s') LIMIT 1",
1546 intval($owner["uid"]), dbesc($repeated_guid),
1547 dbesc(NETWORK_DFRN), dbesc(NETWORK_DIASPORA), dbesc(NETWORK_OSTATUS));
1548 if (dbm::is_result($r)) {
1549 $repeated_item = $r[0];
1553 $contact = self::contact_entry($repeated_item['author-link'], $owner);
1555 $parent_item = (($item['thr-parent']) ? $item['thr-parent'] : $item['parent-uri']);
1557 $title = $owner["nick"]." repeated a notice by ".$contact["nick"];
1559 self::entry_content($doc, $entry, $item, $owner, $title, ACTIVITY_SHARE, false);
1561 $as_object = $doc->createElement("activity:object");
1563 xml::add_element($doc, $as_object, "activity:object-type", NAMESPACE_ACTIVITY_SCHEMA."activity");
1565 self::entry_content($doc, $as_object, $repeated_item, $owner, "", "", false);
1567 $author = self::add_author($doc, $contact);
1568 $as_object->appendChild($author);
1570 $as_object2 = $doc->createElement("activity:object");
1572 xml::add_element($doc, $as_object2, "activity:object-type", self::construct_objecttype($repeated_item));
1574 $title = sprintf("New comment by %s", $contact["nick"]);
1576 self::entry_content($doc, $as_object2, $repeated_item, $owner, $title);
1578 $as_object->appendChild($as_object2);
1580 self::entry_footer($doc, $as_object, $item, $owner, false);
1582 $source = self::source_entry($doc, $contact);
1584 $as_object->appendChild($source);
1586 $entry->appendChild($as_object);
1588 self::entry_footer($doc, $entry, $item, $owner);
1594 * @brief Adds an entry element with a "like"
1596 * @param object $doc XML document
1597 * @param array $item Data of the item that is to be posted
1598 * @param array $owner Contact data of the poster
1599 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1601 * @return object Entry element with "like"
1603 private static function like_entry($doc, $item, $owner, $toplevel) {
1605 if (($item["id"] != $item["parent"]) && (normalise_link($item["author-link"]) != normalise_link($owner["url"]))) {
1606 logger("OStatus entry is from author ".$owner["url"]." - not from ".$item["author-link"].". Quitting.", LOGGER_DEBUG);
1609 $title = self::entry_header($doc, $entry, $owner, $toplevel);
1611 $verb = NAMESPACE_ACTIVITY_SCHEMA."favorite";
1612 self::entry_content($doc, $entry, $item, $owner, "Favorite", $verb, false);
1614 $as_object = $doc->createElement("activity:object");
1616 $parent = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d",
1617 dbesc($item["thr-parent"]), intval($item["uid"]));
1618 $parent_item = (($item['thr-parent']) ? $item['thr-parent'] : $item['parent-uri']);
1620 xml::add_element($doc, $as_object, "activity:object-type", self::construct_objecttype($parent[0]));
1622 self::entry_content($doc, $as_object, $parent[0], $owner, "New entry");
1624 $entry->appendChild($as_object);
1626 self::entry_footer($doc, $entry, $item, $owner);
1632 * @brief Adds the person object element to the XML document
1634 * @param object $doc XML document
1635 * @param array $owner Contact data of the poster
1636 * @param array $contact Contact data of the target
1638 * @return object author element
1640 private static function add_person_object($doc, $owner, $contact) {
1642 $object = $doc->createElement("activity:object");
1643 xml::add_element($doc, $object, "activity:object-type", ACTIVITY_OBJ_PERSON);
1645 if ($contact['network'] == NETWORK_PHANTOM) {
1646 xml::add_element($doc, $object, "id", $contact['url']);
1650 xml::add_element($doc, $object, "id", $contact["alias"]);
1651 xml::add_element($doc, $object, "title", $contact["nick"]);
1653 $attributes = array("rel" => "alternate", "type" => "text/html", "href" => $contact["url"]);
1654 xml::add_element($doc, $object, "link", "", $attributes);
1656 $attributes = array(
1658 "type" => "image/jpeg", // To-Do?
1659 "media:width" => 175,
1660 "media:height" => 175,
1661 "href" => $contact["photo"]);
1662 xml::add_element($doc, $object, "link", "", $attributes);
1664 xml::add_element($doc, $object, "poco:preferredUsername", $contact["nick"]);
1665 xml::add_element($doc, $object, "poco:displayName", $contact["name"]);
1667 if (trim($contact["location"]) != "") {
1668 $element = $doc->createElement("poco:address");
1669 xml::add_element($doc, $element, "poco:formatted", $contact["location"]);
1670 $object->appendChild($element);
1677 * @brief Adds a follow/unfollow entry element
1679 * @param object $doc XML document
1680 * @param array $item Data of the follow/unfollow message
1681 * @param array $owner Contact data of the poster
1682 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1684 * @return object Entry element
1686 private static function follow_entry($doc, $item, $owner, $toplevel) {
1688 $item["id"] = $item["parent"] = 0;
1689 $item["created"] = $item["edited"] = date("c");
1690 $item["private"] = true;
1692 $contact = Probe::uri($item['follow']);
1694 if ($contact['alias'] == '') {
1695 $contact['alias'] = $contact["url"];
1697 $item['follow'] = $contact['alias'];
1700 $r = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `nurl` = '%s'",
1701 intval($owner['uid']), dbesc(normalise_link($contact["url"])));
1703 if (dbm::is_result($r)) {
1704 $connect_id = $r[0]['id'];
1709 if ($item['verb'] == ACTIVITY_FOLLOW) {
1710 $message = t('%s is now following %s.');
1711 $title = t('following');
1712 $action = "subscription";
1714 $message = t('%s stopped following %s.');
1715 $title = t('stopped following');
1716 $action = "unfollow";
1719 $item["uri"] = $item['parent-uri'] = $item['thr-parent'] =
1720 'tag:'.get_app()->get_hostname().
1721 ','.date('Y-m-d').':'.$action.':'.$owner['uid'].
1722 ':person:'.$connect_id.':'.$item['created'];
1724 $item["body"] = sprintf($message, $owner["nick"], $contact["nick"]);
1726 self::entry_header($doc, $entry, $owner, $toplevel);
1728 self::entry_content($doc, $entry, $item, $owner, $title);
1730 $object = self::add_person_object($doc, $owner, $contact);
1731 $entry->appendChild($object);
1733 self::entry_footer($doc, $entry, $item, $owner);
1739 * @brief Adds a regular entry element
1741 * @param object $doc XML document
1742 * @param array $item Data of the item that is to be posted
1743 * @param array $owner Contact data of the poster
1744 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1746 * @return object Entry element
1748 private static function note_entry($doc, $item, $owner, $toplevel) {
1750 if (($item["id"] != $item["parent"]) && (normalise_link($item["author-link"]) != normalise_link($owner["url"]))) {
1751 logger("OStatus entry is from author ".$owner["url"]." - not from ".$item["author-link"].". Quitting.", LOGGER_DEBUG);
1754 $title = self::entry_header($doc, $entry, $owner, $toplevel);
1756 xml::add_element($doc, $entry, "activity:object-type", ACTIVITY_OBJ_NOTE);
1758 self::entry_content($doc, $entry, $item, $owner, $title);
1760 self::entry_footer($doc, $entry, $item, $owner);
1766 * @brief Adds a header element to the XML document
1768 * @param object $doc XML document
1769 * @param object $entry The entry element where the elements are added
1770 * @param array $owner Contact data of the poster
1771 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1773 * @return string The title for the element
1775 private static function entry_header($doc, &$entry, $owner, $toplevel) {
1776 /// @todo Check if this title stuff is really needed (I guess not)
1778 $entry = $doc->createElement("entry");
1779 $title = sprintf("New note by %s", $owner["nick"]);
1781 $entry = $doc->createElementNS(NAMESPACE_ATOM1, "entry");
1783 $entry->setAttribute("xmlns:thr", NAMESPACE_THREAD);
1784 $entry->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
1785 $entry->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
1786 $entry->setAttribute("xmlns:media", NAMESPACE_MEDIA);
1787 $entry->setAttribute("xmlns:poco", NAMESPACE_POCO);
1788 $entry->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
1789 $entry->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
1790 $entry->setAttribute("xmlns:mastodon", NAMESPACE_MASTODON);
1792 $author = self::add_author($doc, $owner);
1793 $entry->appendChild($author);
1795 $title = sprintf("New comment by %s", $owner["nick"]);
1801 * @brief Adds elements to the XML document
1803 * @param object $doc XML document
1804 * @param object $entry Entry element where the content is added
1805 * @param array $item Data of the item that is to be posted
1806 * @param array $owner Contact data of the poster
1807 * @param string $title Title for the post
1808 * @param string $verb The activity verb
1809 * @param bool $complete Add the "status_net" element?
1811 private static function entry_content($doc, $entry, $item, $owner, $title, $verb = "", $complete = true) {
1814 $verb = self::construct_verb($item);
1816 xml::add_element($doc, $entry, "id", $item["uri"]);
1817 xml::add_element($doc, $entry, "title", $title);
1819 $body = self::format_picture_post($item['body']);
1821 if ($item['title'] != "")
1822 $body = "[b]".$item['title']."[/b]\n\n".$body;
1824 $body = bbcode($body, false, false, 7);
1826 xml::add_element($doc, $entry, "content", $body, array("type" => "html"));
1828 xml::add_element($doc, $entry, "link", "", array("rel" => "alternate", "type" => "text/html",
1829 "href" => System::baseUrl()."/display/".$item["guid"]));
1831 if ($complete && ($item["id"] > 0))
1832 xml::add_element($doc, $entry, "status_net", "", array("notice_id" => $item["id"]));
1834 xml::add_element($doc, $entry, "activity:verb", $verb);
1836 xml::add_element($doc, $entry, "published", datetime_convert("UTC","UTC",$item["created"]."+00:00",ATOM_TIME));
1837 xml::add_element($doc, $entry, "updated", datetime_convert("UTC","UTC",$item["edited"]."+00:00",ATOM_TIME));
1841 * @brief Adds the elements at the foot of an entry to the XML document
1843 * @param object $doc XML document
1844 * @param object $entry The entry element where the elements are added
1845 * @param array $item Data of the item that is to be posted
1846 * @param array $owner Contact data of the poster
1849 private static function entry_footer($doc, $entry, $item, $owner, $complete = true) {
1851 $mentioned = array();
1853 if (($item['parent'] != $item['id']) || ($item['parent-uri'] !== $item['uri']) || (($item['thr-parent'] !== '') && ($item['thr-parent'] !== $item['uri']))) {
1854 $parent = q("SELECT `guid`, `author-link`, `owner-link` FROM `item` WHERE `id` = %d", intval($item["parent"]));
1855 $parent_item = (($item['thr-parent']) ? $item['thr-parent'] : $item['parent-uri']);
1857 $thrparent = q("SELECT `guid`, `author-link`, `owner-link`, `plink` FROM `item` WHERE `uid` = %d AND `uri` = '%s'",
1858 intval($owner["uid"]),
1859 dbesc($parent_item));
1861 $mentioned[$thrparent[0]["author-link"]] = $thrparent[0]["author-link"];
1862 $mentioned[$thrparent[0]["owner-link"]] = $thrparent[0]["owner-link"];
1863 $parent_plink = $thrparent[0]["plink"];
1865 $mentioned[$parent[0]["author-link"]] = $parent[0]["author-link"];
1866 $mentioned[$parent[0]["owner-link"]] = $parent[0]["owner-link"];
1867 $parent_plink = System::baseUrl()."/display/".$parent[0]["guid"];
1870 $attributes = array(
1871 "ref" => $parent_item,
1872 "href" => $parent_plink);
1873 xml::add_element($doc, $entry, "thr:in-reply-to", "", $attributes);
1875 $attributes = array(
1877 "href" => $parent_plink);
1878 xml::add_element($doc, $entry, "link", "", $attributes);
1881 if (intval($item["parent"]) > 0) {
1882 $conversation_href = System::baseUrl()."/display/".$owner["nick"]."/".$item["parent"];
1883 $conversation_uri = $conversation_href;
1885 if (isset($parent_item)) {
1886 $r = dba::fetch_first("SELECT `conversation-uri`, `conversation-href` FROM `conversation` WHERE `item-uri` = ?", $parent_item);
1887 if (dbm::is_result($r)) {
1888 if ($r['conversation-uri'] != '') {
1889 $conversation_uri = $r['conversation-uri'];
1891 if ($r['conversation-href'] != '') {
1892 $conversation_href = $r['conversation-href'];
1897 xml::add_element($doc, $entry, "link", "", array("rel" => "ostatus:conversation", "href" => $conversation_href));
1899 $attributes = array(
1900 "href" => $conversation_href,
1901 "local_id" => $item["parent"],
1902 "ref" => $conversation_uri);
1904 xml::add_element($doc, $entry, "ostatus:conversation", $conversation_uri, $attributes);
1907 $tags = item_getfeedtags($item);
1910 foreach ($tags as $t)
1912 $mentioned[$t[1]] = $t[1];
1914 // Make sure that mentions are accepted (GNU Social has problems with mixing HTTP and HTTPS)
1915 $newmentions = array();
1916 foreach ($mentioned AS $mention) {
1917 $newmentions[str_replace("http://", "https://", $mention)] = str_replace("http://", "https://", $mention);
1918 $newmentions[str_replace("https://", "http://", $mention)] = str_replace("https://", "http://", $mention);
1920 $mentioned = $newmentions;
1922 foreach ($mentioned AS $mention) {
1923 $r = q("SELECT `forum`, `prv` FROM `contact` WHERE `uid` = %d AND `nurl` = '%s'",
1924 intval($owner["uid"]),
1925 dbesc(normalise_link($mention)));
1926 if ($r[0]["forum"] || $r[0]["prv"])
1927 xml::add_element($doc, $entry, "link", "", array("rel" => "mentioned",
1928 "ostatus:object-type" => ACTIVITY_OBJ_GROUP,
1929 "href" => $mention));
1931 xml::add_element($doc, $entry, "link", "", array("rel" => "mentioned",
1932 "ostatus:object-type" => ACTIVITY_OBJ_PERSON,
1933 "href" => $mention));
1936 if (!$item["private"]) {
1937 xml::add_element($doc, $entry, "link", "", array("rel" => "ostatus:attention",
1938 "href" => "http://activityschema.org/collection/public"));
1939 xml::add_element($doc, $entry, "link", "", array("rel" => "mentioned",
1940 "ostatus:object-type" => "http://activitystrea.ms/schema/1.0/collection",
1941 "href" => "http://activityschema.org/collection/public"));
1942 xml::add_element($doc, $entry, "mastodon:scope", "public");
1946 foreach ($tags as $t)
1948 xml::add_element($doc, $entry, "category", "", array("term" => $t[2]));
1950 self::get_attachment($doc, $entry, $item);
1952 if ($complete && ($item["id"] > 0)) {
1953 $app = $item["app"];
1957 $attributes = array("local_id" => $item["id"], "source" => $app);
1959 if (isset($parent["id"]))
1960 $attributes["repeat_of"] = $parent["id"];
1962 if ($item["coord"] != "")
1963 xml::add_element($doc, $entry, "georss:point", $item["coord"]);
1965 xml::add_element($doc, $entry, "statusnet:notice_info", "", $attributes);
1970 * @brief Creates the XML feed for a given nickname
1972 * @param App $a The application class
1973 * @param string $owner_nick Nickname of the feed owner
1974 * @param string $last_update Date of the last update
1975 * @param integer $max_items Number of maximum items to fetch
1977 * @return string XML feed
1979 public static function feed(App $a, $owner_nick, &$last_update, $max_items = 300) {
1980 $stamp = microtime(true);
1982 $cachekey = "ostatus:feed:".$owner_nick.":".$last_update;
1984 $previous_created = $last_update;
1986 $result = Cache::get($cachekey);
1987 if (!is_null($result)) {
1988 logger('Feed duration: '.number_format(microtime(true) - $stamp, 3).' - '.$owner_nick.' - '.$previous_created.' (cached)', LOGGER_DEBUG);
1989 $last_update = $result['last_update'];
1990 return $result['feed'];
1993 $r = q("SELECT `contact`.*, `user`.`nickname`, `user`.`timezone`, `user`.`page-flags`
1994 FROM `contact` INNER JOIN `user` ON `user`.`uid` = `contact`.`uid`
1995 WHERE `contact`.`self` AND `user`.`nickname` = '%s' LIMIT 1",
1996 dbesc($owner_nick));
1997 if (!dbm::is_result($r)) {
2003 if (!strlen($last_update)) {
2004 $last_update = 'now -30 days';
2007 $check_date = datetime_convert('UTC','UTC',$last_update,'Y-m-d H:i:s');
2008 $authorid = get_contact($owner["url"], 0);
2010 $items = q("SELECT `item`.*, `item`.`id` AS `item_id` FROM `item` USE INDEX (`uid_contactid_created`)
2011 STRAIGHT_JOIN `thread` ON `thread`.`iid` = `item`.`parent`
2012 WHERE `item`.`uid` = %d AND `item`.`contact-id` = %d AND
2013 `item`.`author-id` = %d AND `item`.`created` > '%s' AND
2014 NOT `item`.`deleted` AND NOT `item`.`private` AND
2015 `thread`.`network` IN ('%s', '%s')
2016 ORDER BY `item`.`created` DESC LIMIT %d",
2017 intval($owner["uid"]), intval($owner["id"]),
2018 intval($authorid), dbesc($check_date),
2019 dbesc(NETWORK_OSTATUS), dbesc(NETWORK_DFRN), intval($max_items));
2021 $doc = new DOMDocument('1.0', 'utf-8');
2022 $doc->formatOutput = true;
2024 $root = self::add_header($doc, $owner);
2026 foreach ($items AS $item) {
2027 if (Config::get('system', 'ostatus_debug')) {
2028 $item['body'] .= '🍼';
2030 $entry = self::entry($doc, $item, $owner);
2031 $root->appendChild($entry);
2033 if ($last_update < $item['created']) {
2034 $last_update = $item['created'];
2038 $feeddata = trim($doc->saveXML());
2040 $msg = array('feed' => $feeddata, 'last_update' => $last_update);
2041 Cache::set($cachekey, $msg, CACHE_QUARTER_HOUR);
2043 logger('Feed duration: '.number_format(microtime(true) - $stamp, 3).' - '.$owner_nick.' - '.$previous_created, LOGGER_DEBUG);
2049 * @brief Creates the XML for a salmon message
2051 * @param array $item Data of the item that is to be posted
2052 * @param array $owner Contact data of the poster
2054 * @return string XML for the salmon
2056 public static function salmon($item,$owner) {
2058 $doc = new DOMDocument('1.0', 'utf-8');
2059 $doc->formatOutput = true;
2061 if (Config::get('system', 'ostatus_debug')) {
2062 $item['body'] .= '🐟';
2065 $entry = self::entry($doc, $item, $owner, true);
2067 $doc->appendChild($entry);
2069 return trim($doc->saveXML());