3 * @file include/ostatus.php
7 use Friendica\Core\Cache;
8 use Friendica\Core\System;
9 use Friendica\Core\Config;
10 use Friendica\Database\DBM;
11 use Friendica\Network\Probe;
12 use Friendica\Util\Lock;
13 use Friendica\Util\Xml;
15 require_once 'include/Contact.php';
16 require_once 'include/threads.php';
17 require_once 'include/html2bbcode.php';
18 require_once 'include/bbcode.php';
19 require_once 'include/items.php';
20 require_once 'mod/share.php';
21 require_once 'include/enotify.php';
22 require_once 'include/socgraph.php';
23 require_once 'include/Photo.php';
24 require_once 'include/follow.php';
25 require_once 'include/api.php';
26 require_once 'mod/proxy.php';
29 * @brief This class contain functions for the OStatus protocol
33 private static $itemlist;
34 private static $conv_list = array();
37 * @brief Fetches author data
39 * @param object $xpath The xpath object
40 * @param object $context The xml context of the author details
41 * @param array $importer user record of the importing user
42 * @param array $contact Called by reference, will contain the fetched contact
43 * @param bool $onlyfetch Only fetch the header without updating the contact entries
45 * @return array Array of author related entries for the item
47 private static function fetchauthor($xpath, $context, $importer, &$contact, $onlyfetch)
50 $author["author-link"] = $xpath->evaluate('atom:author/atom:uri/text()', $context)->item(0)->nodeValue;
51 $author["author-name"] = $xpath->evaluate('atom:author/atom:name/text()', $context)->item(0)->nodeValue;
52 $addr = $xpath->evaluate('atom:author/atom:email/text()', $context)->item(0)->nodeValue;
54 $aliaslink = $author["author-link"];
56 $alternate = $xpath->query("atom:author/atom:link[@rel='alternate']", $context)->item(0)->attributes;
57 if (is_object($alternate)) {
58 foreach ($alternate as $attributes) {
59 if (($attributes->name == "href") && ($attributes->textContent != "")) {
60 $author["author-link"] = $attributes->textContent;
64 $author["contact-id"] = $contact["id"];
68 if ($aliaslink != '') {
69 $condition = array("`uid` = ? AND `alias` = ? AND `network` != ?",
70 $importer["uid"], $aliaslink, NETWORK_STATUSNET);
71 $r = dba::select('contact', array(), $condition, array('limit' => 1));
73 if (DBM::is_result($r)) {
79 $author["contact-id"] = $r["id"];
83 if (!$found && ($author["author-link"] != "")) {
84 if ($aliaslink == "") {
85 $aliaslink = $author["author-link"];
88 $condition = array("`uid` = ? AND `nurl` IN (?, ?) AND `network` != ?", $importer["uid"],
89 normalise_link($author["author-link"]), normalise_link($aliaslink), NETWORK_STATUSNET);
90 $r = dba::select('contact', array(), $condition, array('limit' => 1));
92 if (DBM::is_result($r)) {
98 $author["contact-id"] = $r["id"];
102 if (!$found && ($addr != "")) {
103 $condition = array("`uid` = ? AND `addr` = ? AND `network` != ?",
104 $importer["uid"], $addr, NETWORK_STATUSNET);
105 $r = dba::select('contact', array(), $condition, array('limit' => 1));
107 if (DBM::is_result($r)) {
113 $author["contact-id"] = $r["id"];
117 $avatarlist = array();
118 $avatars = $xpath->query("atom:author/atom:link[@rel='avatar']", $context);
119 foreach ($avatars as $avatar) {
122 foreach ($avatar->attributes as $attributes) {
123 if ($attributes->name == "href") {
124 $href = $attributes->textContent;
126 if ($attributes->name == "width") {
127 $width = $attributes->textContent;
131 $avatarlist[$width] = $href;
134 if (count($avatarlist) > 0) {
136 $author["author-avatar"] = Probe::fixAvatar(current($avatarlist), $author["author-link"]);
139 $displayname = $xpath->evaluate('atom:author/poco:displayName/text()', $context)->item(0)->nodeValue;
140 if ($displayname != "") {
141 $author["author-name"] = $displayname;
144 $author["owner-name"] = $author["author-name"];
145 $author["owner-link"] = $author["author-link"];
146 $author["owner-avatar"] = $author["author-avatar"];
148 // Only update the contacts if it is an OStatus contact
149 if ($r && ($r['id'] > 0) && !$onlyfetch && ($contact["network"] == NETWORK_OSTATUS)) {
150 // This contact is vital, so we awake it from the dead
151 unmark_for_death($contact);
153 // Update contact data
156 unset($current['name-date']);
158 // This query doesn't seem to work
159 // $value = $xpath->query("atom:link[@rel='salmon']", $context)->item(0)->nodeValue;
161 // $contact["notify"] = $value;
163 // This query doesn't seem to work as well - I hate these queries
164 // $value = $xpath->query("atom:link[@rel='self' and @type='application/atom+xml']", $context)->item(0)->nodeValue;
166 // $contact["poll"] = $value;
168 $contact['url'] = $author["author-link"];
169 $contact['nurl'] = normalise_link($contact['url']);
171 $value = $xpath->evaluate('atom:author/atom:uri/text()', $context)->item(0)->nodeValue;
173 $contact["alias"] = $value;
176 $value = $xpath->evaluate('atom:author/poco:displayName/text()', $context)->item(0)->nodeValue;
178 $contact["name"] = $value;
181 $value = $xpath->evaluate('atom:author/poco:preferredUsername/text()', $context)->item(0)->nodeValue;
183 $contact["nick"] = $value;
186 $value = $xpath->evaluate('atom:author/poco:note/text()', $context)->item(0)->nodeValue;
188 $contact["about"] = html2bbcode($value);
191 $value = $xpath->evaluate('atom:author/poco:address/poco:formatted/text()', $context)->item(0)->nodeValue;
193 $contact["location"] = $value;
196 $contact['name-date'] = datetime_convert();
198 dba::update('contact', $contact, array('id' => $contact["id"]), $current);
200 if (!empty($author["author-avatar"]) && ($author["author-avatar"] != $current['avatar'])) {
201 logger("Update profile picture for contact ".$contact["id"], LOGGER_DEBUG);
202 update_contact_avatar($author["author-avatar"], $importer["uid"], $contact["id"]);
205 // Ensure that we are having this contact (with uid=0)
206 $cid = get_contact($aliaslink, 0);
209 $fields = array('url', 'nurl', 'name', 'nick', 'alias', 'about', 'location');
210 $old_contact = dba::select('contact', $fields, array('id' => $cid), array('limit' => 1));
212 // Update it with the current values
213 $fields = array('url' => $author["author-link"], 'name' => $contact["name"],
214 'nurl' => normalise_link($author["author-link"]),
215 'nick' => $contact["nick"], 'alias' => $contact["alias"],
216 'about' => $contact["about"], 'location' => $contact["location"],
217 'success_update' => datetime_convert(), 'last-update' => datetime_convert());
219 dba::update('contact', $fields, array('id' => $cid), $old_contact);
222 update_contact_avatar($author["author-avatar"], 0, $cid);
225 $contact["generation"] = 2;
226 $contact["hide"] = false; // OStatus contacts are never hidden
227 $contact["photo"] = $author["author-avatar"];
228 $gcid = update_gcontact($contact);
230 link_gcontact($gcid, $contact["uid"], $contact["id"]);
237 * @brief Fetches author data from a given XML string
239 * @param string $xml The XML
240 * @param array $importer user record of the importing user
242 * @return array Array of author related entries for the item
244 public static function salmon_author($xml, $importer)
250 $doc = new DOMDocument();
251 @$doc->loadXML($xml);
253 $xpath = new DomXPath($doc);
254 $xpath->registerNamespace('atom', NAMESPACE_ATOM1);
255 $xpath->registerNamespace('thr', NAMESPACE_THREAD);
256 $xpath->registerNamespace('georss', NAMESPACE_GEORSS);
257 $xpath->registerNamespace('activity', NAMESPACE_ACTIVITY);
258 $xpath->registerNamespace('media', NAMESPACE_MEDIA);
259 $xpath->registerNamespace('poco', NAMESPACE_POCO);
260 $xpath->registerNamespace('ostatus', NAMESPACE_OSTATUS);
261 $xpath->registerNamespace('statusnet', NAMESPACE_STATUSNET);
263 $entries = $xpath->query('/atom:entry');
265 foreach ($entries as $entry) {
267 $author = self::fetchauthor($xpath, $entry, $importer, $contact, true);
273 * @brief Read attributes from element
275 * @param object $element Element object
277 * @return array attributes
279 private static function read_attributes($element)
281 $attribute = array();
283 foreach ($element->attributes as $attributes) {
284 $attribute[$attributes->name] = $attributes->textContent;
291 * @brief Imports an XML string containing OStatus elements
293 * @param string $xml The XML
294 * @param array $importer user record of the importing user
295 * @param array $contact contact
296 * @param string $hub Called by reference, returns the fetched hub data
298 public static function import($xml, $importer, &$contact, &$hub)
300 self::process($xml, $importer, $contact, $hub);
304 * @brief Internal feed processing
306 * @param string $xml The XML
307 * @param array $importer user record of the importing user
308 * @param array $contact
309 * @param string $hub Called by reference, returns the fetched hub data
310 * @param boolean $stored Is the post fresh imported or from the database?
311 * @param boolean $initialize Is it the leading post so that data has to be initialized?
313 * @return boolean Could the XML be processed?
315 private static function process($xml, $importer, &$contact, &$hub, $stored = false, $initialize = true)
318 self::$itemlist = array();
319 self::$conv_list = array();
322 logger("Import OStatus message", LOGGER_DEBUG);
327 $doc = new DOMDocument();
328 @$doc->loadXML($xml);
330 $xpath = new DomXPath($doc);
331 $xpath->registerNamespace('atom', NAMESPACE_ATOM1);
332 $xpath->registerNamespace('thr', NAMESPACE_THREAD);
333 $xpath->registerNamespace('georss', NAMESPACE_GEORSS);
334 $xpath->registerNamespace('activity', NAMESPACE_ACTIVITY);
335 $xpath->registerNamespace('media', NAMESPACE_MEDIA);
336 $xpath->registerNamespace('poco', NAMESPACE_POCO);
337 $xpath->registerNamespace('ostatus', NAMESPACE_OSTATUS);
338 $xpath->registerNamespace('statusnet', NAMESPACE_STATUSNET);
341 $hub_attributes = $xpath->query("/atom:feed/atom:link[@rel='hub']")->item(0)->attributes;
342 if (is_object($hub_attributes)) {
343 foreach ($hub_attributes as $hub_attribute) {
344 if ($hub_attribute->name == "href") {
345 $hub = $hub_attribute->textContent;
346 logger("Found hub ".$hub, LOGGER_DEBUG);
352 $header["uid"] = $importer["uid"];
353 $header["network"] = NETWORK_OSTATUS;
354 $header["type"] = "remote";
356 $header["origin"] = 0;
357 $header["gravity"] = GRAVITY_PARENT;
359 $first_child = $doc->firstChild->tagName;
361 if ($first_child == "feed") {
362 $entries = $xpath->query('/atom:feed/atom:entry');
364 $entries = $xpath->query('/atom:entry');
367 if ($entries->length == 1) {
368 // We reformat the XML to make it better readable
369 $doc2 = new DOMDocument();
370 $doc2->loadXML($xml);
371 $doc2->preserveWhiteSpace = false;
372 $doc2->formatOutput = true;
373 $xml2 = $doc2->saveXML();
375 $header["protocol"] = PROTOCOL_OSTATUS_SALMON;
376 $header["source"] = $xml2;
377 } elseif (!$initialize) {
381 // Fetch the first author
382 $authordata = $xpath->query('//author')->item(0);
383 $author = self::fetchauthor($xpath, $authordata, $importer, $contact, $stored);
385 $entry = $xpath->query('/atom:entry');
387 // Reverse the order of the entries
388 $entrylist = array();
390 foreach ($entries as $entry) {
391 $entrylist[] = $entry;
394 foreach (array_reverse($entrylist) as $entry) {
396 $authorelement = $xpath->query('/atom:entry/atom:author', $entry);
398 if ($authorelement->length == 0) {
399 $authorelement = $xpath->query('atom:author', $entry);
402 if ($authorelement->length > 0) {
403 $author = self::fetchauthor($xpath, $entry, $importer, $contact, $stored);
406 $value = $xpath->evaluate('atom:author/poco:preferredUsername/text()', $entry)->item(0)->nodeValue;
410 $nickname = $author["author-name"];
413 $item = array_merge($header, $author);
415 $item["uri"] = $xpath->query('atom:id/text()', $entry)->item(0)->nodeValue;
417 $item["verb"] = $xpath->query('activity:verb/text()', $entry)->item(0)->nodeValue;
420 if (in_array($item["verb"], array('qvitter-delete-notice', ACTIVITY_DELETE, 'delete'))) {
421 self::deleteNotice($item);
425 if (in_array($item["verb"], array(NAMESPACE_OSTATUS."/unfavorite", ACTIVITY_UNFAVORITE))) {
426 // Ignore "Unfavorite" message
427 logger("Ignore unfavorite message ".print_r($item, true), LOGGER_DEBUG);
431 // Deletions come with the same uri, so we check for duplicates after processing deletions
432 if (dba::exists('item', array('uid' => $importer["uid"], 'uri' => $item["uri"]))) {
433 logger('Post with URI '.$item["uri"].' already existed for user '.$importer["uid"].'.', LOGGER_DEBUG);
436 logger('Processing post with URI '.$item["uri"].' for user '.$importer["uid"].'.', LOGGER_DEBUG);
439 if ($item["verb"] == ACTIVITY_JOIN) {
440 // ignore "Join" messages
441 logger("Ignore join message ".print_r($item, true), LOGGER_DEBUG);
445 if ($item["verb"] == "http://mastodon.social/schema/1.0/block") {
446 // ignore mastodon "block" messages
447 logger("Ignore block message ".print_r($item, true), LOGGER_DEBUG);
451 if ($item["verb"] == ACTIVITY_FOLLOW) {
452 new_follower($importer, $contact, $item, $nickname);
456 if ($item["verb"] == NAMESPACE_OSTATUS."/unfollow") {
457 lose_follower($importer, $contact, $item, $dummy);
461 if ($item["verb"] == ACTIVITY_FAVORITE) {
462 $orig_uri = $xpath->query("activity:object/atom:id", $entry)->item(0)->nodeValue;
463 logger("Favorite ".$orig_uri." ".print_r($item, true));
465 $item["verb"] = ACTIVITY_LIKE;
466 $item["parent-uri"] = $orig_uri;
467 $item["gravity"] = GRAVITY_LIKE;
470 // http://activitystrea.ms/schema/1.0/rsvp-yes
471 if (!in_array($item["verb"], array(ACTIVITY_POST, ACTIVITY_LIKE, ACTIVITY_SHARE))) {
472 logger("Unhandled verb ".$item["verb"]." ".print_r($item, true), LOGGER_DEBUG);
475 self::processPost($xpath, $entry, $item, $importer);
477 if ($initialize && (count(self::$itemlist) > 0)) {
478 if (self::$itemlist[0]['uri'] == self::$itemlist[0]['parent-uri']) {
479 // We will import it everytime, when it is started by our contacts
480 $valid = !empty(self::$itemlist[0]['contact-id']);
482 // If not, then it depends on this setting
483 $valid = !Config::get('system', 'ostatus_full_threads');
486 // Never post a thread when the only interaction by our contact was a like
488 $verbs = array(ACTIVITY_POST, ACTIVITY_SHARE);
489 foreach (self::$itemlist as $item) {
490 if (!empty($item['contact-id']) && in_array($item['verb'], $verbs)) {
496 // But we will only import complete threads
497 $valid = dba::exists('item', array('uid' => $importer["uid"], 'uri' => self::$itemlist[0]['parent-uri']));
501 $default_contact = 0;
502 $key = count(self::$itemlist);
503 for ($key = count(self::$itemlist) - 1; $key >= 0; $key--) {
504 if (empty(self::$itemlist[$key]['contact-id'])) {
505 self::$itemlist[$key]['contact-id'] = $default_contact;
507 $default_contact = $item['contact-id'];
510 foreach (self::$itemlist as $item) {
511 $found = dba::exists('item', array('uid' => $importer["uid"], 'uri' => $item["uri"]));
513 logger("Item with uri ".$item["uri"]." for user ".$importer["uid"]." already exists.", LOGGER_DEBUG);
514 } elseif ($item['contact-id'] < 0) {
515 logger("Item with uri ".$item["uri"]." is from a blocked contact.", LOGGER_DEBUG);
517 // We are having duplicated entries. Hopefully this solves it.
518 if (Lock::set('ostatus_process_item_store')) {
519 $ret = item_store($item);
520 Lock::remove('ostatus_process_item_store');
521 logger("Item with uri ".$item["uri"]." for user ".$importer["uid"].' stored. Return value: '.$ret);
523 $ret = item_store($item);
524 logger("We couldn't lock - but tried to store the item anyway. Return value is ".$ret);
529 self::$itemlist = array();
531 logger('Processing done for post with URI '.$item["uri"].' for user '.$importer["uid"].'.', LOGGER_DEBUG);
536 private static function deleteNotice($item)
538 $condition = array('uid' => $item['uid'], 'author-link' => $item['author-link'], 'uri' => $item['uri']);
539 $deleted = dba::select('item', array('id', 'parent-uri'), $condition, array('limit' => 1));
540 if (!DBM::is_result($deleted)) {
541 logger('Item from '.$item['author-link'].' with uri '.$item['uri'].' for user '.$item['uid']." wasn't found. We don't delete it. ");
545 // 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
548 array('deleted' => true, 'title' => '', 'body' => '',
549 'edited' => datetime_convert(), 'changed' => datetime_convert()),
550 array('id' => $deleted["id"])
553 delete_thread($deleted["id"], $deleted["parent-uri"]);
555 logger('Deleted item with uri '.$item['uri'].' for user '.$item['uid']);
559 * @brief Processes the XML for a post
561 * @param object $xpath The xpath object
562 * @param object $entry The xml entry that is processed
563 * @param array $item The item array
564 * @param array $importer user record of the importing user
566 private static function processPost($xpath, $entry, &$item, $importer)
568 $item["body"] = html2bbcode($xpath->query('atom:content/text()', $entry)->item(0)->nodeValue);
569 $item["object-type"] = $xpath->query('activity:object-type/text()', $entry)->item(0)->nodeValue;
570 if (($item["object-type"] == ACTIVITY_OBJ_BOOKMARK) || ($item["object-type"] == ACTIVITY_OBJ_EVENT)) {
571 $item["title"] = $xpath->query('atom:title/text()', $entry)->item(0)->nodeValue;
572 $item["body"] = $xpath->query('atom:summary/text()', $entry)->item(0)->nodeValue;
573 } elseif ($item["object-type"] == ACTIVITY_OBJ_QUESTION) {
574 $item["title"] = $xpath->query('atom:title/text()', $entry)->item(0)->nodeValue;
577 $item["created"] = $xpath->query('atom:published/text()', $entry)->item(0)->nodeValue;
578 $item["edited"] = $xpath->query('atom:updated/text()', $entry)->item(0)->nodeValue;
579 $conversation = $xpath->query('ostatus:conversation/text()', $entry)->item(0)->nodeValue;
580 $item['conversation-uri'] = $conversation;
582 $conv = $xpath->query('ostatus:conversation', $entry);
583 if (is_object($conv->item(0))) {
584 foreach ($conv->item(0)->attributes as $attributes) {
585 if ($attributes->name == "ref") {
586 $item['conversation-uri'] = $attributes->textContent;
588 if ($attributes->name == "href") {
589 $item['conversation-href'] = $attributes->textContent;
596 $inreplyto = $xpath->query('thr:in-reply-to', $entry);
597 if (is_object($inreplyto->item(0))) {
598 foreach ($inreplyto->item(0)->attributes as $attributes) {
599 if ($attributes->name == "ref") {
600 $item["parent-uri"] = $attributes->textContent;
602 if ($attributes->name == "href") {
603 $related = $attributes->textContent;
608 $georsspoint = $xpath->query('georss:point', $entry);
609 if (!empty($georsspoint) && ($georsspoint->length > 0)) {
610 $item["coord"] = $georsspoint->item(0)->nodeValue;
613 $categories = $xpath->query('atom:category', $entry);
615 foreach ($categories as $category) {
616 foreach ($category->attributes as $attributes) {
617 if ($attributes->name == "term") {
618 $term = $attributes->textContent;
619 if (strlen($item["tag"])) {
622 $item["tag"] .= "#[url=".System::baseUrl()."/search?tag=".$term."]".$term."[/url]";
631 $links = $xpath->query('atom:link', $entry);
633 $link_data = self::processLinks($links, $item);
634 $self = $link_data['self'];
635 $add_body = $link_data['add_body'];
640 $notice_info = $xpath->query('statusnet:notice_info', $entry);
641 if ($notice_info && ($notice_info->length > 0)) {
642 foreach ($notice_info->item(0)->attributes as $attributes) {
643 if ($attributes->name == "source") {
644 $item["app"] = strip_tags($attributes->textContent);
646 if ($attributes->name == "repeat_of") {
647 $repeat_of = $attributes->textContent;
651 // Is it a repeated post?
652 if (($repeat_of != "") || ($item["verb"] == ACTIVITY_SHARE)) {
653 $link_data = self::processRepeatedItem($xpath, $entry, $item, $importer);
654 if (!empty($link_data['add_body'])) {
655 $add_body .= $link_data['add_body'];
659 $item["body"] .= $add_body;
661 // Only add additional data when there is no picture in the post
662 if (!strstr($item["body"], '[/img]')) {
663 $item["body"] = add_page_info_to_body($item["body"]);
666 // Mastodon Content Warning
667 if (($item["verb"] == ACTIVITY_POST) && $xpath->evaluate('boolean(atom:summary)', $entry)) {
668 $clear_text = $xpath->query('atom:summary/text()', $entry)->item(0)->nodeValue;
670 $item["body"] = html2bbcode($clear_text) . '[spoiler]' . $item["body"] . '[/spoiler]';
673 if (($self != '') && empty($item['protocol'])) {
674 self::fetchSelf($self, $item);
677 if (!empty($item["conversation-href"])) {
678 self::fetchConversation($item['conversation-href'], $item['conversation-uri']);
681 if (isset($item["parent-uri"]) && ($related != '')) {
682 if (!dba::exists('item', array('uid' => $importer["uid"], 'uri' => $item['parent-uri']))) {
683 self::fetchRelated($related, $item["parent-uri"], $importer);
685 logger('Reply with URI '.$item["uri"].' already existed for user '.$importer["uid"].'.', LOGGER_DEBUG);
688 $item["type"] = 'remote-comment';
689 $item["gravity"] = GRAVITY_COMMENT;
691 $item["parent-uri"] = $item["uri"];
694 if (($item['author-link'] != '') && !empty($item['protocol'])) {
695 $item = store_conversation($item);
698 self::$itemlist[] = $item;
702 * @brief Fetch the conversation for posts
704 * @param string $conversation The link to the conversation
705 * @param string $conversation_uri The conversation in "uri" format
707 private static function fetchConversation($conversation, $conversation_uri)
709 // Ensure that we only store a conversation once in a process
710 if (isset(self::$conv_list[$conversation])) {
714 self::$conv_list[$conversation] = true;
716 $conversation_data = z_fetch_url($conversation, false, $redirects, array('accept_content' => 'application/atom+xml, text/html'));
718 if (!$conversation_data['success']) {
724 if (stristr($conversation_data['header'], 'Content-Type: application/atom+xml')) {
725 $xml = $conversation_data['body'];
729 $doc = new DOMDocument();
730 if (!@$doc->loadHTML($conversation_data['body'])) {
733 $xpath = new DomXPath($doc);
735 $links = $xpath->query('//link');
737 foreach ($links as $link) {
738 $attribute = ostatus::read_attributes($link);
739 if (($attribute['rel'] == 'alternate') && ($attribute['type'] == 'application/atom+xml')) {
740 $file = $attribute['href'];
744 $conversation_atom = z_fetch_url($attribute['href']);
746 if ($conversation_atom['success']) {
747 $xml = $conversation_atom['body'];
757 self::storeConversation($xml, $conversation, $conversation_uri);
761 * @brief Store a feed in several conversation entries
763 * @param string $xml The feed
764 * @param string $conversation conversation
765 * @param string $conversation_uri conversation uri
767 private static function storeConversation($xml, $conversation = '', $conversation_uri = '')
769 $doc = new DOMDocument();
770 @$doc->loadXML($xml);
772 $xpath = new DomXPath($doc);
773 $xpath->registerNamespace('atom', NAMESPACE_ATOM1);
774 $xpath->registerNamespace('thr', NAMESPACE_THREAD);
775 $xpath->registerNamespace('ostatus', NAMESPACE_OSTATUS);
777 $entries = $xpath->query('/atom:feed/atom:entry');
779 // Now store the entries
780 foreach ($entries as $entry) {
781 $doc2 = new DOMDocument();
782 $doc2->preserveWhiteSpace = false;
783 $doc2->formatOutput = true;
785 $conv_data = array();
787 $conv_data['protocol'] = PROTOCOL_SPLITTED_CONV;
788 $conv_data['network'] = NETWORK_OSTATUS;
789 $conv_data['uri'] = $xpath->query('atom:id/text()', $entry)->item(0)->nodeValue;
791 $inreplyto = $xpath->query('thr:in-reply-to', $entry);
792 if (is_object($inreplyto->item(0))) {
793 foreach ($inreplyto->item(0)->attributes as $attributes) {
794 if ($attributes->name == "ref") {
795 $conv_data['reply-to-uri'] = $attributes->textContent;
800 $conv = $xpath->query('ostatus:conversation/text()', $entry)->item(0)->nodeValue;
801 $conv_data['conversation-uri'] = $conv;
803 $conv = $xpath->query('ostatus:conversation', $entry);
804 if (is_object($conv->item(0))) {
805 foreach ($conv->item(0)->attributes as $attributes) {
806 if ($attributes->name == "ref") {
807 $conv_data['conversation-uri'] = $attributes->textContent;
809 if ($attributes->name == "href") {
810 $conv_data['conversation-href'] = $attributes->textContent;
815 if ($conversation != '') {
816 $conv_data['conversation-uri'] = $conversation;
819 if ($conversation_uri != '') {
820 $conv_data['conversation-uri'] = $conversation_uri;
823 $entry = $doc2->importNode($entry, true);
825 $doc2->appendChild($entry);
827 $conv_data['source'] = $doc2->saveXML();
829 $condition = array('item-uri' => $conv_data['uri'],'protocol' => PROTOCOL_OSTATUS_FEED);
830 if (dba::exists('conversation', $condition)) {
831 logger('Delete deprecated entry for URI '.$conv_data['uri'], LOGGER_DEBUG);
832 dba::delete('conversation', array('item-uri' => $conv_data['uri']));
835 logger('Store conversation data for uri '.$conv_data['uri'], LOGGER_DEBUG);
836 store_conversation($conv_data);
841 * @brief Fetch the own post so that it can be stored later
842 * @param array $item The item array
844 * We want to store the original data for later processing.
845 * This function is meant for cases where we process a feed with multiple entries.
846 * In that case we need to fetch the single posts here.
848 * @param string $self The link to the self item
850 private static function fetchSelf($self, &$item)
852 $condition = array('`item-uri` = ? AND `protocol` IN (?, ?)', $self, PROTOCOL_DFRN, PROTOCOL_OSTATUS_SALMON);
853 if (dba::exists('conversation', $condition)) {
854 logger('Conversation '.$item['uri'].' is already stored.', LOGGER_DEBUG);
858 $self_data = z_fetch_url($self);
860 if (!$self_data['success']) {
864 // We reformat the XML to make it better readable
865 $doc = new DOMDocument();
866 $doc->loadXML($self_data['body']);
867 $doc->preserveWhiteSpace = false;
868 $doc->formatOutput = true;
869 $xml = $doc->saveXML();
871 $item["protocol"] = PROTOCOL_OSTATUS_SALMON;
872 $item["source"] = $xml;
874 logger('Conversation '.$item['uri'].' is now fetched.', LOGGER_DEBUG);
878 * @brief Fetch related posts and processes them
880 * @param string $related The link to the related item
881 * @param string $related_uri The related item in "uri" format
882 * @param array $importer user record of the importing user
884 private static function fetchRelated($related, $related_uri, $importer)
886 $condition = array('`item-uri` = ? AND `protocol` IN (?, ?)', $related_uri, PROTOCOL_DFRN, PROTOCOL_OSTATUS_SALMON);
887 $conversation = dba::select('conversation', array('source', 'protocol'), $condition, array('limit' => 1));
888 if (DBM::is_result($conversation)) {
890 $xml = $conversation['source'];
891 if (self::process($xml, $importer, $contact, $hub, $stored, false)) {
892 logger('Got valid cached XML for URI '.$related_uri, LOGGER_DEBUG);
895 if ($conversation['protocol'] == PROTOCOL_OSTATUS_SALMON) {
896 logger('Delete invalid cached XML for URI '.$related_uri, LOGGER_DEBUG);
897 dba::delete('conversation', array('item-uri' => $related_uri));
902 $related_data = z_fetch_url($related, false, $redirects, array('accept_content' => 'application/atom+xml, text/html'));
904 if (!$related_data['success']) {
910 if (stristr($related_data['header'], 'Content-Type: application/atom+xml')) {
911 logger('Directly fetched XML for URI '.$related_uri, LOGGER_DEBUG);
912 $xml = $related_data['body'];
916 $doc = new DOMDocument();
917 if (!@$doc->loadHTML($related_data['body'])) {
920 $xpath = new DomXPath($doc);
924 $links = $xpath->query('//link');
926 foreach ($links as $link) {
927 $attribute = self::read_attributes($link);
928 if (($attribute['rel'] == 'alternate') && ($attribute['type'] == 'application/atom+xml')) {
929 $atom_file = $attribute['href'];
932 if ($atom_file != '') {
933 $related_atom = z_fetch_url($atom_file);
935 if ($related_atom['success']) {
936 logger('Fetched XML for URI '.$related_uri, LOGGER_DEBUG);
937 $xml = $related_atom['body'];
943 // Workaround for older GNU Social servers
944 if (($xml == '') && strstr($related, '/notice/')) {
945 $related_atom = z_fetch_url(str_replace('/notice/', '/api/statuses/show/', $related).'.atom');
947 if ($related_atom['success']) {
948 logger('GNU Social workaround to fetch XML for URI '.$related_uri, LOGGER_DEBUG);
949 $xml = $related_atom['body'];
953 // Even more worse workaround for GNU Social ;-)
955 $related_guess = ostatus::convert_href($related_uri);
956 $related_atom = z_fetch_url(str_replace('/notice/', '/api/statuses/show/', $related_guess).'.atom');
958 if ($related_atom['success']) {
959 logger('GNU Social workaround 2 to fetch XML for URI '.$related_uri, LOGGER_DEBUG);
960 $xml = $related_atom['body'];
964 // Finally we take the data that we fetched from "ostatus:conversation"
966 $condition = array('item-uri' => $related_uri, 'protocol' => PROTOCOL_SPLITTED_CONV);
967 $conversation = dba::select('conversation', array('source'), $condition, array('limit' => 1));
968 if (DBM::is_result($conversation)) {
970 logger('Got cached XML from conversation for URI '.$related_uri, LOGGER_DEBUG);
971 $xml = $conversation['source'];
976 self::process($xml, $importer, $contact, $hub, $stored, false);
978 logger("XML couldn't be fetched for URI: ".$related_uri." - href: ".$related, LOGGER_DEBUG);
984 * @brief Processes the XML for a repeated post
986 * @param object $xpath The xpath object
987 * @param object $entry The xml entry that is processed
988 * @param array $item The item array
989 * @param array $importer user record of the importing user
991 * @return array with data from links
993 private static function processRepeatedItem($xpath, $entry, &$item, $importer)
995 $activityobjects = $xpath->query('activity:object', $entry)->item(0);
997 if (!is_object($activityobjects)) {
1001 $link_data = array();
1003 $orig_uri = $xpath->query('atom:id/text()', $activityobjects)->item(0)->nodeValue;
1005 $links = $xpath->query("atom:link", $activityobjects);
1007 $link_data = self::processLinks($links, $item);
1010 $orig_body = $xpath->query('atom:content/text()', $activityobjects)->item(0)->nodeValue;
1011 $orig_created = $xpath->query('atom:published/text()', $activityobjects)->item(0)->nodeValue;
1012 $orig_edited = $xpath->query('atom:updated/text()', $activityobjects)->item(0)->nodeValue;
1014 $orig_contact = $contact;
1015 $orig_author = self::fetchauthor($xpath, $activityobjects, $importer, $orig_contact, false);
1017 $item["author-name"] = $orig_author["author-name"];
1018 $item["author-link"] = $orig_author["author-link"];
1019 $item["author-avatar"] = $orig_author["author-avatar"];
1021 $item["body"] = html2bbcode($orig_body);
1022 $item["created"] = $orig_created;
1023 $item["edited"] = $orig_edited;
1025 $item["uri"] = $orig_uri;
1027 $item["verb"] = $xpath->query('activity:verb/text()', $activityobjects)->item(0)->nodeValue;
1029 $item["object-type"] = $xpath->query('activity:object-type/text()', $activityobjects)->item(0)->nodeValue;
1031 $inreplyto = $xpath->query('thr:in-reply-to', $activityobjects);
1032 if (is_object($inreplyto->item(0))) {
1033 foreach ($inreplyto->item(0)->attributes as $attributes) {
1034 if ($attributes->name == "ref") {
1035 $item["parent-uri"] = $attributes->textContent;
1044 * @brief Processes links in the XML
1046 * @param object $links The xml data that contain links
1047 * @param array $item The item array
1049 * @return array with data from the links
1051 private static function processLinks($links, &$item)
1053 $link_data = array('add_body' => '', 'self' => '');
1055 foreach ($links as $link) {
1056 $attribute = self::read_attributes($link);
1058 if (($attribute['rel'] != "") && ($attribute['href'] != "")) {
1059 switch ($attribute['rel']) {
1061 $item["plink"] = $attribute['href'];
1062 if (($item["object-type"] == ACTIVITY_OBJ_QUESTION)
1063 || ($item["object-type"] == ACTIVITY_OBJ_EVENT)
1065 $item["body"] .= add_page_info($attribute['href']);
1068 case "ostatus:conversation":
1069 $link_data['conversation'] = $attribute['href'];
1070 $item['conversation-href'] = $link_data['conversation'];
1071 if (!isset($item['conversation-uri'])) {
1072 $item['conversation-uri'] = $item['conversation-href'];
1076 $filetype = strtolower(substr($attribute['type'], 0, strpos($attribute['type'], '/')));
1077 if ($filetype == 'image') {
1078 $link_data['add_body'] .= "\n[img]".$attribute['href'].'[/img]';
1080 if (strlen($item["attach"])) {
1081 $item["attach"] .= ',';
1083 if (!isset($attribute['length'])) {
1084 $attribute['length'] = "0";
1086 $item["attach"] .= '[attach]href="'.$attribute['href'].'" length="'.$attribute['length'].'" type="'.$attribute['type'].'" title="'.$attribute['title'].'"[/attach]';
1090 if ($item["object-type"] != ACTIVITY_OBJ_BOOKMARK) {
1091 if (!isset($item["parent-uri"])) {
1092 $item["parent-uri"] = $attribute['href'];
1094 $link_data['related'] = $attribute['href'];
1096 $item["body"] .= add_page_info($attribute['href']);
1100 if ($item["plink"] == '') {
1101 $item["plink"] = $attribute['href'];
1103 $link_data['self'] = $attribute['href'];
1112 * @brief Create an url out of an uri
1114 * @param string $href URI in the format "parameter1:parameter1:..."
1116 * @return string URL in the format http(s)://....
1118 public static function convert_href($href)
1120 $elements = explode(":", $href);
1122 if ((count($elements) <= 2) || ($elements[0] != "tag")) {
1126 $server = explode(",", $elements[1]);
1127 $conversation = explode("=", $elements[2]);
1129 if ((count($elements) == 4) && ($elements[2] == "post")) {
1130 return "http://".$server[0]."/notice/".$elements[3];
1133 if ((count($conversation) != 2) || ($conversation[1] =="")) {
1136 if ($elements[3] == "objectType=thread") {
1137 return "http://".$server[0]."/conversation/".$conversation[1];
1139 return "http://".$server[0]."/notice/".$conversation[1];
1145 * @brief Checks if the current post is a reshare
1147 * @param array $item The item array of thw post
1149 * @return string The guid if the post is a reshare
1151 private static function get_reshared_guid($item)
1153 $body = trim($item["body"]);
1155 // Skip if it isn't a pure repeated messages
1156 // Does it start with a share?
1157 if (strpos($body, "[share") > 0) {
1161 // Does it end with a share?
1162 if (strlen($body) > (strrpos($body, "[/share]") + 8)) {
1166 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "$1", $body);
1167 // Skip if there is no shared message in there
1168 if ($body == $attributes) {
1173 preg_match("/guid='(.*?)'/ism", $attributes, $matches);
1174 if ($matches[1] != "") {
1175 $guid = $matches[1];
1178 preg_match('/guid="(.*?)"/ism', $attributes, $matches);
1179 if ($matches[1] != "") {
1180 $guid = $matches[1];
1187 * @brief Cleans the body of a post if it contains picture links
1189 * @param string $body The body
1191 * @return string The cleaned body
1193 private static function format_picture_post($body)
1195 $siteinfo = get_attached_data($body);
1197 if (($siteinfo["type"] == "photo")) {
1198 if (isset($siteinfo["preview"])) {
1199 $preview = $siteinfo["preview"];
1201 $preview = $siteinfo["image"];
1204 // Is it a remote picture? Then make a smaller preview here
1205 $preview = proxy_url($preview, false, PROXY_SIZE_SMALL);
1207 // Is it a local picture? Then make it smaller here
1208 $preview = str_replace(array("-0.jpg", "-0.png"), array("-2.jpg", "-2.png"), $preview);
1209 $preview = str_replace(array("-1.jpg", "-1.png"), array("-2.jpg", "-2.png"), $preview);
1211 if (isset($siteinfo["url"])) {
1212 $url = $siteinfo["url"];
1214 $url = $siteinfo["image"];
1217 $body = trim($siteinfo["text"])." [url]".$url."[/url]\n[img]".$preview."[/img]";
1224 * @brief Adds the header elements to the XML document
1226 * @param object $doc XML document
1227 * @param array $owner Contact data of the poster
1229 * @return object header root element
1231 private static function add_header($doc, $owner)
1235 $root = $doc->createElementNS(NAMESPACE_ATOM1, 'feed');
1236 $doc->appendChild($root);
1238 $root->setAttribute("xmlns:thr", NAMESPACE_THREAD);
1239 $root->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
1240 $root->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
1241 $root->setAttribute("xmlns:media", NAMESPACE_MEDIA);
1242 $root->setAttribute("xmlns:poco", NAMESPACE_POCO);
1243 $root->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
1244 $root->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
1245 $root->setAttribute("xmlns:mastodon", NAMESPACE_MASTODON);
1247 $attributes = array("uri" => "https://friendi.ca", "version" => FRIENDICA_VERSION."-".DB_UPDATE_VERSION);
1248 Xml::add_element($doc, $root, "generator", FRIENDICA_PLATFORM, $attributes);
1249 Xml::add_element($doc, $root, "id", System::baseUrl()."/profile/".$owner["nick"]);
1250 Xml::add_element($doc, $root, "title", sprintf("%s timeline", $owner["name"]));
1251 Xml::add_element($doc, $root, "subtitle", sprintf("Updates from %s on %s", $owner["name"], $a->config["sitename"]));
1252 Xml::add_element($doc, $root, "logo", $owner["photo"]);
1253 Xml::add_element($doc, $root, "updated", datetime_convert("UTC", "UTC", "now", ATOM_TIME));
1255 $author = self::add_author($doc, $owner);
1256 $root->appendChild($author);
1258 $attributes = array("href" => $owner["url"], "rel" => "alternate", "type" => "text/html");
1259 Xml::add_element($doc, $root, "link", "", $attributes);
1261 /// @TODO We have to find out what this is
1262 /// $attributes = array("href" => System::baseUrl()."/sup",
1263 /// "rel" => "http://api.friendfeed.com/2008/03#sup",
1264 /// "type" => "application/json");
1265 /// Xml::add_element($doc, $root, "link", "", $attributes);
1267 self::hublinks($doc, $root, $owner["nick"]);
1269 $attributes = array("href" => System::baseUrl()."/salmon/".$owner["nick"], "rel" => "salmon");
1270 Xml::add_element($doc, $root, "link", "", $attributes);
1272 $attributes = array("href" => System::baseUrl()."/salmon/".$owner["nick"], "rel" => "http://salmon-protocol.org/ns/salmon-replies");
1273 Xml::add_element($doc, $root, "link", "", $attributes);
1275 $attributes = array("href" => System::baseUrl()."/salmon/".$owner["nick"], "rel" => "http://salmon-protocol.org/ns/salmon-mention");
1276 Xml::add_element($doc, $root, "link", "", $attributes);
1278 $attributes = array("href" => System::baseUrl()."/api/statuses/user_timeline/".$owner["nick"].".atom",
1279 "rel" => "self", "type" => "application/atom+xml");
1280 Xml::add_element($doc, $root, "link", "", $attributes);
1286 * @brief Add the link to the push hubs to the XML document
1288 * @param object $doc XML document
1289 * @param object $root XML root element where the hub links are added
1290 * @param object $nick nick
1292 public static function hublinks($doc, $root, $nick)
1294 $h = System::baseUrl() . '/pubsubhubbub/'.$nick;
1295 Xml::add_element($doc, $root, "link", "", array("href" => $h, "rel" => "hub"));
1299 * @brief Adds attachement data to the XML document
1301 * @param object $doc XML document
1302 * @param object $root XML root element where the hub links are added
1303 * @param array $item Data of the item that is to be posted
1305 private static function get_attachment($doc, $root, $item)
1308 $siteinfo = get_attached_data($item["body"]);
1310 switch ($siteinfo["type"]) {
1312 $imgdata = get_photo_info($siteinfo["image"]);
1313 $attributes = array("rel" => "enclosure",
1314 "href" => $siteinfo["image"],
1315 "type" => $imgdata["mime"],
1316 "length" => intval($imgdata["size"]));
1317 Xml::add_element($doc, $root, "link", "", $attributes);
1320 $attributes = array("rel" => "enclosure",
1321 "href" => $siteinfo["url"],
1322 "type" => "text/html; charset=UTF-8",
1324 "title" => $siteinfo["title"]);
1325 Xml::add_element($doc, $root, "link", "", $attributes);
1331 if (!Config::get('system', 'ostatus_not_attach_preview') && ($siteinfo["type"] != "photo") && isset($siteinfo["image"])) {
1332 $imgdata = get_photo_info($siteinfo["image"]);
1333 $attributes = array("rel" => "enclosure",
1334 "href" => $siteinfo["image"],
1335 "type" => $imgdata["mime"],
1336 "length" => intval($imgdata["size"]));
1338 Xml::add_element($doc, $root, "link", "", $attributes);
1341 $arr = explode('[/attach],', $item['attach']);
1343 foreach ($arr as $r) {
1345 $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"|', $r, $matches);
1347 $attributes = array("rel" => "enclosure",
1348 "href" => $matches[1],
1349 "type" => $matches[3]);
1351 if (intval($matches[2])) {
1352 $attributes["length"] = intval($matches[2]);
1354 if (trim($matches[4]) != "") {
1355 $attributes["title"] = trim($matches[4]);
1357 Xml::add_element($doc, $root, "link", "", $attributes);
1364 * @brief Adds the author element to the XML document
1366 * @param object $doc XML document
1367 * @param array $owner Contact data of the poster
1369 * @return object author element
1371 private static function add_author($doc, $owner)
1373 $r = q("SELECT `homepage`, `publish` FROM `profile` WHERE `uid` = %d AND `is-default` LIMIT 1", intval($owner["uid"]));
1374 if (DBM::is_result($r)) {
1377 $author = $doc->createElement("author");
1378 Xml::add_element($doc, $author, "id", $owner["url"]);
1379 Xml::add_element($doc, $author, "activity:object-type", ACTIVITY_OBJ_PERSON);
1380 Xml::add_element($doc, $author, "uri", $owner["url"]);
1381 Xml::add_element($doc, $author, "name", $owner["nick"]);
1382 Xml::add_element($doc, $author, "email", $owner["addr"]);
1383 Xml::add_element($doc, $author, "summary", bbcode($owner["about"], false, false, 7));
1385 $attributes = array("rel" => "alternate", "type" => "text/html", "href" => $owner["url"]);
1386 Xml::add_element($doc, $author, "link", "", $attributes);
1388 $attributes = array(
1390 "type" => "image/jpeg", // To-Do?
1391 "media:width" => 175,
1392 "media:height" => 175,
1393 "href" => $owner["photo"]);
1394 Xml::add_element($doc, $author, "link", "", $attributes);
1396 if (isset($owner["thumb"])) {
1397 $attributes = array(
1399 "type" => "image/jpeg", // To-Do?
1400 "media:width" => 80,
1401 "media:height" => 80,
1402 "href" => $owner["thumb"]);
1403 Xml::add_element($doc, $author, "link", "", $attributes);
1406 Xml::add_element($doc, $author, "poco:preferredUsername", $owner["nick"]);
1407 Xml::add_element($doc, $author, "poco:displayName", $owner["name"]);
1408 Xml::add_element($doc, $author, "poco:note", bbcode($owner["about"], false, false, 7));
1410 if (trim($owner["location"]) != "") {
1411 $element = $doc->createElement("poco:address");
1412 Xml::add_element($doc, $element, "poco:formatted", $owner["location"]);
1413 $author->appendChild($element);
1416 if (trim($profile["homepage"]) != "") {
1417 $urls = $doc->createElement("poco:urls");
1418 Xml::add_element($doc, $urls, "poco:type", "homepage");
1419 Xml::add_element($doc, $urls, "poco:value", $profile["homepage"]);
1420 Xml::add_element($doc, $urls, "poco:primary", "true");
1421 $author->appendChild($urls);
1424 if (count($profile)) {
1425 Xml::add_element($doc, $author, "followers", "", array("url" => System::baseUrl()."/viewcontacts/".$owner["nick"]));
1426 Xml::add_element($doc, $author, "statusnet:profile_info", "", array("local_id" => $owner["uid"]));
1429 if ($profile["publish"]) {
1430 Xml::add_element($doc, $author, "mastodon:scope", "public");
1436 * @TODO Picture attachments should look like this:
1437 * <a href="https://status.pirati.ca/attachment/572819" title="https://status.pirati.ca/file/heluecht-20151202T222602-rd3u49p.gif"
1438 * class="attachment thumbnail" id="attachment-572819" rel="nofollow external">https://status.pirati.ca/attachment/572819</a>
1442 * @brief Returns the given activity if present - otherwise returns the "post" activity
1444 * @param array $item Data of the item that is to be posted
1446 * @return string activity
1448 private static function construct_verb($item)
1450 if ($item['verb']) {
1451 return $item['verb'];
1454 return ACTIVITY_POST;
1458 * @brief Returns the given object type if present - otherwise returns the "note" object type
1460 * @param array $item Data of the item that is to be posted
1462 * @return string Object type
1464 private static function construct_objecttype($item)
1466 if (in_array($item['object-type'], array(ACTIVITY_OBJ_NOTE, ACTIVITY_OBJ_COMMENT)))
1467 return $item['object-type'];
1468 return ACTIVITY_OBJ_NOTE;
1472 * @brief Adds an entry element to the XML document
1474 * @param object $doc XML document
1475 * @param array $item Data of the item that is to be posted
1476 * @param array $owner Contact data of the poster
1477 * @param bool $toplevel optional default false
1479 * @return object Entry element
1481 private static function entry($doc, $item, $owner, $toplevel = false)
1483 $repeated_guid = self::get_reshared_guid($item);
1484 if ($repeated_guid != "") {
1485 $xml = self::reshare_entry($doc, $item, $owner, $repeated_guid, $toplevel);
1492 if ($item["verb"] == ACTIVITY_LIKE) {
1493 return self::like_entry($doc, $item, $owner, $toplevel);
1494 } elseif (in_array($item["verb"], array(ACTIVITY_FOLLOW, NAMESPACE_OSTATUS."/unfollow"))) {
1495 return self::follow_entry($doc, $item, $owner, $toplevel);
1497 return self::note_entry($doc, $item, $owner, $toplevel);
1502 * @brief Adds a source entry to the XML document
1504 * @param object $doc XML document
1505 * @param array $contact Array of the contact that is added
1507 * @return object Source element
1509 private static function source_entry($doc, $contact)
1511 $source = $doc->createElement("source");
1512 Xml::add_element($doc, $source, "id", $contact["poll"]);
1513 Xml::add_element($doc, $source, "title", $contact["name"]);
1514 Xml::add_element($doc, $source, "link", "", array("rel" => "alternate", "type" => "text/html", "href" => $contact["alias"]));
1515 Xml::add_element($doc, $source, "link", "", array("rel" => "self", "type" => "application/atom+xml", "href" => $contact["poll"]));
1516 Xml::add_element($doc, $source, "icon", $contact["photo"]);
1517 Xml::add_element($doc, $source, "updated", datetime_convert("UTC", "UTC", $contact["success_update"]."+00:00", ATOM_TIME));
1523 * @brief Fetches contact data from the contact or the gcontact table
1525 * @param string $url URL of the contact
1526 * @param array $owner Contact data of the poster
1528 * @return array Contact array
1530 private static function contact_entry($url, $owner)
1533 "SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` IN (0, %d) ORDER BY `uid` DESC LIMIT 1",
1534 dbesc(normalise_link($url)),
1535 intval($owner["uid"])
1537 if (DBM::is_result($r)) {
1539 $contact["uid"] = -1;
1542 if (!DBM::is_result($r)) {
1544 "SELECT * FROM `gcontact` WHERE `nurl` = '%s' LIMIT 1",
1545 dbesc(normalise_link($url))
1547 if (DBM::is_result($r)) {
1549 $contact["uid"] = -1;
1550 $contact["success_update"] = $contact["updated"];
1554 if (!DBM::is_result($r)) {
1558 if (!isset($contact["poll"])) {
1559 $data = Probe::uri($url);
1560 $contact["poll"] = $data["poll"];
1562 if (!$contact["alias"]) {
1563 $contact["alias"] = $data["alias"];
1567 if (!isset($contact["alias"])) {
1568 $contact["alias"] = $contact["url"];
1575 * @brief Adds an entry element with reshared content
1577 * @param object $doc XML document
1578 * @param array $item Data of the item that is to be posted
1579 * @param array $owner Contact data of the poster
1580 * @param $repeated_guid
1581 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1583 * @return object Entry element
1585 private static function reshare_entry($doc, $item, $owner, $repeated_guid, $toplevel)
1587 if (($item["id"] != $item["parent"]) && (normalise_link($item["author-link"]) != normalise_link($owner["url"]))) {
1588 logger("OStatus entry is from author ".$owner["url"]." - not from ".$item["author-link"].". Quitting.", LOGGER_DEBUG);
1591 $title = self::entry_header($doc, $entry, $owner, $toplevel);
1594 "SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' AND NOT `private` AND `network` IN ('%s', '%s', '%s') LIMIT 1",
1595 intval($owner["uid"]),
1596 dbesc($repeated_guid),
1597 dbesc(NETWORK_DFRN),
1598 dbesc(NETWORK_DIASPORA),
1599 dbesc(NETWORK_OSTATUS)
1601 if (DBM::is_result($r)) {
1602 $repeated_item = $r[0];
1606 $contact = self::contact_entry($repeated_item['author-link'], $owner);
1608 $parent_item = (($item['thr-parent']) ? $item['thr-parent'] : $item['parent-uri']);
1610 $title = $owner["nick"]." repeated a notice by ".$contact["nick"];
1612 self::entry_content($doc, $entry, $item, $owner, $title, ACTIVITY_SHARE, false);
1614 $as_object = $doc->createElement("activity:object");
1616 Xml::add_element($doc, $as_object, "activity:object-type", NAMESPACE_ACTIVITY_SCHEMA."activity");
1618 self::entry_content($doc, $as_object, $repeated_item, $owner, "", "", false);
1620 $author = self::add_author($doc, $contact);
1621 $as_object->appendChild($author);
1623 $as_object2 = $doc->createElement("activity:object");
1625 Xml::add_element($doc, $as_object2, "activity:object-type", self::construct_objecttype($repeated_item));
1627 $title = sprintf("New comment by %s", $contact["nick"]);
1629 self::entry_content($doc, $as_object2, $repeated_item, $owner, $title);
1631 $as_object->appendChild($as_object2);
1633 self::entry_footer($doc, $as_object, $item, $owner, false);
1635 $source = self::source_entry($doc, $contact);
1637 $as_object->appendChild($source);
1639 $entry->appendChild($as_object);
1641 self::entry_footer($doc, $entry, $item, $owner);
1647 * @brief Adds an entry element with a "like"
1649 * @param object $doc XML document
1650 * @param array $item Data of the item that is to be posted
1651 * @param array $owner Contact data of the poster
1652 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1654 * @return object Entry element with "like"
1656 private static function like_entry($doc, $item, $owner, $toplevel)
1658 if (($item["id"] != $item["parent"]) && (normalise_link($item["author-link"]) != normalise_link($owner["url"]))) {
1659 logger("OStatus entry is from author ".$owner["url"]." - not from ".$item["author-link"].". Quitting.", LOGGER_DEBUG);
1662 $title = self::entry_header($doc, $entry, $owner, $toplevel);
1664 $verb = NAMESPACE_ACTIVITY_SCHEMA."favorite";
1665 self::entry_content($doc, $entry, $item, $owner, "Favorite", $verb, false);
1667 $as_object = $doc->createElement("activity:object");
1670 "SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d",
1671 dbesc($item["thr-parent"]),
1672 intval($item["uid"])
1674 $parent_item = (($item['thr-parent']) ? $item['thr-parent'] : $item['parent-uri']);
1676 Xml::add_element($doc, $as_object, "activity:object-type", self::construct_objecttype($parent[0]));
1678 self::entry_content($doc, $as_object, $parent[0], $owner, "New entry");
1680 $entry->appendChild($as_object);
1682 self::entry_footer($doc, $entry, $item, $owner);
1688 * @brief Adds the person object element to the XML document
1690 * @param object $doc XML document
1691 * @param array $owner Contact data of the poster
1692 * @param array $contact Contact data of the target
1694 * @return object author element
1696 private static function add_person_object($doc, $owner, $contact)
1698 $object = $doc->createElement("activity:object");
1699 Xml::add_element($doc, $object, "activity:object-type", ACTIVITY_OBJ_PERSON);
1701 if ($contact['network'] == NETWORK_PHANTOM) {
1702 Xml::add_element($doc, $object, "id", $contact['url']);
1706 Xml::add_element($doc, $object, "id", $contact["alias"]);
1707 Xml::add_element($doc, $object, "title", $contact["nick"]);
1709 $attributes = array("rel" => "alternate", "type" => "text/html", "href" => $contact["url"]);
1710 Xml::add_element($doc, $object, "link", "", $attributes);
1712 $attributes = array(
1714 "type" => "image/jpeg", // To-Do?
1715 "media:width" => 175,
1716 "media:height" => 175,
1717 "href" => $contact["photo"]);
1718 Xml::add_element($doc, $object, "link", "", $attributes);
1720 Xml::add_element($doc, $object, "poco:preferredUsername", $contact["nick"]);
1721 Xml::add_element($doc, $object, "poco:displayName", $contact["name"]);
1723 if (trim($contact["location"]) != "") {
1724 $element = $doc->createElement("poco:address");
1725 Xml::add_element($doc, $element, "poco:formatted", $contact["location"]);
1726 $object->appendChild($element);
1733 * @brief Adds a follow/unfollow entry element
1735 * @param object $doc XML document
1736 * @param array $item Data of the follow/unfollow message
1737 * @param array $owner Contact data of the poster
1738 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1740 * @return object Entry element
1742 private static function follow_entry($doc, $item, $owner, $toplevel)
1744 $item["id"] = $item["parent"] = 0;
1745 $item["created"] = $item["edited"] = date("c");
1746 $item["private"] = true;
1748 $contact = Probe::uri($item['follow']);
1750 if ($contact['alias'] == '') {
1751 $contact['alias'] = $contact["url"];
1753 $item['follow'] = $contact['alias'];
1757 "SELECT `id` FROM `contact` WHERE `uid` = %d AND `nurl` = '%s'",
1758 intval($owner['uid']),
1759 dbesc(normalise_link($contact["url"]))
1762 if (DBM::is_result($r)) {
1763 $connect_id = $r[0]['id'];
1768 if ($item['verb'] == ACTIVITY_FOLLOW) {
1769 $message = t('%s is now following %s.');
1770 $title = t('following');
1771 $action = "subscription";
1773 $message = t('%s stopped following %s.');
1774 $title = t('stopped following');
1775 $action = "unfollow";
1778 $item["uri"] = $item['parent-uri'] = $item['thr-parent']
1779 = 'tag:'.get_app()->get_hostname().
1780 ','.date('Y-m-d').':'.$action.':'.$owner['uid'].
1781 ':person:'.$connect_id.':'.$item['created'];
1783 $item["body"] = sprintf($message, $owner["nick"], $contact["nick"]);
1785 self::entry_header($doc, $entry, $owner, $toplevel);
1787 self::entry_content($doc, $entry, $item, $owner, $title);
1789 $object = self::add_person_object($doc, $owner, $contact);
1790 $entry->appendChild($object);
1792 self::entry_footer($doc, $entry, $item, $owner);
1798 * @brief Adds a regular entry element
1800 * @param object $doc XML document
1801 * @param array $item Data of the item that is to be posted
1802 * @param array $owner Contact data of the poster
1803 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1805 * @return object Entry element
1807 private static function note_entry($doc, $item, $owner, $toplevel)
1809 if (($item["id"] != $item["parent"]) && (normalise_link($item["author-link"]) != normalise_link($owner["url"]))) {
1810 logger("OStatus entry is from author ".$owner["url"]." - not from ".$item["author-link"].". Quitting.", LOGGER_DEBUG);
1813 $title = self::entry_header($doc, $entry, $owner, $toplevel);
1815 Xml::add_element($doc, $entry, "activity:object-type", ACTIVITY_OBJ_NOTE);
1817 self::entry_content($doc, $entry, $item, $owner, $title);
1819 self::entry_footer($doc, $entry, $item, $owner);
1825 * @brief Adds a header element to the XML document
1827 * @param object $doc XML document
1828 * @param object $entry The entry element where the elements are added
1829 * @param array $owner Contact data of the poster
1830 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1832 * @return string The title for the element
1834 private static function entry_header($doc, &$entry, $owner, $toplevel)
1836 /// @todo Check if this title stuff is really needed (I guess not)
1838 $entry = $doc->createElement("entry");
1839 $title = sprintf("New note by %s", $owner["nick"]);
1841 $entry = $doc->createElementNS(NAMESPACE_ATOM1, "entry");
1843 $entry->setAttribute("xmlns:thr", NAMESPACE_THREAD);
1844 $entry->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
1845 $entry->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
1846 $entry->setAttribute("xmlns:media", NAMESPACE_MEDIA);
1847 $entry->setAttribute("xmlns:poco", NAMESPACE_POCO);
1848 $entry->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
1849 $entry->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
1850 $entry->setAttribute("xmlns:mastodon", NAMESPACE_MASTODON);
1852 $author = self::add_author($doc, $owner);
1853 $entry->appendChild($author);
1855 $title = sprintf("New comment by %s", $owner["nick"]);
1861 * @brief Adds elements to the XML document
1863 * @param object $doc XML document
1864 * @param object $entry Entry element where the content is added
1865 * @param array $item Data of the item that is to be posted
1866 * @param array $owner Contact data of the poster
1867 * @param string $title Title for the post
1868 * @param string $verb The activity verb
1869 * @param bool $complete Add the "status_net" element?
1871 private static function entry_content($doc, $entry, $item, $owner, $title, $verb = "", $complete = true)
1874 $verb = self::construct_verb($item);
1877 Xml::add_element($doc, $entry, "id", $item["uri"]);
1878 Xml::add_element($doc, $entry, "title", $title);
1880 $body = self::format_picture_post($item['body']);
1882 if ($item['title'] != "") {
1883 $body = "[b]".$item['title']."[/b]\n\n".$body;
1886 $body = bbcode($body, false, false, 7);
1888 Xml::add_element($doc, $entry, "content", $body, array("type" => "html"));
1890 Xml::add_element($doc, $entry, "link", "", array("rel" => "alternate", "type" => "text/html",
1891 "href" => System::baseUrl()."/display/".$item["guid"])
1894 if ($complete && ($item["id"] > 0)) {
1895 Xml::add_element($doc, $entry, "status_net", "", array("notice_id" => $item["id"]));
1898 Xml::add_element($doc, $entry, "activity:verb", $verb);
1900 Xml::add_element($doc, $entry, "published", datetime_convert("UTC", "UTC", $item["created"]."+00:00", ATOM_TIME));
1901 Xml::add_element($doc, $entry, "updated", datetime_convert("UTC", "UTC", $item["edited"]."+00:00", ATOM_TIME));
1905 * @brief Adds the elements at the foot of an entry to the XML document
1907 * @param object $doc XML document
1908 * @param object $entry The entry element where the elements are added
1909 * @param array $item Data of the item that is to be posted
1910 * @param array $owner Contact data of the poster
1911 * @param bool $complete default true
1913 private static function entry_footer($doc, $entry, $item, $owner, $complete = true)
1915 $mentioned = array();
1917 if (($item['parent'] != $item['id']) || ($item['parent-uri'] !== $item['uri']) || (($item['thr-parent'] !== '') && ($item['thr-parent'] !== $item['uri']))) {
1918 $parent = q("SELECT `guid`, `author-link`, `owner-link` FROM `item` WHERE `id` = %d", intval($item["parent"]));
1919 $parent_item = (($item['thr-parent']) ? $item['thr-parent'] : $item['parent-uri']);
1922 "SELECT `guid`, `author-link`, `owner-link`, `plink` FROM `item` WHERE `uid` = %d AND `uri` = '%s'",
1923 intval($owner["uid"]),
1927 $mentioned[$thrparent[0]["author-link"]] = $thrparent[0]["author-link"];
1928 $mentioned[$thrparent[0]["owner-link"]] = $thrparent[0]["owner-link"];
1929 $parent_plink = $thrparent[0]["plink"];
1931 $mentioned[$parent[0]["author-link"]] = $parent[0]["author-link"];
1932 $mentioned[$parent[0]["owner-link"]] = $parent[0]["owner-link"];
1933 $parent_plink = System::baseUrl()."/display/".$parent[0]["guid"];
1936 $attributes = array(
1937 "ref" => $parent_item,
1938 "href" => $parent_plink);
1939 Xml::add_element($doc, $entry, "thr:in-reply-to", "", $attributes);
1941 $attributes = array(
1943 "href" => $parent_plink);
1944 Xml::add_element($doc, $entry, "link", "", $attributes);
1947 if (intval($item["parent"]) > 0) {
1948 $conversation_href = System::baseUrl()."/display/".$owner["nick"]."/".$item["parent"];
1949 $conversation_uri = $conversation_href;
1951 if (isset($parent_item)) {
1952 $r = dba::fetch_first("SELECT `conversation-uri`, `conversation-href` FROM `conversation` WHERE `item-uri` = ?", $parent_item);
1953 if (DBM::is_result($r)) {
1954 if ($r['conversation-uri'] != '') {
1955 $conversation_uri = $r['conversation-uri'];
1957 if ($r['conversation-href'] != '') {
1958 $conversation_href = $r['conversation-href'];
1963 Xml::add_element($doc, $entry, "link", "", array("rel" => "ostatus:conversation", "href" => $conversation_href));
1965 $attributes = array(
1966 "href" => $conversation_href,
1967 "local_id" => $item["parent"],
1968 "ref" => $conversation_uri);
1970 Xml::add_element($doc, $entry, "ostatus:conversation", $conversation_uri, $attributes);
1973 $tags = item_getfeedtags($item);
1976 foreach ($tags as $t) {
1978 $mentioned[$t[1]] = $t[1];
1983 // Make sure that mentions are accepted (GNU Social has problems with mixing HTTP and HTTPS)
1984 $newmentions = array();
1985 foreach ($mentioned as $mention) {
1986 $newmentions[str_replace("http://", "https://", $mention)] = str_replace("http://", "https://", $mention);
1987 $newmentions[str_replace("https://", "http://", $mention)] = str_replace("https://", "http://", $mention);
1989 $mentioned = $newmentions;
1991 foreach ($mentioned as $mention) {
1993 "SELECT `forum`, `prv` FROM `contact` WHERE `uid` = %d AND `nurl` = '%s'",
1994 intval($owner["uid"]),
1995 dbesc(normalise_link($mention))
1997 if ($r[0]["forum"] || $r[0]["prv"]) {
1998 Xml::add_element($doc, $entry, "link", "",
2000 "rel" => "mentioned",
2001 "ostatus:object-type" => ACTIVITY_OBJ_GROUP,
2005 Xml::add_element($doc, $entry, "link", "",
2007 "rel" => "mentioned",
2008 "ostatus:object-type" => ACTIVITY_OBJ_PERSON,
2014 if (!$item["private"]) {
2015 Xml::add_element($doc, $entry, "link", "", array("rel" => "ostatus:attention",
2016 "href" => "http://activityschema.org/collection/public"));
2017 Xml::add_element($doc, $entry, "link", "", array("rel" => "mentioned",
2018 "ostatus:object-type" => "http://activitystrea.ms/schema/1.0/collection",
2019 "href" => "http://activityschema.org/collection/public"));
2020 Xml::add_element($doc, $entry, "mastodon:scope", "public");
2024 foreach ($tags as $t) {
2026 Xml::add_element($doc, $entry, "category", "", array("term" => $t[2]));
2031 self::get_attachment($doc, $entry, $item);
2033 if ($complete && ($item["id"] > 0)) {
2034 $app = $item["app"];
2039 $attributes = array("local_id" => $item["id"], "source" => $app);
2041 if (isset($parent["id"])) {
2042 $attributes["repeat_of"] = $parent["id"];
2045 if ($item["coord"] != "") {
2046 Xml::add_element($doc, $entry, "georss:point", $item["coord"]);
2049 Xml::add_element($doc, $entry, "statusnet:notice_info", "", $attributes);
2054 * @brief Creates the XML feed for a given nickname
2056 * @param object $a The application class
2057 * @param string $owner_nick Nickname of the feed owner
2058 * @param string $last_update Date of the last update
2059 * @param integer $max_items Number of maximum items to fetch
2061 * @return string XML feed
2063 public static function feed(App $a, $owner_nick, &$last_update, $max_items = 300)
2065 $stamp = microtime(true);
2067 $cachekey = "ostatus:feed:".$owner_nick.":".$last_update;
2069 $previous_created = $last_update;
2071 $result = Cache::get($cachekey);
2072 if (!is_null($result)) {
2073 logger('Feed duration: '.number_format(microtime(true) - $stamp, 3).' - '.$owner_nick.' - '.$previous_created.' (cached)', LOGGER_DEBUG);
2074 $last_update = $result['last_update'];
2075 return $result['feed'];
2079 "SELECT `contact`.*, `user`.`nickname`, `user`.`timezone`, `user`.`page-flags`
2080 FROM `contact` INNER JOIN `user` ON `user`.`uid` = `contact`.`uid`
2081 WHERE `contact`.`self` AND `user`.`nickname` = '%s' LIMIT 1",
2084 if (!DBM::is_result($r)) {
2090 if (!strlen($last_update)) {
2091 $last_update = 'now -30 days';
2094 $check_date = datetime_convert('UTC', 'UTC', $last_update, 'Y-m-d H:i:s');
2095 $authorid = get_contact($owner["url"], 0);
2098 "SELECT `item`.*, `item`.`id` AS `item_id` FROM `item` USE INDEX (`uid_contactid_created`)
2099 STRAIGHT_JOIN `thread` ON `thread`.`iid` = `item`.`parent`
2100 WHERE `item`.`uid` = %d AND `item`.`contact-id` = %d AND
2101 `item`.`author-id` = %d AND `item`.`created` > '%s' AND
2102 NOT `item`.`deleted` AND NOT `item`.`private` AND
2103 `thread`.`network` IN ('%s', '%s')
2104 ORDER BY `item`.`created` DESC LIMIT %d",
2105 intval($owner["uid"]), intval($owner["id"]),
2106 intval($authorid), dbesc($check_date),
2107 dbesc(NETWORK_OSTATUS), dbesc(NETWORK_DFRN), intval($max_items)
2110 $doc = new DOMDocument('1.0', 'utf-8');
2111 $doc->formatOutput = true;
2113 $root = self::add_header($doc, $owner);
2115 foreach ($items as $item) {
2116 if (Config::get('system', 'ostatus_debug')) {
2117 $item['body'] .= '🍼';
2119 $entry = self::entry($doc, $item, $owner);
2120 $root->appendChild($entry);
2122 if ($last_update < $item['created']) {
2123 $last_update = $item['created'];
2127 $feeddata = trim($doc->saveXML());
2129 $msg = array('feed' => $feeddata, 'last_update' => $last_update);
2130 Cache::set($cachekey, $msg, CACHE_QUARTER_HOUR);
2132 logger('Feed duration: '.number_format(microtime(true) - $stamp, 3).' - '.$owner_nick.' - '.$previous_created, LOGGER_DEBUG);
2138 * @brief Creates the XML for a salmon message
2140 * @param array $item Data of the item that is to be posted
2141 * @param array $owner Contact data of the poster
2143 * @return string XML for the salmon
2145 public static function salmon($item, $owner)
2147 $doc = new DOMDocument('1.0', 'utf-8');
2148 $doc->formatOutput = true;
2150 if (Config::get('system', 'ostatus_debug')) {
2151 $item['body'] .= '🐟';
2154 $entry = self::entry($doc, $item, $owner, true);
2156 $doc->appendChild($entry);
2158 return trim($doc->saveXML());