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;
66 $author["contact-id"] = $contact["id"];
70 if ($author["author-link"] != "") {
71 if ($aliaslink == "") {
72 $aliaslink = $author["author-link"];
75 $condition = array("`uid` = ? AND `nurl` IN (?, ?) AND `network` != ?", $importer["uid"],
76 normalise_link($author["author-link"]), normalise_link($aliaslink), NETWORK_STATUSNET);
77 $r = dba::select('contact', array(), $condition, array('limit' => 1));
79 if (dbm::is_result($r)) {
85 $author["contact-id"] = $r["id"];
86 $author["author-link"] = $r["url"];
90 if (!$found && ($addr != "")) {
91 $condition = array("`uid` = ? AND `addr` = ? AND `network` != ?",
92 $importer["uid"], $addr, NETWORK_STATUSNET);
93 $r = dba::select('contact', array(), $condition, array('limit' => 1));
95 if (dbm::is_result($r)) {
100 $author["contact-id"] = $r["id"];
101 $author["author-link"] = $r["url"];
105 $avatarlist = array();
106 $avatars = $xpath->query("atom:author/atom:link[@rel='avatar']", $context);
107 foreach ($avatars AS $avatar) {
110 foreach ($avatar->attributes AS $attributes) {
111 if ($attributes->name == "href") {
112 $href = $attributes->textContent;
114 if ($attributes->name == "width") {
115 $width = $attributes->textContent;
119 $avatarlist[$width] = $href;
122 if (count($avatarlist) > 0) {
124 $author["author-avatar"] = Probe::fixAvatar(current($avatarlist), $author["author-link"]);
127 $displayname = $xpath->evaluate('atom:author/poco:displayName/text()', $context)->item(0)->nodeValue;
128 if ($displayname != "") {
129 $author["author-name"] = $displayname;
132 $author["owner-name"] = $author["author-name"];
133 $author["owner-link"] = $author["author-link"];
134 $author["owner-avatar"] = $author["author-avatar"];
136 // Only update the contacts if it is an OStatus contact
137 if ($r && ($r['id'] > 0) && !$onlyfetch && ($contact["network"] == NETWORK_OSTATUS)) {
139 // Update contact data
141 // This query doesn't seem to work
142 // $value = $xpath->query("atom:link[@rel='salmon']", $context)->item(0)->nodeValue;
144 // $contact["notify"] = $value;
146 // This query doesn't seem to work as well - I hate these queries
147 // $value = $xpath->query("atom:link[@rel='self' and @type='application/atom+xml']", $context)->item(0)->nodeValue;
149 // $contact["poll"] = $value;
151 $value = $xpath->evaluate('atom:author/atom:uri/text()', $context)->item(0)->nodeValue;
153 $contact["alias"] = $value;
155 $value = $xpath->evaluate('atom:author/poco:displayName/text()', $context)->item(0)->nodeValue;
157 $contact["name"] = $value;
159 $value = $xpath->evaluate('atom:author/poco:preferredUsername/text()', $context)->item(0)->nodeValue;
161 $contact["nick"] = $value;
163 $value = $xpath->evaluate('atom:author/poco:note/text()', $context)->item(0)->nodeValue;
165 $contact["about"] = html2bbcode($value);
167 $value = $xpath->evaluate('atom:author/poco:address/poco:formatted/text()', $context)->item(0)->nodeValue;
169 $contact["location"] = $value;
171 if (($contact["name"] != $r[0]["name"]) || ($contact["nick"] != $r[0]["nick"]) || ($contact["about"] != $r[0]["about"]) ||
172 ($contact["alias"] != $r[0]["alias"]) || ($contact["location"] != $r[0]["location"])) {
174 logger("Update contact data for contact ".$contact["id"], LOGGER_DEBUG);
176 q("UPDATE `contact` SET `name` = '%s', `nick` = '%s', `alias` = '%s', `about` = '%s', `location` = '%s', `name-date` = '%s' WHERE `id` = %d",
177 dbesc($contact["name"]), dbesc($contact["nick"]), dbesc($contact["alias"]),
178 dbesc($contact["about"]), dbesc($contact["location"]),
179 dbesc(datetime_convert()), intval($contact["id"]));
182 if (isset($author["author-avatar"]) && ($author["author-avatar"] != $r[0]['avatar'])) {
183 logger("Update profile picture for contact ".$contact["id"], LOGGER_DEBUG);
185 update_contact_avatar($author["author-avatar"], $importer["uid"], $contact["id"]);
188 // Ensure that we are having this contact (with uid=0)
189 $cid = get_contact($author["author-link"], 0);
192 $fields = array('url', 'name', 'nick', 'alias', 'about', 'location');
193 $old_contact = dba::select('contact', $fields, array('id' => $cid), array('limit' => 1));
195 // Update it with the current values
196 $fields = array('url' => $author["author-link"], 'name' => $contact["name"],
197 'nick' => $contact["nick"], 'alias' => $contact["alias"],
198 'about' => $contact["about"], 'location' => $contact["location"],
199 'success_update' => datetime_convert(), 'last-update' => datetime_convert());
201 dba::update('contact', $fields, array('id' => $cid), $old_contact);
204 update_contact_avatar($author["author-avatar"], 0, $cid);
207 $contact["generation"] = 2;
208 $contact["hide"] = false; // OStatus contacts are never hidden
209 $contact["photo"] = $author["author-avatar"];
210 $gcid = update_gcontact($contact);
212 link_gcontact($gcid, $contact["uid"], $contact["id"]);
219 * @brief Fetches author data from a given XML string
221 * @param string $xml The XML
222 * @param array $importer user record of the importing user
224 * @return array Array of author related entries for the item
226 public static function salmon_author($xml, $importer) {
231 $doc = new DOMDocument();
232 @$doc->loadXML($xml);
234 $xpath = new DomXPath($doc);
235 $xpath->registerNamespace('atom', NAMESPACE_ATOM1);
236 $xpath->registerNamespace('thr', NAMESPACE_THREAD);
237 $xpath->registerNamespace('georss', NAMESPACE_GEORSS);
238 $xpath->registerNamespace('activity', NAMESPACE_ACTIVITY);
239 $xpath->registerNamespace('media', NAMESPACE_MEDIA);
240 $xpath->registerNamespace('poco', NAMESPACE_POCO);
241 $xpath->registerNamespace('ostatus', NAMESPACE_OSTATUS);
242 $xpath->registerNamespace('statusnet', NAMESPACE_STATUSNET);
244 $entries = $xpath->query('/atom:entry');
246 foreach ($entries AS $entry) {
248 $author = self::fetchauthor($xpath, $entry, $importer, $contact, true);
254 * @brief Read attributes from element
256 * @param object $element Element object
258 * @return array attributes
260 private static function read_attributes($element) {
261 $attribute = array();
263 foreach ($element->attributes AS $attributes) {
264 $attribute[$attributes->name] = $attributes->textContent;
271 * @brief Imports an XML string containing OStatus elements
273 * @param string $xml The XML
274 * @param array $importer user record of the importing user
275 * @param array $contact
276 * @param string $hub Called by reference, returns the fetched hub data
278 public static function import($xml, $importer, &$contact, &$hub) {
279 self::process($xml, $importer, $contact, $hub);
283 * @brief Internal feed processing
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
289 * @param boolean $stored Is the post fresh imported or from the database?
290 * @param boolean $initialize Is it the leading post so that data has to be initialized?
292 * @return boolean Could the XML be processed?
294 private static function process($xml, $importer, &$contact, &$hub, $stored = false, $initialize = true) {
296 self::$itemlist = array();
297 self::$conv_list = array();
300 logger("Import OStatus message", LOGGER_DEBUG);
305 $doc = new DOMDocument();
306 @$doc->loadXML($xml);
308 $xpath = new DomXPath($doc);
309 $xpath->registerNamespace('atom', NAMESPACE_ATOM1);
310 $xpath->registerNamespace('thr', NAMESPACE_THREAD);
311 $xpath->registerNamespace('georss', NAMESPACE_GEORSS);
312 $xpath->registerNamespace('activity', NAMESPACE_ACTIVITY);
313 $xpath->registerNamespace('media', NAMESPACE_MEDIA);
314 $xpath->registerNamespace('poco', NAMESPACE_POCO);
315 $xpath->registerNamespace('ostatus', NAMESPACE_OSTATUS);
316 $xpath->registerNamespace('statusnet', NAMESPACE_STATUSNET);
319 $hub_attributes = $xpath->query("/atom:feed/atom:link[@rel='hub']")->item(0)->attributes;
320 if (is_object($hub_attributes)) {
321 foreach ($hub_attributes AS $hub_attribute) {
322 if ($hub_attribute->name == "href") {
323 $hub = $hub_attribute->textContent;
324 logger("Found hub ".$hub, LOGGER_DEBUG);
330 $header["uid"] = $importer["uid"];
331 $header["network"] = NETWORK_OSTATUS;
332 $header["type"] = "remote";
334 $header["origin"] = 0;
335 $header["gravity"] = GRAVITY_PARENT;
337 $first_child = $doc->firstChild->tagName;
339 if ($first_child == "feed") {
340 $entries = $xpath->query('/atom:feed/atom:entry');
342 $entries = $xpath->query('/atom:entry');
345 if ($entries->length == 1) {
346 // We reformat the XML to make it better readable
347 $doc2 = new DOMDocument();
348 $doc2->loadXML($xml);
349 $doc2->preserveWhiteSpace = false;
350 $doc2->formatOutput = true;
351 $xml2 = $doc2->saveXML();
353 $header["protocol"] = PROTOCOL_OSTATUS_SALMON;
354 $header["source"] = $xml2;
355 } elseif (!$initialize) {
359 // Fetch the first author
360 $authordata = $xpath->query('//author')->item(0);
361 $author = self::fetchauthor($xpath, $authordata, $importer, $contact, $stored);
363 $entry = $xpath->query('/atom:entry');
365 // Reverse the order of the entries
366 $entrylist = array();
368 foreach ($entries AS $entry) {
369 $entrylist[] = $entry;
372 foreach (array_reverse($entrylist) AS $entry) {
374 $authorelement = $xpath->query('/atom:entry/atom:author', $entry);
376 if ($authorelement->length == 0) {
377 $authorelement = $xpath->query('atom:author', $entry);
380 if ($authorelement->length > 0) {
381 $author = self::fetchauthor($xpath, $entry, $importer, $contact, $stored);
384 $value = $xpath->evaluate('atom:author/poco:preferredUsername/text()', $entry)->item(0)->nodeValue;
388 $nickname = $author["author-name"];
391 $item = array_merge($header, $author);
393 $item["uri"] = $xpath->query('atom:id/text()', $entry)->item(0)->nodeValue;
395 $item["verb"] = $xpath->query('activity:verb/text()', $entry)->item(0)->nodeValue;
398 if (in_array($item["verb"], array('qvitter-delete-notice', ACTIVITY_DELETE, 'delete'))) {
399 self::deleteNotice($item);
403 if (in_array($item["verb"], array(NAMESPACE_OSTATUS."/unfavorite", ACTIVITY_UNFAVORITE))) {
404 // Ignore "Unfavorite" message
405 logger("Ignore unfavorite message ".print_r($item, true), LOGGER_DEBUG);
409 // Deletions come with the same uri, so we check for duplicates after processing deletions
410 if (dba::exists('item', array('uid' => $importer["uid"], 'uri' => $item["uri"]))) {
411 logger('Post with URI '.$item["uri"].' already existed for user '.$importer["uid"].'.', LOGGER_DEBUG);
414 logger('Processing post with URI '.$item["uri"].' for user '.$importer["uid"].'.', LOGGER_DEBUG);
417 if ($item["verb"] == ACTIVITY_JOIN) {
418 // ignore "Join" messages
419 logger("Ignore join message ".print_r($item, true), LOGGER_DEBUG);
423 if ($item["verb"] == "http://mastodon.social/schema/1.0/block") {
424 // ignore mastodon "block" messages
425 logger("Ignore block message ".print_r($item, true), LOGGER_DEBUG);
429 if ($item["verb"] == ACTIVITY_FOLLOW) {
430 new_follower($importer, $contact, $item, $nickname);
434 if ($item["verb"] == NAMESPACE_OSTATUS."/unfollow") {
435 lose_follower($importer, $contact, $item, $dummy);
439 if ($item["verb"] == ACTIVITY_FAVORITE) {
440 $orig_uri = $xpath->query("activity:object/atom:id", $entry)->item(0)->nodeValue;
441 logger("Favorite ".$orig_uri." ".print_r($item, true));
443 $item["verb"] = ACTIVITY_LIKE;
444 $item["parent-uri"] = $orig_uri;
445 $item["gravity"] = GRAVITY_LIKE;
448 // http://activitystrea.ms/schema/1.0/rsvp-yes
449 if (!in_array($item["verb"], array(ACTIVITY_POST, ACTIVITY_LIKE, ACTIVITY_SHARE))) {
450 logger("Unhandled verb ".$item["verb"]." ".print_r($item, true), LOGGER_DEBUG);
453 self::processPost($xpath, $entry, $item, $importer);
455 if ($initialize && (count(self::$itemlist) > 0)) {
456 if (self::$itemlist[0]['uri'] == self::$itemlist[0]['parent-uri']) {
457 // We will import it everytime, when it is started by our contacts
458 $valid = !empty(self::$itemlist[0]['contact-id']);
460 // If not, then it depends on this setting
461 $valid = !Config::get('system','ostatus_full_threads');
464 // Never post a thread when the only interaction by our contact was a like
466 $verbs = array(ACTIVITY_POST, ACTIVITY_SHARE);
467 foreach (self::$itemlist AS $item) {
468 if (!empty($item['contact-id']) && in_array($item['verb'], $verbs)) {
474 // But we will only import complete threads
475 $valid = dba::exists('item', array('uid' => $importer["uid"], 'uri' => self::$itemlist[0]['parent-uri']));
479 $default_contact = 0;
480 $key = count(self::$itemlist);
481 for ($key = count(self::$itemlist) - 1; $key >= 0; $key--) {
482 if (empty(self::$itemlist[$key]['contact-id'])) {
483 self::$itemlist[$key]['contact-id'] = $default_contact;
485 $default_contact = $item['contact-id'];
488 foreach (self::$itemlist AS $item) {
489 $found = dba::exists('item', array('uid' => $importer["uid"], 'uri' => $item["uri"]));
491 logger("Item with uri ".$item["uri"]." for user ".$importer["uid"]." already exists.", LOGGER_DEBUG);
492 } elseif ($item['contact-id'] < 0) {
493 logger("Item with uri ".$item["uri"]." is from a blocked contact.", LOGGER_DEBUG);
495 // We are having duplicated entries. Hopefully this solves it.
496 if (Lock::set('ostatus_process_item_store')) {
497 $ret = item_store($item);
498 Lock::remove('ostatus_process_item_store');
499 logger("Item with uri ".$item["uri"]." for user ".$importer["uid"].' stored. Return value: '.$ret);
501 $ret = item_store($item);
502 logger("We couldn't lock - but tried to store the item anyway. Return value is ".$ret);
507 self::$itemlist = array();
509 logger('Processing done for post with URI '.$item["uri"].' for user '.$importer["uid"].'.', LOGGER_DEBUG);
514 private static function deleteNotice($item) {
516 $condition = array('uid' => $item['uid'], 'author-link' => $item['author-link'], 'uri' => $item['uri']);
517 $deleted = dba::select('item', array('id', 'parent-uri'), $condition, array('limit' => 1));
518 if (!dbm::is_result($deleted)) {
519 logger('Item from '.$item['author-link'].' with uri '.$item['uri'].' for user '.$item['uid']." wasn't found. We don't delete it. ");
523 // 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
524 dba::update('item', array('deleted' => true, 'title' => '', 'body' => '',
525 'edited' => datetime_convert(), 'changed' => datetime_convert()),
526 array('id' => $deleted["id"]));
528 delete_thread($deleted["id"], $deleted["parent-uri"]);
530 logger('Deleted item with uri '.$item['uri'].' for user '.$item['uid']);
534 * @brief Processes the XML for a post
536 * @param object $xpath The xpath object
537 * @param object $entry The xml entry that is processed
538 * @param array $item The item array
539 * @param array $importer user record of the importing user
541 private static function processPost($xpath, $entry, &$item, $importer) {
542 $item["body"] = html2bbcode($xpath->query('atom:content/text()', $entry)->item(0)->nodeValue);
543 $item["object-type"] = $xpath->query('activity:object-type/text()', $entry)->item(0)->nodeValue;
544 if (($item["object-type"] == ACTIVITY_OBJ_BOOKMARK) || ($item["object-type"] == ACTIVITY_OBJ_EVENT)) {
545 $item["title"] = $xpath->query('atom:title/text()', $entry)->item(0)->nodeValue;
546 $item["body"] = $xpath->query('atom:summary/text()', $entry)->item(0)->nodeValue;
547 } elseif ($item["object-type"] == ACTIVITY_OBJ_QUESTION) {
548 $item["title"] = $xpath->query('atom:title/text()', $entry)->item(0)->nodeValue;
551 $item["created"] = $xpath->query('atom:published/text()', $entry)->item(0)->nodeValue;
552 $item["edited"] = $xpath->query('atom:updated/text()', $entry)->item(0)->nodeValue;
553 $conversation = $xpath->query('ostatus:conversation/text()', $entry)->item(0)->nodeValue;
554 $item['conversation-uri'] = $conversation;
556 $conv = $xpath->query('ostatus:conversation', $entry);
557 if (is_object($conv->item(0))) {
558 foreach ($conv->item(0)->attributes AS $attributes) {
559 if ($attributes->name == "ref") {
560 $item['conversation-uri'] = $attributes->textContent;
562 if ($attributes->name == "href") {
563 $item['conversation-href'] = $attributes->textContent;
570 $inreplyto = $xpath->query('thr:in-reply-to', $entry);
571 if (is_object($inreplyto->item(0))) {
572 foreach ($inreplyto->item(0)->attributes AS $attributes) {
573 if ($attributes->name == "ref") {
574 $item["parent-uri"] = $attributes->textContent;
576 if ($attributes->name == "href") {
577 $related = $attributes->textContent;
582 $georsspoint = $xpath->query('georss:point', $entry);
583 if (!empty($georsspoint) && ($georsspoint->length > 0)) {
584 $item["coord"] = $georsspoint->item(0)->nodeValue;
587 $categories = $xpath->query('atom:category', $entry);
589 foreach ($categories AS $category) {
590 foreach ($category->attributes AS $attributes) {
591 if ($attributes->name == "term") {
592 $term = $attributes->textContent;
593 if (strlen($item["tag"])) {
596 $item["tag"] .= "#[url=".System::baseUrl()."/search?tag=".$term."]".$term."[/url]";
605 $links = $xpath->query('atom:link', $entry);
607 $link_data = self::processLinks($links, $item);
608 $self = $link_data['self'];
609 $add_body = $link_data['add_body'];
614 $notice_info = $xpath->query('statusnet:notice_info', $entry);
615 if ($notice_info && ($notice_info->length > 0)) {
616 foreach ($notice_info->item(0)->attributes AS $attributes) {
617 if ($attributes->name == "source") {
618 $item["app"] = strip_tags($attributes->textContent);
620 if ($attributes->name == "repeat_of") {
621 $repeat_of = $attributes->textContent;
625 // Is it a repeated post?
626 if (($repeat_of != "") || ($item["verb"] == ACTIVITY_SHARE)) {
627 $link_data = self::processRepeatedItem($xpath, $entry, $item, $importer);
628 if (!empty($link_data['add_body'])) {
629 $add_body .= $link_data['add_body'];
633 $item["body"] .= $add_body;
635 // Only add additional data when there is no picture in the post
636 if (!strstr($item["body"],'[/img]')) {
637 $item["body"] = add_page_info_to_body($item["body"]);
640 // Mastodon Content Warning
641 if (($item["verb"] == ACTIVITY_POST) && $xpath->evaluate('boolean(atom:summary)', $entry)) {
642 $clear_text = $xpath->query('atom:summary/text()', $entry)->item(0)->nodeValue;
644 $item["body"] = html2bbcode($clear_text) . '[spoiler]' . $item["body"] . '[/spoiler]';
647 if (($self != '') && empty($item['protocol'])) {
648 self::fetchSelf($self, $item);
651 if (!empty($item["conversation-href"])) {
652 self::fetchConversation($item['conversation-href'], $item['conversation-uri']);
655 if (isset($item["parent-uri"]) && ($related != '')) {
656 if (!dba::exists('item', array('uid' => $importer["uid"], 'uri' => $item['parent-uri']))) {
657 self::fetchRelated($related, $item["parent-uri"], $importer);
659 logger('Reply with URI '.$item["uri"].' already existed for user '.$importer["uid"].'.', LOGGER_DEBUG);
662 $item["type"] = 'remote-comment';
663 $item["gravity"] = GRAVITY_COMMENT;
665 $item["parent-uri"] = $item["uri"];
668 if (($item['author-link'] != '') && !empty($item['protocol'])) {
669 $item = store_conversation($item);
672 self::$itemlist[] = $item;
676 * @brief Fetch the conversation for posts
678 * @param string $conversation The link to the conversation
679 * @param string $conversation_uri The conversation in "uri" format
681 private static function fetchConversation($conversation, $conversation_uri) {
683 // Ensure that we only store a conversation once in a process
684 if (isset(self::$conv_list[$conversation])) {
688 self::$conv_list[$conversation] = true;
690 $conversation_data = z_fetch_url($conversation, false, $redirects, array('accept_content' => 'application/atom+xml, text/html'));
692 if (!$conversation_data['success']) {
698 if (stristr($conversation_data['header'], 'Content-Type: application/atom+xml')) {
699 $xml = $conversation_data['body'];
703 $doc = new DOMDocument();
704 if (!@$doc->loadHTML($conversation_data['body'])) {
707 $xpath = new DomXPath($doc);
709 $links = $xpath->query('//link');
711 foreach ($links AS $link) {
712 $attribute = ostatus::read_attributes($link);
713 if (($attribute['rel'] == 'alternate') && ($attribute['type'] == 'application/atom+xml')) {
714 $file = $attribute['href'];
718 $conversation_atom = z_fetch_url($attribute['href']);
720 if ($conversation_atom['success']) {
721 $xml = $conversation_atom['body'];
731 self::storeConversation($xml, $conversation, $conversation_uri);
735 * @brief Store a feed in several conversation entries
737 * @param string $xml The feed
739 private static function storeConversation($xml, $conversation = '', $conversation_uri = '') {
740 $doc = new DOMDocument();
741 @$doc->loadXML($xml);
743 $xpath = new DomXPath($doc);
744 $xpath->registerNamespace('atom', NAMESPACE_ATOM1);
745 $xpath->registerNamespace('thr', NAMESPACE_THREAD);
746 $xpath->registerNamespace('ostatus', NAMESPACE_OSTATUS);
748 $entries = $xpath->query('/atom:feed/atom:entry');
750 // Now store the entries
751 foreach ($entries AS $entry) {
752 $doc2 = new DOMDocument();
753 $doc2->preserveWhiteSpace = false;
754 $doc2->formatOutput = true;
756 $conv_data = array();
758 $conv_data['protocol'] = PROTOCOL_SPLITTED_CONV;
759 $conv_data['network'] = NETWORK_OSTATUS;
760 $conv_data['uri'] = $xpath->query('atom:id/text()', $entry)->item(0)->nodeValue;
762 $inreplyto = $xpath->query('thr:in-reply-to', $entry);
763 if (is_object($inreplyto->item(0))) {
764 foreach ($inreplyto->item(0)->attributes AS $attributes) {
765 if ($attributes->name == "ref") {
766 $conv_data['reply-to-uri'] = $attributes->textContent;
771 $conv = $xpath->query('ostatus:conversation/text()', $entry)->item(0)->nodeValue;
772 $conv_data['conversation-uri'] = $conv;
774 $conv = $xpath->query('ostatus:conversation', $entry);
775 if (is_object($conv->item(0))) {
776 foreach ($conv->item(0)->attributes AS $attributes) {
777 if ($attributes->name == "ref") {
778 $conv_data['conversation-uri'] = $attributes->textContent;
780 if ($attributes->name == "href") {
781 $conv_data['conversation-href'] = $attributes->textContent;
786 if ($conversation != '') {
787 $conv_data['conversation-uri'] = $conversation;
790 if ($conversation_uri != '') {
791 $conv_data['conversation-uri'] = $conversation_uri;
794 $entry = $doc2->importNode($entry, true);
796 $doc2->appendChild($entry);
798 $conv_data['source'] = $doc2->saveXML();
800 $condition = array('item-uri' => $conv_data['uri'],'protocol' => PROTOCOL_OSTATUS_FEED);
801 if (dba::exists('conversation', $condition)) {
802 logger('Delete deprecated entry for URI '.$conv_data['uri'], LOGGER_DEBUG);
803 dba::delete('conversation', array('item-uri' => $conv_data['uri']));
806 logger('Store conversation data for uri '.$conv_data['uri'], LOGGER_DEBUG);
807 store_conversation($conv_data);
812 * @brief Fetch the own post so that it can be stored later
813 * @param array $item The item array
815 * We want to store the original data for later processing.
816 * This function is meant for cases where we process a feed with multiple entries.
817 * In that case we need to fetch the single posts here.
819 * @param string $self The link to the self item
821 private static function fetchSelf($self, &$item) {
822 $condition = array('`item-uri` = ? AND `protocol` IN (?, ?)', $self, PROTOCOL_DFRN, PROTOCOL_OSTATUS_SALMON);
823 if (dba::exists('conversation', $condition)) {
824 logger('Conversation '.$item['uri'].' is already stored.', LOGGER_DEBUG);
828 $self_data = z_fetch_url($self);
830 if (!$self_data['success']) {
834 // We reformat the XML to make it better readable
835 $doc = new DOMDocument();
836 $doc->loadXML($self_data['body']);
837 $doc->preserveWhiteSpace = false;
838 $doc->formatOutput = true;
839 $xml = $doc->saveXML();
841 $item["protocol"] = PROTOCOL_OSTATUS_SALMON;
842 $item["source"] = $xml;
844 logger('Conversation '.$item['uri'].' is now fetched.', LOGGER_DEBUG);
848 * @brief Fetch related posts and processes them
850 * @param string $related The link to the related item
851 * @param string $related_uri The related item in "uri" format
852 * @param array $importer user record of the importing user
854 private static function fetchRelated($related, $related_uri, $importer) {
855 $condition = array('`item-uri` = ? AND `protocol` IN (?, ?)', $related_uri, PROTOCOL_DFRN, PROTOCOL_OSTATUS_SALMON);
856 $conversation = dba::select('conversation', array('source', 'protocol'), $condition, array('limit' => 1));
857 if (dbm::is_result($conversation)) {
859 $xml = $conversation['source'];
860 if (self::process($xml, $importer, $contact, $hub, $stored, false)) {
861 logger('Got valid cached XML for URI '.$related_uri, LOGGER_DEBUG);
864 if ($conversation['protocol'] == PROTOCOL_OSTATUS_SALMON) {
865 logger('Delete invalid cached XML for URI '.$related_uri, LOGGER_DEBUG);
866 dba::delete('conversation', array('item-uri' => $related_uri));
871 $related_data = z_fetch_url($related, false, $redirects, array('accept_content' => 'application/atom+xml, text/html'));
873 if (!$related_data['success']) {
879 if (stristr($related_data['header'], 'Content-Type: application/atom+xml')) {
880 logger('Directly fetched XML for URI '.$related_uri, LOGGER_DEBUG);
881 $xml = $related_data['body'];
885 $doc = new DOMDocument();
886 if (!@$doc->loadHTML($related_data['body'])) {
889 $xpath = new DomXPath($doc);
893 $links = $xpath->query('//link');
895 foreach ($links AS $link) {
896 $attribute = self::read_attributes($link);
897 if (($attribute['rel'] == 'alternate') && ($attribute['type'] == 'application/atom+xml')) {
898 $atom_file = $attribute['href'];
901 if ($atom_file != '') {
902 $related_atom = z_fetch_url($atom_file);
904 if ($related_atom['success']) {
905 logger('Fetched XML for URI '.$related_uri, LOGGER_DEBUG);
906 $xml = $related_atom['body'];
912 // Workaround for older GNU Social servers
913 if (($xml == '') && strstr($related, '/notice/')) {
914 $related_atom = z_fetch_url(str_replace('/notice/', '/api/statuses/show/', $related).'.atom');
916 if ($related_atom['success']) {
917 logger('GNU Social workaround to fetch XML for URI '.$related_uri, LOGGER_DEBUG);
918 $xml = $related_atom['body'];
922 // Even more worse workaround for GNU Social ;-)
924 $related_guess = ostatus::convert_href($related_uri);
925 $related_atom = z_fetch_url(str_replace('/notice/', '/api/statuses/show/', $related_guess).'.atom');
927 if ($related_atom['success']) {
928 logger('GNU Social workaround 2 to fetch XML for URI '.$related_uri, LOGGER_DEBUG);
929 $xml = $related_atom['body'];
933 // Finally we take the data that we fetched from "ostatus:conversation"
935 $condition = array('item-uri' => $related_uri, 'protocol' => PROTOCOL_SPLITTED_CONV);
936 $conversation = dba::select('conversation', array('source'), $condition, array('limit' => 1));
937 if (dbm::is_result($conversation)) {
939 logger('Got cached XML from conversation for URI '.$related_uri, LOGGER_DEBUG);
940 $xml = $conversation['source'];
945 self::process($xml, $importer, $contact, $hub, $stored, false);
947 logger("XML couldn't be fetched for URI: ".$related_uri." - href: ".$related, LOGGER_DEBUG);
953 * @brief Processes the XML for a repeated post
955 * @param object $xpath The xpath object
956 * @param object $entry The xml entry that is processed
957 * @param array $item The item array
958 * @param array $importer user record of the importing user
960 * @return array with data from links
962 private static function processRepeatedItem($xpath, $entry, &$item, $importer) {
963 $activityobjects = $xpath->query('activity:object', $entry)->item(0);
965 if (!is_object($activityobjects)) {
969 $link_data = array();
971 $orig_uri = $xpath->query('atom:id/text()', $activityobjects)->item(0)->nodeValue;
973 $links = $xpath->query("atom:link", $activityobjects);
975 $link_data = self::processLinks($links, $item);
978 $orig_body = $xpath->query('atom:content/text()', $activityobjects)->item(0)->nodeValue;
979 $orig_created = $xpath->query('atom:published/text()', $activityobjects)->item(0)->nodeValue;
980 $orig_edited = $xpath->query('atom:updated/text()', $activityobjects)->item(0)->nodeValue;
982 $orig_contact = $contact;
983 $orig_author = self::fetchauthor($xpath, $activityobjects, $importer, $orig_contact, false);
985 $item["author-name"] = $orig_author["author-name"];
986 $item["author-link"] = $orig_author["author-link"];
987 $item["author-avatar"] = $orig_author["author-avatar"];
989 $item["body"] = html2bbcode($orig_body);
990 $item["created"] = $orig_created;
991 $item["edited"] = $orig_edited;
993 $item["uri"] = $orig_uri;
995 $item["verb"] = $xpath->query('activity:verb/text()', $activityobjects)->item(0)->nodeValue;
997 $item["object-type"] = $xpath->query('activity:object-type/text()', $activityobjects)->item(0)->nodeValue;
999 $inreplyto = $xpath->query('thr:in-reply-to', $activityobjects);
1000 if (is_object($inreplyto->item(0))) {
1001 foreach ($inreplyto->item(0)->attributes AS $attributes) {
1002 if ($attributes->name == "ref") {
1003 $item["parent-uri"] = $attributes->textContent;
1012 * @brief Processes links in the XML
1014 * @param object $links The xml data that contain links
1015 * @param array $item The item array
1017 * @return array with data from the links
1019 private static function processLinks($links, &$item) {
1020 $link_data = array('add_body' => '', 'self' => '');
1022 foreach ($links AS $link) {
1023 $attribute = self::read_attributes($link);
1025 if (($attribute['rel'] != "") && ($attribute['href'] != "")) {
1026 switch ($attribute['rel']) {
1028 $item["plink"] = $attribute['href'];
1029 if (($item["object-type"] == ACTIVITY_OBJ_QUESTION) ||
1030 ($item["object-type"] == ACTIVITY_OBJ_EVENT)) {
1031 $item["body"] .= add_page_info($attribute['href']);
1034 case "ostatus:conversation":
1035 $link_data['conversation'] = $attribute['href'];
1036 $item['conversation-href'] = $link_data['conversation'];
1037 if (!isset($item['conversation-uri'])) {
1038 $item['conversation-uri'] = $item['conversation-href'];
1042 $filetype = strtolower(substr($attribute['type'], 0, strpos($attribute['type'],'/')));
1043 if ($filetype == 'image') {
1044 $link_data['add_body'] .= "\n[img]".$attribute['href'].'[/img]';
1046 if (strlen($item["attach"])) {
1047 $item["attach"] .= ',';
1049 if (!isset($attribute['length'])) {
1050 $attribute['length'] = "0";
1052 $item["attach"] .= '[attach]href="'.$attribute['href'].'" length="'.$attribute['length'].'" type="'.$attribute['type'].'" title="'.$attribute['title'].'"[/attach]';
1056 if ($item["object-type"] != ACTIVITY_OBJ_BOOKMARK) {
1057 if (!isset($item["parent-uri"])) {
1058 $item["parent-uri"] = $attribute['href'];
1060 $link_data['related'] = $attribute['href'];
1062 $item["body"] .= add_page_info($attribute['href']);
1066 if ($item["plink"] == '') {
1067 $item["plink"] = $attribute['href'];
1069 $link_data['self'] = $attribute['href'];
1078 * @brief Create an url out of an uri
1080 * @param string $href URI in the format "parameter1:parameter1:..."
1082 * @return string URL in the format http(s)://....
1084 public static function convert_href($href) {
1085 $elements = explode(":",$href);
1087 if ((count($elements) <= 2) || ($elements[0] != "tag"))
1090 $server = explode(",", $elements[1]);
1091 $conversation = explode("=", $elements[2]);
1093 if ((count($elements) == 4) && ($elements[2] == "post"))
1094 return "http://".$server[0]."/notice/".$elements[3];
1096 if ((count($conversation) != 2) || ($conversation[1] =="")) {
1099 if ($elements[3] == "objectType=thread") {
1100 return "http://".$server[0]."/conversation/".$conversation[1];
1102 return "http://".$server[0]."/notice/".$conversation[1];
1108 * @brief Checks if the current post is a reshare
1110 * @param array $item The item array of thw post
1112 * @return string The guid if the post is a reshare
1114 private static function get_reshared_guid($item) {
1115 $body = trim($item["body"]);
1117 // Skip if it isn't a pure repeated messages
1118 // Does it start with a share?
1119 if (strpos($body, "[share") > 0)
1122 // Does it end with a share?
1123 if (strlen($body) > (strrpos($body, "[/share]") + 8))
1126 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$1",$body);
1127 // Skip if there is no shared message in there
1128 if ($body == $attributes)
1132 preg_match("/guid='(.*?)'/ism", $attributes, $matches);
1133 if ($matches[1] != "")
1134 $guid = $matches[1];
1136 preg_match('/guid="(.*?)"/ism', $attributes, $matches);
1137 if ($matches[1] != "")
1138 $guid = $matches[1];
1144 * @brief Cleans the body of a post if it contains picture links
1146 * @param string $body The body
1148 * @return string The cleaned body
1150 private static function format_picture_post($body) {
1151 $siteinfo = get_attached_data($body);
1153 if (($siteinfo["type"] == "photo")) {
1154 if (isset($siteinfo["preview"]))
1155 $preview = $siteinfo["preview"];
1157 $preview = $siteinfo["image"];
1159 // Is it a remote picture? Then make a smaller preview here
1160 $preview = proxy_url($preview, false, PROXY_SIZE_SMALL);
1162 // Is it a local picture? Then make it smaller here
1163 $preview = str_replace(array("-0.jpg", "-0.png"), array("-2.jpg", "-2.png"), $preview);
1164 $preview = str_replace(array("-1.jpg", "-1.png"), array("-2.jpg", "-2.png"), $preview);
1166 if (isset($siteinfo["url"]))
1167 $url = $siteinfo["url"];
1169 $url = $siteinfo["image"];
1171 $body = trim($siteinfo["text"])." [url]".$url."[/url]\n[img]".$preview."[/img]";
1178 * @brief Adds the header elements to the XML document
1180 * @param object $doc XML document
1181 * @param array $owner Contact data of the poster
1183 * @return object header root element
1185 private static function add_header($doc, $owner) {
1189 $root = $doc->createElementNS(NAMESPACE_ATOM1, 'feed');
1190 $doc->appendChild($root);
1192 $root->setAttribute("xmlns:thr", NAMESPACE_THREAD);
1193 $root->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
1194 $root->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
1195 $root->setAttribute("xmlns:media", NAMESPACE_MEDIA);
1196 $root->setAttribute("xmlns:poco", NAMESPACE_POCO);
1197 $root->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
1198 $root->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
1199 $root->setAttribute("xmlns:mastodon", NAMESPACE_MASTODON);
1201 $attributes = array("uri" => "https://friendi.ca", "version" => FRIENDICA_VERSION."-".DB_UPDATE_VERSION);
1202 xml::add_element($doc, $root, "generator", FRIENDICA_PLATFORM, $attributes);
1203 xml::add_element($doc, $root, "id", System::baseUrl()."/profile/".$owner["nick"]);
1204 xml::add_element($doc, $root, "title", sprintf("%s timeline", $owner["name"]));
1205 xml::add_element($doc, $root, "subtitle", sprintf("Updates from %s on %s", $owner["name"], $a->config["sitename"]));
1206 xml::add_element($doc, $root, "logo", $owner["photo"]);
1207 xml::add_element($doc, $root, "updated", datetime_convert("UTC", "UTC", "now", ATOM_TIME));
1209 $author = self::add_author($doc, $owner);
1210 $root->appendChild($author);
1212 $attributes = array("href" => $owner["url"], "rel" => "alternate", "type" => "text/html");
1213 xml::add_element($doc, $root, "link", "", $attributes);
1215 /// @TODO We have to find out what this is
1216 /// $attributes = array("href" => System::baseUrl()."/sup",
1217 /// "rel" => "http://api.friendfeed.com/2008/03#sup",
1218 /// "type" => "application/json");
1219 /// xml::add_element($doc, $root, "link", "", $attributes);
1221 self::hublinks($doc, $root, $owner["nick"]);
1223 $attributes = array("href" => System::baseUrl()."/salmon/".$owner["nick"], "rel" => "salmon");
1224 xml::add_element($doc, $root, "link", "", $attributes);
1226 $attributes = array("href" => System::baseUrl()."/salmon/".$owner["nick"], "rel" => "http://salmon-protocol.org/ns/salmon-replies");
1227 xml::add_element($doc, $root, "link", "", $attributes);
1229 $attributes = array("href" => System::baseUrl()."/salmon/".$owner["nick"], "rel" => "http://salmon-protocol.org/ns/salmon-mention");
1230 xml::add_element($doc, $root, "link", "", $attributes);
1232 $attributes = array("href" => System::baseUrl()."/api/statuses/user_timeline/".$owner["nick"].".atom",
1233 "rel" => "self", "type" => "application/atom+xml");
1234 xml::add_element($doc, $root, "link", "", $attributes);
1240 * @brief Add the link to the push hubs to the XML document
1242 * @param object $doc XML document
1243 * @param object $root XML root element where the hub links are added
1245 public static function hublinks($doc, $root, $nick) {
1246 $h = System::baseUrl() . '/pubsubhubbub/'.$nick;
1247 xml::add_element($doc, $root, "link", "", array("href" => $h, "rel" => "hub"));
1251 * @brief Adds attachement data to the XML document
1253 * @param object $doc XML document
1254 * @param object $root XML root element where the hub links are added
1255 * @param array $item Data of the item that is to be posted
1257 private static function get_attachment($doc, $root, $item) {
1259 $siteinfo = get_attached_data($item["body"]);
1261 switch ($siteinfo["type"]) {
1263 $imgdata = get_photo_info($siteinfo["image"]);
1264 $attributes = array("rel" => "enclosure",
1265 "href" => $siteinfo["image"],
1266 "type" => $imgdata["mime"],
1267 "length" => intval($imgdata["size"]));
1268 xml::add_element($doc, $root, "link", "", $attributes);
1271 $attributes = array("rel" => "enclosure",
1272 "href" => $siteinfo["url"],
1273 "type" => "text/html; charset=UTF-8",
1275 "title" => $siteinfo["title"]);
1276 xml::add_element($doc, $root, "link", "", $attributes);
1282 if (!Config::get('system', 'ostatus_not_attach_preview') && ($siteinfo["type"] != "photo") && isset($siteinfo["image"])) {
1283 $imgdata = get_photo_info($siteinfo["image"]);
1284 $attributes = array("rel" => "enclosure",
1285 "href" => $siteinfo["image"],
1286 "type" => $imgdata["mime"],
1287 "length" => intval($imgdata["size"]));
1289 xml::add_element($doc, $root, "link", "", $attributes);
1292 $arr = explode('[/attach],', $item['attach']);
1294 foreach ($arr as $r) {
1296 $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"|', $r, $matches);
1298 $attributes = array("rel" => "enclosure",
1299 "href" => $matches[1],
1300 "type" => $matches[3]);
1302 if (intval($matches[2])) {
1303 $attributes["length"] = intval($matches[2]);
1305 if (trim($matches[4]) != "") {
1306 $attributes["title"] = trim($matches[4]);
1308 xml::add_element($doc, $root, "link", "", $attributes);
1315 * @brief Adds the author element to the XML document
1317 * @param object $doc XML document
1318 * @param array $owner Contact data of the poster
1320 * @return object author element
1322 private static function add_author($doc, $owner) {
1324 $r = q("SELECT `homepage`, `publish` FROM `profile` WHERE `uid` = %d AND `is-default` LIMIT 1", intval($owner["uid"]));
1325 if (dbm::is_result($r)) {
1328 $author = $doc->createElement("author");
1329 xml::add_element($doc, $author, "id", $owner["url"]);
1330 xml::add_element($doc, $author, "activity:object-type", ACTIVITY_OBJ_PERSON);
1331 xml::add_element($doc, $author, "uri", $owner["url"]);
1332 xml::add_element($doc, $author, "name", $owner["nick"]);
1333 xml::add_element($doc, $author, "email", $owner["addr"]);
1334 xml::add_element($doc, $author, "summary", bbcode($owner["about"], false, false, 7));
1336 $attributes = array("rel" => "alternate", "type" => "text/html", "href" => $owner["url"]);
1337 xml::add_element($doc, $author, "link", "", $attributes);
1339 $attributes = array(
1341 "type" => "image/jpeg", // To-Do?
1342 "media:width" => 175,
1343 "media:height" => 175,
1344 "href" => $owner["photo"]);
1345 xml::add_element($doc, $author, "link", "", $attributes);
1347 if (isset($owner["thumb"])) {
1348 $attributes = array(
1350 "type" => "image/jpeg", // To-Do?
1351 "media:width" => 80,
1352 "media:height" => 80,
1353 "href" => $owner["thumb"]);
1354 xml::add_element($doc, $author, "link", "", $attributes);
1357 xml::add_element($doc, $author, "poco:preferredUsername", $owner["nick"]);
1358 xml::add_element($doc, $author, "poco:displayName", $owner["name"]);
1359 xml::add_element($doc, $author, "poco:note", bbcode($owner["about"], false, false, 7));
1361 if (trim($owner["location"]) != "") {
1362 $element = $doc->createElement("poco:address");
1363 xml::add_element($doc, $element, "poco:formatted", $owner["location"]);
1364 $author->appendChild($element);
1367 if (trim($profile["homepage"]) != "") {
1368 $urls = $doc->createElement("poco:urls");
1369 xml::add_element($doc, $urls, "poco:type", "homepage");
1370 xml::add_element($doc, $urls, "poco:value", $profile["homepage"]);
1371 xml::add_element($doc, $urls, "poco:primary", "true");
1372 $author->appendChild($urls);
1375 if (count($profile)) {
1376 xml::add_element($doc, $author, "followers", "", array("url" => System::baseUrl()."/viewcontacts/".$owner["nick"]));
1377 xml::add_element($doc, $author, "statusnet:profile_info", "", array("local_id" => $owner["uid"]));
1380 if ($profile["publish"]) {
1381 xml::add_element($doc, $author, "mastodon:scope", "public");
1387 * @TODO Picture attachments should look like this:
1388 * <a href="https://status.pirati.ca/attachment/572819" title="https://status.pirati.ca/file/heluecht-20151202T222602-rd3u49p.gif"
1389 * class="attachment thumbnail" id="attachment-572819" rel="nofollow external">https://status.pirati.ca/attachment/572819</a>
1394 * @brief Returns the given activity if present - otherwise returns the "post" activity
1396 * @param array $item Data of the item that is to be posted
1398 * @return string activity
1400 private static function construct_verb($item) {
1402 return $item['verb'];
1403 return ACTIVITY_POST;
1407 * @brief Returns the given object type if present - otherwise returns the "note" object type
1409 * @param array $item Data of the item that is to be posted
1411 * @return string Object type
1413 private static function construct_objecttype($item) {
1414 if (in_array($item['object-type'], array(ACTIVITY_OBJ_NOTE, ACTIVITY_OBJ_COMMENT)))
1415 return $item['object-type'];
1416 return ACTIVITY_OBJ_NOTE;
1420 * @brief Adds an entry element to the XML document
1422 * @param object $doc XML document
1423 * @param array $item Data of the item that is to be posted
1424 * @param array $owner Contact data of the poster
1425 * @param bool $toplevel
1427 * @return object Entry element
1429 private static function entry($doc, $item, $owner, $toplevel = false) {
1430 $repeated_guid = self::get_reshared_guid($item);
1431 if ($repeated_guid != "")
1432 $xml = self::reshare_entry($doc, $item, $owner, $repeated_guid, $toplevel);
1437 if ($item["verb"] == ACTIVITY_LIKE) {
1438 return self::like_entry($doc, $item, $owner, $toplevel);
1439 } elseif (in_array($item["verb"], array(ACTIVITY_FOLLOW, NAMESPACE_OSTATUS."/unfollow"))) {
1440 return self::follow_entry($doc, $item, $owner, $toplevel);
1442 return self::note_entry($doc, $item, $owner, $toplevel);
1447 * @brief Adds a source entry to the XML document
1449 * @param object $doc XML document
1450 * @param array $contact Array of the contact that is added
1452 * @return object Source element
1454 private static function source_entry($doc, $contact) {
1455 $source = $doc->createElement("source");
1456 xml::add_element($doc, $source, "id", $contact["poll"]);
1457 xml::add_element($doc, $source, "title", $contact["name"]);
1458 xml::add_element($doc, $source, "link", "", array("rel" => "alternate",
1459 "type" => "text/html",
1460 "href" => $contact["alias"]));
1461 xml::add_element($doc, $source, "link", "", array("rel" => "self",
1462 "type" => "application/atom+xml",
1463 "href" => $contact["poll"]));
1464 xml::add_element($doc, $source, "icon", $contact["photo"]);
1465 xml::add_element($doc, $source, "updated", datetime_convert("UTC","UTC",$contact["success_update"]."+00:00",ATOM_TIME));
1471 * @brief Fetches contact data from the contact or the gcontact table
1473 * @param string $url URL of the contact
1474 * @param array $owner Contact data of the poster
1476 * @return array Contact array
1478 private static function contact_entry($url, $owner) {
1480 $r = q("SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` IN (0, %d) ORDER BY `uid` DESC LIMIT 1",
1481 dbesc(normalise_link($url)), intval($owner["uid"]));
1482 if (dbm::is_result($r)) {
1484 $contact["uid"] = -1;
1487 if (!dbm::is_result($r)) {
1488 $r = q("SELECT * FROM `gcontact` WHERE `nurl` = '%s' LIMIT 1",
1489 dbesc(normalise_link($url)));
1490 if (dbm::is_result($r)) {
1492 $contact["uid"] = -1;
1493 $contact["success_update"] = $contact["updated"];
1497 if (!dbm::is_result($r))
1500 if (!isset($contact["poll"])) {
1501 $data = probe_url($url);
1502 $contact["poll"] = $data["poll"];
1504 if (!$contact["alias"])
1505 $contact["alias"] = $data["alias"];
1508 if (!isset($contact["alias"]))
1509 $contact["alias"] = $contact["url"];
1515 * @brief Adds an entry element with reshared content
1517 * @param object $doc XML document
1518 * @param array $item Data of the item that is to be posted
1519 * @param array $owner Contact data of the poster
1520 * @param $repeated_guid
1521 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1523 * @return object Entry element
1525 private static function reshare_entry($doc, $item, $owner, $repeated_guid, $toplevel) {
1527 if (($item["id"] != $item["parent"]) && (normalise_link($item["author-link"]) != normalise_link($owner["url"]))) {
1528 logger("OStatus entry is from author ".$owner["url"]." - not from ".$item["author-link"].". Quitting.", LOGGER_DEBUG);
1531 $title = self::entry_header($doc, $entry, $owner, $toplevel);
1533 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' AND NOT `private` AND `network` IN ('%s', '%s', '%s') LIMIT 1",
1534 intval($owner["uid"]), dbesc($repeated_guid),
1535 dbesc(NETWORK_DFRN), dbesc(NETWORK_DIASPORA), dbesc(NETWORK_OSTATUS));
1536 if (dbm::is_result($r)) {
1537 $repeated_item = $r[0];
1541 $contact = self::contact_entry($repeated_item['author-link'], $owner);
1543 $parent_item = (($item['thr-parent']) ? $item['thr-parent'] : $item['parent-uri']);
1545 $title = $owner["nick"]." repeated a notice by ".$contact["nick"];
1547 self::entry_content($doc, $entry, $item, $owner, $title, ACTIVITY_SHARE, false);
1549 $as_object = $doc->createElement("activity:object");
1551 xml::add_element($doc, $as_object, "activity:object-type", NAMESPACE_ACTIVITY_SCHEMA."activity");
1553 self::entry_content($doc, $as_object, $repeated_item, $owner, "", "", false);
1555 $author = self::add_author($doc, $contact);
1556 $as_object->appendChild($author);
1558 $as_object2 = $doc->createElement("activity:object");
1560 xml::add_element($doc, $as_object2, "activity:object-type", self::construct_objecttype($repeated_item));
1562 $title = sprintf("New comment by %s", $contact["nick"]);
1564 self::entry_content($doc, $as_object2, $repeated_item, $owner, $title);
1566 $as_object->appendChild($as_object2);
1568 self::entry_footer($doc, $as_object, $item, $owner, false);
1570 $source = self::source_entry($doc, $contact);
1572 $as_object->appendChild($source);
1574 $entry->appendChild($as_object);
1576 self::entry_footer($doc, $entry, $item, $owner);
1582 * @brief Adds an entry element with a "like"
1584 * @param object $doc XML document
1585 * @param array $item Data of the item that is to be posted
1586 * @param array $owner Contact data of the poster
1587 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1589 * @return object Entry element with "like"
1591 private static function like_entry($doc, $item, $owner, $toplevel) {
1593 if (($item["id"] != $item["parent"]) && (normalise_link($item["author-link"]) != normalise_link($owner["url"]))) {
1594 logger("OStatus entry is from author ".$owner["url"]." - not from ".$item["author-link"].". Quitting.", LOGGER_DEBUG);
1597 $title = self::entry_header($doc, $entry, $owner, $toplevel);
1599 $verb = NAMESPACE_ACTIVITY_SCHEMA."favorite";
1600 self::entry_content($doc, $entry, $item, $owner, "Favorite", $verb, false);
1602 $as_object = $doc->createElement("activity:object");
1604 $parent = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d",
1605 dbesc($item["thr-parent"]), intval($item["uid"]));
1606 $parent_item = (($item['thr-parent']) ? $item['thr-parent'] : $item['parent-uri']);
1608 xml::add_element($doc, $as_object, "activity:object-type", self::construct_objecttype($parent[0]));
1610 self::entry_content($doc, $as_object, $parent[0], $owner, "New entry");
1612 $entry->appendChild($as_object);
1614 self::entry_footer($doc, $entry, $item, $owner);
1620 * @brief Adds the person object element to the XML document
1622 * @param object $doc XML document
1623 * @param array $owner Contact data of the poster
1624 * @param array $contact Contact data of the target
1626 * @return object author element
1628 private static function add_person_object($doc, $owner, $contact) {
1630 $object = $doc->createElement("activity:object");
1631 xml::add_element($doc, $object, "activity:object-type", ACTIVITY_OBJ_PERSON);
1633 if ($contact['network'] == NETWORK_PHANTOM) {
1634 xml::add_element($doc, $object, "id", $contact['url']);
1638 xml::add_element($doc, $object, "id", $contact["alias"]);
1639 xml::add_element($doc, $object, "title", $contact["nick"]);
1641 $attributes = array("rel" => "alternate", "type" => "text/html", "href" => $contact["url"]);
1642 xml::add_element($doc, $object, "link", "", $attributes);
1644 $attributes = array(
1646 "type" => "image/jpeg", // To-Do?
1647 "media:width" => 175,
1648 "media:height" => 175,
1649 "href" => $contact["photo"]);
1650 xml::add_element($doc, $object, "link", "", $attributes);
1652 xml::add_element($doc, $object, "poco:preferredUsername", $contact["nick"]);
1653 xml::add_element($doc, $object, "poco:displayName", $contact["name"]);
1655 if (trim($contact["location"]) != "") {
1656 $element = $doc->createElement("poco:address");
1657 xml::add_element($doc, $element, "poco:formatted", $contact["location"]);
1658 $object->appendChild($element);
1665 * @brief Adds a follow/unfollow entry element
1667 * @param object $doc XML document
1668 * @param array $item Data of the follow/unfollow message
1669 * @param array $owner Contact data of the poster
1670 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1672 * @return object Entry element
1674 private static function follow_entry($doc, $item, $owner, $toplevel) {
1676 $item["id"] = $item["parent"] = 0;
1677 $item["created"] = $item["edited"] = date("c");
1678 $item["private"] = true;
1680 $contact = Probe::uri($item['follow']);
1682 if ($contact['alias'] == '') {
1683 $contact['alias'] = $contact["url"];
1685 $item['follow'] = $contact['alias'];
1688 $r = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `nurl` = '%s'",
1689 intval($owner['uid']), dbesc(normalise_link($contact["url"])));
1691 if (dbm::is_result($r)) {
1692 $connect_id = $r[0]['id'];
1697 if ($item['verb'] == ACTIVITY_FOLLOW) {
1698 $message = t('%s is now following %s.');
1699 $title = t('following');
1700 $action = "subscription";
1702 $message = t('%s stopped following %s.');
1703 $title = t('stopped following');
1704 $action = "unfollow";
1707 $item["uri"] = $item['parent-uri'] = $item['thr-parent'] =
1708 'tag:'.get_app()->get_hostname().
1709 ','.date('Y-m-d').':'.$action.':'.$owner['uid'].
1710 ':person:'.$connect_id.':'.$item['created'];
1712 $item["body"] = sprintf($message, $owner["nick"], $contact["nick"]);
1714 self::entry_header($doc, $entry, $owner, $toplevel);
1716 self::entry_content($doc, $entry, $item, $owner, $title);
1718 $object = self::add_person_object($doc, $owner, $contact);
1719 $entry->appendChild($object);
1721 self::entry_footer($doc, $entry, $item, $owner);
1727 * @brief Adds a regular entry element
1729 * @param object $doc XML document
1730 * @param array $item Data of the item that is to be posted
1731 * @param array $owner Contact data of the poster
1732 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1734 * @return object Entry element
1736 private static function note_entry($doc, $item, $owner, $toplevel) {
1738 if (($item["id"] != $item["parent"]) && (normalise_link($item["author-link"]) != normalise_link($owner["url"]))) {
1739 logger("OStatus entry is from author ".$owner["url"]." - not from ".$item["author-link"].". Quitting.", LOGGER_DEBUG);
1742 $title = self::entry_header($doc, $entry, $owner, $toplevel);
1744 xml::add_element($doc, $entry, "activity:object-type", ACTIVITY_OBJ_NOTE);
1746 self::entry_content($doc, $entry, $item, $owner, $title);
1748 self::entry_footer($doc, $entry, $item, $owner);
1754 * @brief Adds a header element to the XML document
1756 * @param object $doc XML document
1757 * @param object $entry The entry element where the elements are added
1758 * @param array $owner Contact data of the poster
1759 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1761 * @return string The title for the element
1763 private static function entry_header($doc, &$entry, $owner, $toplevel) {
1764 /// @todo Check if this title stuff is really needed (I guess not)
1766 $entry = $doc->createElement("entry");
1767 $title = sprintf("New note by %s", $owner["nick"]);
1769 $entry = $doc->createElementNS(NAMESPACE_ATOM1, "entry");
1771 $entry->setAttribute("xmlns:thr", NAMESPACE_THREAD);
1772 $entry->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
1773 $entry->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
1774 $entry->setAttribute("xmlns:media", NAMESPACE_MEDIA);
1775 $entry->setAttribute("xmlns:poco", NAMESPACE_POCO);
1776 $entry->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
1777 $entry->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
1778 $entry->setAttribute("xmlns:mastodon", NAMESPACE_MASTODON);
1780 $author = self::add_author($doc, $owner);
1781 $entry->appendChild($author);
1783 $title = sprintf("New comment by %s", $owner["nick"]);
1789 * @brief Adds elements to the XML document
1791 * @param object $doc XML document
1792 * @param object $entry Entry element where the content is added
1793 * @param array $item Data of the item that is to be posted
1794 * @param array $owner Contact data of the poster
1795 * @param string $title Title for the post
1796 * @param string $verb The activity verb
1797 * @param bool $complete Add the "status_net" element?
1799 private static function entry_content($doc, $entry, $item, $owner, $title, $verb = "", $complete = true) {
1802 $verb = self::construct_verb($item);
1804 xml::add_element($doc, $entry, "id", $item["uri"]);
1805 xml::add_element($doc, $entry, "title", $title);
1807 $body = self::format_picture_post($item['body']);
1809 if ($item['title'] != "")
1810 $body = "[b]".$item['title']."[/b]\n\n".$body;
1812 $body = bbcode($body, false, false, 7);
1814 xml::add_element($doc, $entry, "content", $body, array("type" => "html"));
1816 xml::add_element($doc, $entry, "link", "", array("rel" => "alternate", "type" => "text/html",
1817 "href" => System::baseUrl()."/display/".$item["guid"]));
1819 if ($complete && ($item["id"] > 0))
1820 xml::add_element($doc, $entry, "status_net", "", array("notice_id" => $item["id"]));
1822 xml::add_element($doc, $entry, "activity:verb", $verb);
1824 xml::add_element($doc, $entry, "published", datetime_convert("UTC","UTC",$item["created"]."+00:00",ATOM_TIME));
1825 xml::add_element($doc, $entry, "updated", datetime_convert("UTC","UTC",$item["edited"]."+00:00",ATOM_TIME));
1829 * @brief Adds the elements at the foot of an entry to the XML document
1831 * @param object $doc XML document
1832 * @param object $entry The entry element where the elements are added
1833 * @param array $item Data of the item that is to be posted
1834 * @param array $owner Contact data of the poster
1837 private static function entry_footer($doc, $entry, $item, $owner, $complete = true) {
1839 $mentioned = array();
1841 if (($item['parent'] != $item['id']) || ($item['parent-uri'] !== $item['uri']) || (($item['thr-parent'] !== '') && ($item['thr-parent'] !== $item['uri']))) {
1842 $parent = q("SELECT `guid`, `author-link`, `owner-link` FROM `item` WHERE `id` = %d", intval($item["parent"]));
1843 $parent_item = (($item['thr-parent']) ? $item['thr-parent'] : $item['parent-uri']);
1845 $thrparent = q("SELECT `guid`, `author-link`, `owner-link`, `plink` FROM `item` WHERE `uid` = %d AND `uri` = '%s'",
1846 intval($owner["uid"]),
1847 dbesc($parent_item));
1849 $mentioned[$thrparent[0]["author-link"]] = $thrparent[0]["author-link"];
1850 $mentioned[$thrparent[0]["owner-link"]] = $thrparent[0]["owner-link"];
1851 $parent_plink = $thrparent[0]["plink"];
1853 $mentioned[$parent[0]["author-link"]] = $parent[0]["author-link"];
1854 $mentioned[$parent[0]["owner-link"]] = $parent[0]["owner-link"];
1855 $parent_plink = System::baseUrl()."/display/".$parent[0]["guid"];
1858 $attributes = array(
1859 "ref" => $parent_item,
1860 "href" => $parent_plink);
1861 xml::add_element($doc, $entry, "thr:in-reply-to", "", $attributes);
1863 $attributes = array(
1865 "href" => $parent_plink);
1866 xml::add_element($doc, $entry, "link", "", $attributes);
1869 if (intval($item["parent"]) > 0) {
1870 $conversation_href = System::baseUrl()."/display/".$owner["nick"]."/".$item["parent"];
1871 $conversation_uri = $conversation_href;
1873 if (isset($parent_item)) {
1874 $r = dba::fetch_first("SELECT `conversation-uri`, `conversation-href` FROM `conversation` WHERE `item-uri` = ?", $parent_item);
1875 if (dbm::is_result($r)) {
1876 if ($r['conversation-uri'] != '') {
1877 $conversation_uri = $r['conversation-uri'];
1879 if ($r['conversation-href'] != '') {
1880 $conversation_href = $r['conversation-href'];
1885 xml::add_element($doc, $entry, "link", "", array("rel" => "ostatus:conversation", "href" => $conversation_href));
1887 $attributes = array(
1888 "href" => $conversation_href,
1889 "local_id" => $item["parent"],
1890 "ref" => $conversation_uri);
1892 xml::add_element($doc, $entry, "ostatus:conversation", $conversation_uri, $attributes);
1895 $tags = item_getfeedtags($item);
1898 foreach ($tags as $t)
1900 $mentioned[$t[1]] = $t[1];
1902 // Make sure that mentions are accepted (GNU Social has problems with mixing HTTP and HTTPS)
1903 $newmentions = array();
1904 foreach ($mentioned AS $mention) {
1905 $newmentions[str_replace("http://", "https://", $mention)] = str_replace("http://", "https://", $mention);
1906 $newmentions[str_replace("https://", "http://", $mention)] = str_replace("https://", "http://", $mention);
1908 $mentioned = $newmentions;
1910 foreach ($mentioned AS $mention) {
1911 $r = q("SELECT `forum`, `prv` FROM `contact` WHERE `uid` = %d AND `nurl` = '%s'",
1912 intval($owner["uid"]),
1913 dbesc(normalise_link($mention)));
1914 if ($r[0]["forum"] || $r[0]["prv"])
1915 xml::add_element($doc, $entry, "link", "", array("rel" => "mentioned",
1916 "ostatus:object-type" => ACTIVITY_OBJ_GROUP,
1917 "href" => $mention));
1919 xml::add_element($doc, $entry, "link", "", array("rel" => "mentioned",
1920 "ostatus:object-type" => ACTIVITY_OBJ_PERSON,
1921 "href" => $mention));
1924 if (!$item["private"]) {
1925 xml::add_element($doc, $entry, "link", "", array("rel" => "ostatus:attention",
1926 "href" => "http://activityschema.org/collection/public"));
1927 xml::add_element($doc, $entry, "link", "", array("rel" => "mentioned",
1928 "ostatus:object-type" => "http://activitystrea.ms/schema/1.0/collection",
1929 "href" => "http://activityschema.org/collection/public"));
1930 xml::add_element($doc, $entry, "mastodon:scope", "public");
1934 foreach ($tags as $t)
1936 xml::add_element($doc, $entry, "category", "", array("term" => $t[2]));
1938 self::get_attachment($doc, $entry, $item);
1940 if ($complete && ($item["id"] > 0)) {
1941 $app = $item["app"];
1945 $attributes = array("local_id" => $item["id"], "source" => $app);
1947 if (isset($parent["id"]))
1948 $attributes["repeat_of"] = $parent["id"];
1950 if ($item["coord"] != "")
1951 xml::add_element($doc, $entry, "georss:point", $item["coord"]);
1953 xml::add_element($doc, $entry, "statusnet:notice_info", "", $attributes);
1958 * @brief Creates the XML feed for a given nickname
1960 * @param App $a The application class
1961 * @param string $owner_nick Nickname of the feed owner
1962 * @param string $last_update Date of the last update
1963 * @param integer $max_items Number of maximum items to fetch
1965 * @return string XML feed
1967 public static function feed(App $a, $owner_nick, &$last_update, $max_items = 300) {
1968 $stamp = microtime(true);
1970 $cachekey = "ostatus:feed:".$owner_nick.":".$last_update;
1972 $previous_created = $last_update;
1974 $result = Cache::get($cachekey);
1975 if (!is_null($result)) {
1976 logger('Feed duration: '.number_format(microtime(true) - $stamp, 3).' - '.$owner_nick.' - '.$previous_created.' (cached)', LOGGER_DEBUG);
1977 $last_update = $result['last_update'];
1978 return $result['feed'];
1981 $r = q("SELECT `contact`.*, `user`.`nickname`, `user`.`timezone`, `user`.`page-flags`
1982 FROM `contact` INNER JOIN `user` ON `user`.`uid` = `contact`.`uid`
1983 WHERE `contact`.`self` AND `user`.`nickname` = '%s' LIMIT 1",
1984 dbesc($owner_nick));
1985 if (!dbm::is_result($r)) {
1991 if (!strlen($last_update)) {
1992 $last_update = 'now -30 days';
1995 $check_date = datetime_convert('UTC','UTC',$last_update,'Y-m-d H:i:s');
1996 $authorid = get_contact($owner["url"], 0);
1998 $items = q("SELECT `item`.*, `item`.`id` AS `item_id` FROM `item` USE INDEX (`uid_contactid_created`)
1999 STRAIGHT_JOIN `thread` ON `thread`.`iid` = `item`.`parent`
2000 WHERE `item`.`uid` = %d AND `item`.`contact-id` = %d AND
2001 `item`.`author-id` = %d AND `item`.`created` > '%s' AND
2002 NOT `item`.`deleted` AND NOT `item`.`private` AND
2003 `thread`.`network` IN ('%s', '%s')
2004 ORDER BY `item`.`created` DESC LIMIT %d",
2005 intval($owner["uid"]), intval($owner["id"]),
2006 intval($authorid), dbesc($check_date),
2007 dbesc(NETWORK_OSTATUS), dbesc(NETWORK_DFRN), intval($max_items));
2009 $doc = new DOMDocument('1.0', 'utf-8');
2010 $doc->formatOutput = true;
2012 $root = self::add_header($doc, $owner);
2014 foreach ($items AS $item) {
2015 if (Config::get('system', 'ostatus_debug')) {
2016 $item['body'] .= '🍼';
2018 $entry = self::entry($doc, $item, $owner);
2019 $root->appendChild($entry);
2021 if ($last_update < $item['created']) {
2022 $last_update = $item['created'];
2026 $feeddata = trim($doc->saveXML());
2028 $msg = array('feed' => $feeddata, 'last_update' => $last_update);
2029 Cache::set($cachekey, $msg, CACHE_QUARTER_HOUR);
2031 logger('Feed duration: '.number_format(microtime(true) - $stamp, 3).' - '.$owner_nick.' - '.$previous_created, LOGGER_DEBUG);
2037 * @brief Creates the XML for a salmon message
2039 * @param array $item Data of the item that is to be posted
2040 * @param array $owner Contact data of the poster
2042 * @return string XML for the salmon
2044 public static function salmon($item,$owner) {
2046 $doc = new DOMDocument('1.0', 'utf-8');
2047 $doc->formatOutput = true;
2049 if (Config::get('system', 'ostatus_debug')) {
2050 $item['body'] .= '🐟';
2053 $entry = self::entry($doc, $item, $owner, true);
2055 $doc->appendChild($entry);
2057 return trim($doc->saveXML());