3 * @file include/ostatus.php
7 use Friendica\Core\System;
8 use Friendica\Core\Config;
9 use Friendica\Network\Probe;
10 use Friendica\Util\Lock;
12 require_once 'include/Contact.php';
13 require_once 'include/threads.php';
14 require_once 'include/html2bbcode.php';
15 require_once 'include/bbcode.php';
16 require_once 'include/items.php';
17 require_once 'mod/share.php';
18 require_once 'include/enotify.php';
19 require_once 'include/socgraph.php';
20 require_once 'include/Photo.php';
21 require_once 'include/probe.php';
22 require_once 'include/follow.php';
23 require_once 'include/api.php';
24 require_once 'mod/proxy.php';
25 require_once 'include/xml.php';
26 require_once 'include/cache.php';
29 * @brief This class contain functions for the OStatus protocol
34 private static $itemlist;
35 private static $conv_list = array();
38 * @brief Fetches author data
40 * @param object $xpath The xpath object
41 * @param object $context The xml context of the author details
42 * @param array $importer user record of the importing user
43 * @param array $contact Called by reference, will contain the fetched contact
44 * @param bool $onlyfetch Only fetch the header without updating the contact entries
46 * @return array Array of author related entries for the item
48 private static function fetchauthor($xpath, $context, $importer, &$contact, $onlyfetch) {
51 $author["author-link"] = $xpath->evaluate('atom:author/atom:uri/text()', $context)->item(0)->nodeValue;
52 $author["author-name"] = $xpath->evaluate('atom:author/atom:name/text()', $context)->item(0)->nodeValue;
53 $addr = $xpath->evaluate('atom:author/atom:email/text()', $context)->item(0)->nodeValue;
55 $aliaslink = $author["author-link"];
57 $alternate = $xpath->query("atom:author/atom:link[@rel='alternate']", $context)->item(0)->attributes;
58 if (is_object($alternate)) {
59 foreach ($alternate AS $attributes) {
60 if (($attributes->name == "href") && ($attributes->textContent != "")) {
61 $author["author-link"] = $attributes->textContent;
65 $author["contact-id"] = $contact["id"];
69 if ($aliaslink != '') {
70 $condition = array("`uid` = ? AND `alias` = ? AND `network` != ?",
71 $importer["uid"], $aliaslink, NETWORK_STATUSNET);
72 $r = dba::select('contact', array(), $condition, array('limit' => 1));
74 if (dbm::is_result($r)) {
80 $author["contact-id"] = $r["id"];
84 if (!$found && ($author["author-link"] != "")) {
85 if ($aliaslink == "") {
86 $aliaslink = $author["author-link"];
89 $condition = array("`uid` = ? AND `nurl` IN (?, ?) AND `network` != ?", $importer["uid"],
90 normalise_link($author["author-link"]), normalise_link($aliaslink), NETWORK_STATUSNET);
91 $r = dba::select('contact', array(), $condition, array('limit' => 1));
93 if (dbm::is_result($r)) {
99 $author["contact-id"] = $r["id"];
103 if (!$found && ($addr != "")) {
104 $condition = array("`uid` = ? AND `addr` = ? AND `network` != ?",
105 $importer["uid"], $addr, NETWORK_STATUSNET);
106 $r = dba::select('contact', array(), $condition, array('limit' => 1));
108 if (dbm::is_result($r)) {
114 $author["contact-id"] = $r["id"];
118 $avatarlist = array();
119 $avatars = $xpath->query("atom:author/atom:link[@rel='avatar']", $context);
120 foreach ($avatars AS $avatar) {
123 foreach ($avatar->attributes AS $attributes) {
124 if ($attributes->name == "href") {
125 $href = $attributes->textContent;
127 if ($attributes->name == "width") {
128 $width = $attributes->textContent;
132 $avatarlist[$width] = $href;
135 if (count($avatarlist) > 0) {
137 $author["author-avatar"] = Probe::fixAvatar(current($avatarlist), $author["author-link"]);
140 $displayname = $xpath->evaluate('atom:author/poco:displayName/text()', $context)->item(0)->nodeValue;
141 if ($displayname != "") {
142 $author["author-name"] = $displayname;
145 $author["owner-name"] = $author["author-name"];
146 $author["owner-link"] = $author["author-link"];
147 $author["owner-avatar"] = $author["author-avatar"];
149 // Only update the contacts if it is an OStatus contact
150 if ($r && ($r['id'] > 0) && !$onlyfetch && ($contact["network"] == NETWORK_OSTATUS)) {
152 // This contact is vital, so we awake it from the dead
153 unmark_for_death($contact);
155 // Update contact data
158 unset($current['name-date']);
160 // This query doesn't seem to work
161 // $value = $xpath->query("atom:link[@rel='salmon']", $context)->item(0)->nodeValue;
163 // $contact["notify"] = $value;
165 // This query doesn't seem to work as well - I hate these queries
166 // $value = $xpath->query("atom:link[@rel='self' and @type='application/atom+xml']", $context)->item(0)->nodeValue;
168 // $contact["poll"] = $value;
170 $contact['url'] = $author["author-link"];
171 $contact['nurl'] = normalise_link($contact['url']);
173 $value = $xpath->evaluate('atom:author/atom:uri/text()', $context)->item(0)->nodeValue;
175 $contact["alias"] = $value;
177 $value = $xpath->evaluate('atom:author/poco:displayName/text()', $context)->item(0)->nodeValue;
179 $contact["name"] = $value;
181 $value = $xpath->evaluate('atom:author/poco:preferredUsername/text()', $context)->item(0)->nodeValue;
183 $contact["nick"] = $value;
185 $value = $xpath->evaluate('atom:author/poco:note/text()', $context)->item(0)->nodeValue;
187 $contact["about"] = html2bbcode($value);
189 $value = $xpath->evaluate('atom:author/poco:address/poco:formatted/text()', $context)->item(0)->nodeValue;
191 $contact["location"] = $value;
193 $contact['name-date'] = datetime_convert();
195 dba::update('contact', $contact, array('id' => $contact["id"]), $current);
197 if (!empty($author["author-avatar"]) && ($author["author-avatar"] != $current['avatar'])) {
198 logger("Update profile picture for contact ".$contact["id"], LOGGER_DEBUG);
199 update_contact_avatar($author["author-avatar"], $importer["uid"], $contact["id"]);
202 // Ensure that we are having this contact (with uid=0)
203 $cid = get_contact($aliaslink, 0);
206 $fields = array('url', 'nurl', 'name', 'nick', 'alias', 'about', 'location');
207 $old_contact = dba::select('contact', $fields, array('id' => $cid), array('limit' => 1));
209 // Update it with the current values
210 $fields = array('url' => $author["author-link"], 'name' => $contact["name"],
211 'nurl' => normalise_link($author["author-link"]),
212 'nick' => $contact["nick"], 'alias' => $contact["alias"],
213 'about' => $contact["about"], 'location' => $contact["location"],
214 'success_update' => datetime_convert(), 'last-update' => datetime_convert());
216 dba::update('contact', $fields, array('id' => $cid), $old_contact);
219 update_contact_avatar($author["author-avatar"], 0, $cid);
222 $contact["generation"] = 2;
223 $contact["hide"] = false; // OStatus contacts are never hidden
224 $contact["photo"] = $author["author-avatar"];
225 $gcid = update_gcontact($contact);
227 link_gcontact($gcid, $contact["uid"], $contact["id"]);
234 * @brief Fetches author data from a given XML string
236 * @param string $xml The XML
237 * @param array $importer user record of the importing user
239 * @return array Array of author related entries for the item
241 public static function salmon_author($xml, $importer) {
246 $doc = new DOMDocument();
247 @$doc->loadXML($xml);
249 $xpath = new DomXPath($doc);
250 $xpath->registerNamespace('atom', NAMESPACE_ATOM1);
251 $xpath->registerNamespace('thr', NAMESPACE_THREAD);
252 $xpath->registerNamespace('georss', NAMESPACE_GEORSS);
253 $xpath->registerNamespace('activity', NAMESPACE_ACTIVITY);
254 $xpath->registerNamespace('media', NAMESPACE_MEDIA);
255 $xpath->registerNamespace('poco', NAMESPACE_POCO);
256 $xpath->registerNamespace('ostatus', NAMESPACE_OSTATUS);
257 $xpath->registerNamespace('statusnet', NAMESPACE_STATUSNET);
259 $entries = $xpath->query('/atom:entry');
261 foreach ($entries AS $entry) {
263 $author = self::fetchauthor($xpath, $entry, $importer, $contact, true);
269 * @brief Read attributes from element
271 * @param object $element Element object
273 * @return array attributes
275 private static function read_attributes($element) {
276 $attribute = array();
278 foreach ($element->attributes AS $attributes) {
279 $attribute[$attributes->name] = $attributes->textContent;
286 * @brief Imports an XML string containing OStatus elements
288 * @param string $xml The XML
289 * @param array $importer user record of the importing user
290 * @param array $contact
291 * @param string $hub Called by reference, returns the fetched hub data
293 public static function import($xml, $importer, &$contact, &$hub) {
294 self::process($xml, $importer, $contact, $hub);
298 * @brief Internal feed processing
300 * @param string $xml The XML
301 * @param array $importer user record of the importing user
302 * @param array $contact
303 * @param string $hub Called by reference, returns the fetched hub data
304 * @param boolean $stored Is the post fresh imported or from the database?
305 * @param boolean $initialize Is it the leading post so that data has to be initialized?
307 * @return boolean Could the XML be processed?
309 private static function process($xml, $importer, &$contact, &$hub, $stored = false, $initialize = true) {
311 self::$itemlist = array();
312 self::$conv_list = array();
315 logger("Import OStatus message", LOGGER_DEBUG);
320 $doc = new DOMDocument();
321 @$doc->loadXML($xml);
323 $xpath = new DomXPath($doc);
324 $xpath->registerNamespace('atom', NAMESPACE_ATOM1);
325 $xpath->registerNamespace('thr', NAMESPACE_THREAD);
326 $xpath->registerNamespace('georss', NAMESPACE_GEORSS);
327 $xpath->registerNamespace('activity', NAMESPACE_ACTIVITY);
328 $xpath->registerNamespace('media', NAMESPACE_MEDIA);
329 $xpath->registerNamespace('poco', NAMESPACE_POCO);
330 $xpath->registerNamespace('ostatus', NAMESPACE_OSTATUS);
331 $xpath->registerNamespace('statusnet', NAMESPACE_STATUSNET);
334 $hub_attributes = $xpath->query("/atom:feed/atom:link[@rel='hub']")->item(0)->attributes;
335 if (is_object($hub_attributes)) {
336 foreach ($hub_attributes AS $hub_attribute) {
337 if ($hub_attribute->name == "href") {
338 $hub = $hub_attribute->textContent;
339 logger("Found hub ".$hub, LOGGER_DEBUG);
345 $header["uid"] = $importer["uid"];
346 $header["network"] = NETWORK_OSTATUS;
347 $header["type"] = "remote";
349 $header["origin"] = 0;
350 $header["gravity"] = GRAVITY_PARENT;
352 $first_child = $doc->firstChild->tagName;
354 if ($first_child == "feed") {
355 $entries = $xpath->query('/atom:feed/atom:entry');
357 $entries = $xpath->query('/atom:entry');
360 if ($entries->length == 1) {
361 // We reformat the XML to make it better readable
362 $doc2 = new DOMDocument();
363 $doc2->loadXML($xml);
364 $doc2->preserveWhiteSpace = false;
365 $doc2->formatOutput = true;
366 $xml2 = $doc2->saveXML();
368 $header["protocol"] = PROTOCOL_OSTATUS_SALMON;
369 $header["source"] = $xml2;
370 } elseif (!$initialize) {
374 // Fetch the first author
375 $authordata = $xpath->query('//author')->item(0);
376 $author = self::fetchauthor($xpath, $authordata, $importer, $contact, $stored);
378 $entry = $xpath->query('/atom:entry');
380 // Reverse the order of the entries
381 $entrylist = array();
383 foreach ($entries AS $entry) {
384 $entrylist[] = $entry;
387 foreach (array_reverse($entrylist) AS $entry) {
389 $authorelement = $xpath->query('/atom:entry/atom:author', $entry);
391 if ($authorelement->length == 0) {
392 $authorelement = $xpath->query('atom:author', $entry);
395 if ($authorelement->length > 0) {
396 $author = self::fetchauthor($xpath, $entry, $importer, $contact, $stored);
399 $value = $xpath->evaluate('atom:author/poco:preferredUsername/text()', $entry)->item(0)->nodeValue;
403 $nickname = $author["author-name"];
406 $item = array_merge($header, $author);
408 $item["uri"] = $xpath->query('atom:id/text()', $entry)->item(0)->nodeValue;
410 $item["verb"] = $xpath->query('activity:verb/text()', $entry)->item(0)->nodeValue;
413 if (in_array($item["verb"], array('qvitter-delete-notice', ACTIVITY_DELETE, 'delete'))) {
414 self::deleteNotice($item);
418 if (in_array($item["verb"], array(NAMESPACE_OSTATUS."/unfavorite", ACTIVITY_UNFAVORITE))) {
419 // Ignore "Unfavorite" message
420 logger("Ignore unfavorite message ".print_r($item, true), LOGGER_DEBUG);
424 // Deletions come with the same uri, so we check for duplicates after processing deletions
425 if (dba::exists('item', array('uid' => $importer["uid"], 'uri' => $item["uri"]))) {
426 logger('Post with URI '.$item["uri"].' already existed for user '.$importer["uid"].'.', LOGGER_DEBUG);
429 logger('Processing post with URI '.$item["uri"].' for user '.$importer["uid"].'.', LOGGER_DEBUG);
432 if ($item["verb"] == ACTIVITY_JOIN) {
433 // ignore "Join" messages
434 logger("Ignore join message ".print_r($item, true), LOGGER_DEBUG);
438 if ($item["verb"] == "http://mastodon.social/schema/1.0/block") {
439 // ignore mastodon "block" messages
440 logger("Ignore block message ".print_r($item, true), LOGGER_DEBUG);
444 if ($item["verb"] == ACTIVITY_FOLLOW) {
445 new_follower($importer, $contact, $item, $nickname);
449 if ($item["verb"] == NAMESPACE_OSTATUS."/unfollow") {
450 lose_follower($importer, $contact, $item, $dummy);
454 if ($item["verb"] == ACTIVITY_FAVORITE) {
455 $orig_uri = $xpath->query("activity:object/atom:id", $entry)->item(0)->nodeValue;
456 logger("Favorite ".$orig_uri." ".print_r($item, true));
458 $item["verb"] = ACTIVITY_LIKE;
459 $item["parent-uri"] = $orig_uri;
460 $item["gravity"] = GRAVITY_LIKE;
463 // http://activitystrea.ms/schema/1.0/rsvp-yes
464 if (!in_array($item["verb"], array(ACTIVITY_POST, ACTIVITY_LIKE, ACTIVITY_SHARE))) {
465 logger("Unhandled verb ".$item["verb"]." ".print_r($item, true), LOGGER_DEBUG);
468 self::processPost($xpath, $entry, $item, $importer);
470 if ($initialize && (count(self::$itemlist) > 0)) {
471 if (self::$itemlist[0]['uri'] == self::$itemlist[0]['parent-uri']) {
472 // We will import it everytime, when it is started by our contacts
473 $valid = !empty(self::$itemlist[0]['contact-id']);
475 // If not, then it depends on this setting
476 $valid = !Config::get('system','ostatus_full_threads');
479 // Never post a thread when the only interaction by our contact was a like
481 $verbs = array(ACTIVITY_POST, ACTIVITY_SHARE);
482 foreach (self::$itemlist AS $item) {
483 if (!empty($item['contact-id']) && in_array($item['verb'], $verbs)) {
489 // But we will only import complete threads
490 $valid = dba::exists('item', array('uid' => $importer["uid"], 'uri' => self::$itemlist[0]['parent-uri']));
494 $default_contact = 0;
495 $key = count(self::$itemlist);
496 for ($key = count(self::$itemlist) - 1; $key >= 0; $key--) {
497 if (empty(self::$itemlist[$key]['contact-id'])) {
498 self::$itemlist[$key]['contact-id'] = $default_contact;
500 $default_contact = $item['contact-id'];
503 foreach (self::$itemlist AS $item) {
504 $found = dba::exists('item', array('uid' => $importer["uid"], 'uri' => $item["uri"]));
506 logger("Item with uri ".$item["uri"]." for user ".$importer["uid"]." already exists.", LOGGER_DEBUG);
507 } elseif ($item['contact-id'] < 0) {
508 logger("Item with uri ".$item["uri"]." is from a blocked contact.", LOGGER_DEBUG);
510 // We are having duplicated entries. Hopefully this solves it.
511 if (Lock::set('ostatus_process_item_store')) {
512 $ret = item_store($item);
513 Lock::remove('ostatus_process_item_store');
514 logger("Item with uri ".$item["uri"]." for user ".$importer["uid"].' stored. Return value: '.$ret);
516 $ret = item_store($item);
517 logger("We couldn't lock - but tried to store the item anyway. Return value is ".$ret);
522 self::$itemlist = array();
524 logger('Processing done for post with URI '.$item["uri"].' for user '.$importer["uid"].'.', LOGGER_DEBUG);
529 private static function deleteNotice($item) {
531 $condition = array('uid' => $item['uid'], 'author-link' => $item['author-link'], 'uri' => $item['uri']);
532 $deleted = dba::select('item', array('id', 'parent-uri'), $condition, array('limit' => 1));
533 if (!dbm::is_result($deleted)) {
534 logger('Item from '.$item['author-link'].' with uri '.$item['uri'].' for user '.$item['uid']." wasn't found. We don't delete it. ");
538 // 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
539 dba::update('item', array('deleted' => true, 'title' => '', 'body' => '',
540 'edited' => datetime_convert(), 'changed' => datetime_convert()),
541 array('id' => $deleted["id"]));
543 delete_thread($deleted["id"], $deleted["parent-uri"]);
545 logger('Deleted item with uri '.$item['uri'].' for user '.$item['uid']);
549 * @brief Processes the XML for a post
551 * @param object $xpath The xpath object
552 * @param object $entry The xml entry that is processed
553 * @param array $item The item array
554 * @param array $importer user record of the importing user
556 private static function processPost($xpath, $entry, &$item, $importer) {
557 $item["body"] = html2bbcode($xpath->query('atom:content/text()', $entry)->item(0)->nodeValue);
558 $item["object-type"] = $xpath->query('activity:object-type/text()', $entry)->item(0)->nodeValue;
559 if (($item["object-type"] == ACTIVITY_OBJ_BOOKMARK) || ($item["object-type"] == ACTIVITY_OBJ_EVENT)) {
560 $item["title"] = $xpath->query('atom:title/text()', $entry)->item(0)->nodeValue;
561 $item["body"] = $xpath->query('atom:summary/text()', $entry)->item(0)->nodeValue;
562 } elseif ($item["object-type"] == ACTIVITY_OBJ_QUESTION) {
563 $item["title"] = $xpath->query('atom:title/text()', $entry)->item(0)->nodeValue;
566 $item["created"] = $xpath->query('atom:published/text()', $entry)->item(0)->nodeValue;
567 $item["edited"] = $xpath->query('atom:updated/text()', $entry)->item(0)->nodeValue;
568 $conversation = $xpath->query('ostatus:conversation/text()', $entry)->item(0)->nodeValue;
569 $item['conversation-uri'] = $conversation;
571 $conv = $xpath->query('ostatus:conversation', $entry);
572 if (is_object($conv->item(0))) {
573 foreach ($conv->item(0)->attributes AS $attributes) {
574 if ($attributes->name == "ref") {
575 $item['conversation-uri'] = $attributes->textContent;
577 if ($attributes->name == "href") {
578 $item['conversation-href'] = $attributes->textContent;
585 $inreplyto = $xpath->query('thr:in-reply-to', $entry);
586 if (is_object($inreplyto->item(0))) {
587 foreach ($inreplyto->item(0)->attributes AS $attributes) {
588 if ($attributes->name == "ref") {
589 $item["parent-uri"] = $attributes->textContent;
591 if ($attributes->name == "href") {
592 $related = $attributes->textContent;
597 $georsspoint = $xpath->query('georss:point', $entry);
598 if (!empty($georsspoint) && ($georsspoint->length > 0)) {
599 $item["coord"] = $georsspoint->item(0)->nodeValue;
602 $categories = $xpath->query('atom:category', $entry);
604 foreach ($categories AS $category) {
605 foreach ($category->attributes AS $attributes) {
606 if ($attributes->name == "term") {
607 $term = $attributes->textContent;
608 if (strlen($item["tag"])) {
611 $item["tag"] .= "#[url=".System::baseUrl()."/search?tag=".$term."]".$term."[/url]";
620 $links = $xpath->query('atom:link', $entry);
622 $link_data = self::processLinks($links, $item);
623 $self = $link_data['self'];
624 $add_body = $link_data['add_body'];
629 $notice_info = $xpath->query('statusnet:notice_info', $entry);
630 if ($notice_info && ($notice_info->length > 0)) {
631 foreach ($notice_info->item(0)->attributes AS $attributes) {
632 if ($attributes->name == "source") {
633 $item["app"] = strip_tags($attributes->textContent);
635 if ($attributes->name == "repeat_of") {
636 $repeat_of = $attributes->textContent;
640 // Is it a repeated post?
641 if (($repeat_of != "") || ($item["verb"] == ACTIVITY_SHARE)) {
642 $link_data = self::processRepeatedItem($xpath, $entry, $item, $importer);
643 if (!empty($link_data['add_body'])) {
644 $add_body .= $link_data['add_body'];
648 $item["body"] .= $add_body;
650 // Only add additional data when there is no picture in the post
651 if (!strstr($item["body"],'[/img]')) {
652 $item["body"] = add_page_info_to_body($item["body"]);
655 // Mastodon Content Warning
656 if (($item["verb"] == ACTIVITY_POST) && $xpath->evaluate('boolean(atom:summary)', $entry)) {
657 $clear_text = $xpath->query('atom:summary/text()', $entry)->item(0)->nodeValue;
659 $item["body"] = html2bbcode($clear_text) . '[spoiler]' . $item["body"] . '[/spoiler]';
662 if (($self != '') && empty($item['protocol'])) {
663 self::fetchSelf($self, $item);
666 if (!empty($item["conversation-href"])) {
667 self::fetchConversation($item['conversation-href'], $item['conversation-uri']);
670 if (isset($item["parent-uri"]) && ($related != '')) {
671 if (!dba::exists('item', array('uid' => $importer["uid"], 'uri' => $item['parent-uri']))) {
672 self::fetchRelated($related, $item["parent-uri"], $importer);
674 logger('Reply with URI '.$item["uri"].' already existed for user '.$importer["uid"].'.', LOGGER_DEBUG);
677 $item["type"] = 'remote-comment';
678 $item["gravity"] = GRAVITY_COMMENT;
680 $item["parent-uri"] = $item["uri"];
683 if (($item['author-link'] != '') && !empty($item['protocol'])) {
684 $item = store_conversation($item);
687 self::$itemlist[] = $item;
691 * @brief Fetch the conversation for posts
693 * @param string $conversation The link to the conversation
694 * @param string $conversation_uri The conversation in "uri" format
696 private static function fetchConversation($conversation, $conversation_uri) {
698 // Ensure that we only store a conversation once in a process
699 if (isset(self::$conv_list[$conversation])) {
703 self::$conv_list[$conversation] = true;
705 $conversation_data = z_fetch_url($conversation, false, $redirects, array('accept_content' => 'application/atom+xml, text/html'));
707 if (!$conversation_data['success']) {
713 if (stristr($conversation_data['header'], 'Content-Type: application/atom+xml')) {
714 $xml = $conversation_data['body'];
718 $doc = new DOMDocument();
719 if (!@$doc->loadHTML($conversation_data['body'])) {
722 $xpath = new DomXPath($doc);
724 $links = $xpath->query('//link');
726 foreach ($links AS $link) {
727 $attribute = ostatus::read_attributes($link);
728 if (($attribute['rel'] == 'alternate') && ($attribute['type'] == 'application/atom+xml')) {
729 $file = $attribute['href'];
733 $conversation_atom = z_fetch_url($attribute['href']);
735 if ($conversation_atom['success']) {
736 $xml = $conversation_atom['body'];
746 self::storeConversation($xml, $conversation, $conversation_uri);
750 * @brief Store a feed in several conversation entries
752 * @param string $xml The feed
754 private static function storeConversation($xml, $conversation = '', $conversation_uri = '') {
755 $doc = new DOMDocument();
756 @$doc->loadXML($xml);
758 $xpath = new DomXPath($doc);
759 $xpath->registerNamespace('atom', NAMESPACE_ATOM1);
760 $xpath->registerNamespace('thr', NAMESPACE_THREAD);
761 $xpath->registerNamespace('ostatus', NAMESPACE_OSTATUS);
763 $entries = $xpath->query('/atom:feed/atom:entry');
765 // Now store the entries
766 foreach ($entries AS $entry) {
767 $doc2 = new DOMDocument();
768 $doc2->preserveWhiteSpace = false;
769 $doc2->formatOutput = true;
771 $conv_data = array();
773 $conv_data['protocol'] = PROTOCOL_SPLITTED_CONV;
774 $conv_data['network'] = NETWORK_OSTATUS;
775 $conv_data['uri'] = $xpath->query('atom:id/text()', $entry)->item(0)->nodeValue;
777 $inreplyto = $xpath->query('thr:in-reply-to', $entry);
778 if (is_object($inreplyto->item(0))) {
779 foreach ($inreplyto->item(0)->attributes AS $attributes) {
780 if ($attributes->name == "ref") {
781 $conv_data['reply-to-uri'] = $attributes->textContent;
786 $conv = $xpath->query('ostatus:conversation/text()', $entry)->item(0)->nodeValue;
787 $conv_data['conversation-uri'] = $conv;
789 $conv = $xpath->query('ostatus:conversation', $entry);
790 if (is_object($conv->item(0))) {
791 foreach ($conv->item(0)->attributes AS $attributes) {
792 if ($attributes->name == "ref") {
793 $conv_data['conversation-uri'] = $attributes->textContent;
795 if ($attributes->name == "href") {
796 $conv_data['conversation-href'] = $attributes->textContent;
801 if ($conversation != '') {
802 $conv_data['conversation-uri'] = $conversation;
805 if ($conversation_uri != '') {
806 $conv_data['conversation-uri'] = $conversation_uri;
809 $entry = $doc2->importNode($entry, true);
811 $doc2->appendChild($entry);
813 $conv_data['source'] = $doc2->saveXML();
815 $condition = array('item-uri' => $conv_data['uri'],'protocol' => PROTOCOL_OSTATUS_FEED);
816 if (dba::exists('conversation', $condition)) {
817 logger('Delete deprecated entry for URI '.$conv_data['uri'], LOGGER_DEBUG);
818 dba::delete('conversation', array('item-uri' => $conv_data['uri']));
821 logger('Store conversation data for uri '.$conv_data['uri'], LOGGER_DEBUG);
822 store_conversation($conv_data);
827 * @brief Fetch the own post so that it can be stored later
828 * @param array $item The item array
830 * We want to store the original data for later processing.
831 * This function is meant for cases where we process a feed with multiple entries.
832 * In that case we need to fetch the single posts here.
834 * @param string $self The link to the self item
836 private static function fetchSelf($self, &$item) {
837 $condition = array('`item-uri` = ? AND `protocol` IN (?, ?)', $self, PROTOCOL_DFRN, PROTOCOL_OSTATUS_SALMON);
838 if (dba::exists('conversation', $condition)) {
839 logger('Conversation '.$item['uri'].' is already stored.', LOGGER_DEBUG);
843 $self_data = z_fetch_url($self);
845 if (!$self_data['success']) {
849 // We reformat the XML to make it better readable
850 $doc = new DOMDocument();
851 $doc->loadXML($self_data['body']);
852 $doc->preserveWhiteSpace = false;
853 $doc->formatOutput = true;
854 $xml = $doc->saveXML();
856 $item["protocol"] = PROTOCOL_OSTATUS_SALMON;
857 $item["source"] = $xml;
859 logger('Conversation '.$item['uri'].' is now fetched.', LOGGER_DEBUG);
863 * @brief Fetch related posts and processes them
865 * @param string $related The link to the related item
866 * @param string $related_uri The related item in "uri" format
867 * @param array $importer user record of the importing user
869 private static function fetchRelated($related, $related_uri, $importer) {
870 $condition = array('`item-uri` = ? AND `protocol` IN (?, ?)', $related_uri, PROTOCOL_DFRN, PROTOCOL_OSTATUS_SALMON);
871 $conversation = dba::select('conversation', array('source', 'protocol'), $condition, array('limit' => 1));
872 if (dbm::is_result($conversation)) {
874 $xml = $conversation['source'];
875 if (self::process($xml, $importer, $contact, $hub, $stored, false)) {
876 logger('Got valid cached XML for URI '.$related_uri, LOGGER_DEBUG);
879 if ($conversation['protocol'] == PROTOCOL_OSTATUS_SALMON) {
880 logger('Delete invalid cached XML for URI '.$related_uri, LOGGER_DEBUG);
881 dba::delete('conversation', array('item-uri' => $related_uri));
886 $related_data = z_fetch_url($related, false, $redirects, array('accept_content' => 'application/atom+xml, text/html'));
888 if (!$related_data['success']) {
894 if (stristr($related_data['header'], 'Content-Type: application/atom+xml')) {
895 logger('Directly fetched XML for URI '.$related_uri, LOGGER_DEBUG);
896 $xml = $related_data['body'];
900 $doc = new DOMDocument();
901 if (!@$doc->loadHTML($related_data['body'])) {
904 $xpath = new DomXPath($doc);
908 $links = $xpath->query('//link');
910 foreach ($links AS $link) {
911 $attribute = self::read_attributes($link);
912 if (($attribute['rel'] == 'alternate') && ($attribute['type'] == 'application/atom+xml')) {
913 $atom_file = $attribute['href'];
916 if ($atom_file != '') {
917 $related_atom = z_fetch_url($atom_file);
919 if ($related_atom['success']) {
920 logger('Fetched XML for URI '.$related_uri, LOGGER_DEBUG);
921 $xml = $related_atom['body'];
927 // Workaround for older GNU Social servers
928 if (($xml == '') && strstr($related, '/notice/')) {
929 $related_atom = z_fetch_url(str_replace('/notice/', '/api/statuses/show/', $related).'.atom');
931 if ($related_atom['success']) {
932 logger('GNU Social workaround to fetch XML for URI '.$related_uri, LOGGER_DEBUG);
933 $xml = $related_atom['body'];
937 // Even more worse workaround for GNU Social ;-)
939 $related_guess = ostatus::convert_href($related_uri);
940 $related_atom = z_fetch_url(str_replace('/notice/', '/api/statuses/show/', $related_guess).'.atom');
942 if ($related_atom['success']) {
943 logger('GNU Social workaround 2 to fetch XML for URI '.$related_uri, LOGGER_DEBUG);
944 $xml = $related_atom['body'];
948 // Finally we take the data that we fetched from "ostatus:conversation"
950 $condition = array('item-uri' => $related_uri, 'protocol' => PROTOCOL_SPLITTED_CONV);
951 $conversation = dba::select('conversation', array('source'), $condition, array('limit' => 1));
952 if (dbm::is_result($conversation)) {
954 logger('Got cached XML from conversation for URI '.$related_uri, LOGGER_DEBUG);
955 $xml = $conversation['source'];
960 self::process($xml, $importer, $contact, $hub, $stored, false);
962 logger("XML couldn't be fetched for URI: ".$related_uri." - href: ".$related, LOGGER_DEBUG);
968 * @brief Processes the XML for a repeated post
970 * @param object $xpath The xpath object
971 * @param object $entry The xml entry that is processed
972 * @param array $item The item array
973 * @param array $importer user record of the importing user
975 * @return array with data from links
977 private static function processRepeatedItem($xpath, $entry, &$item, $importer) {
978 $activityobjects = $xpath->query('activity:object', $entry)->item(0);
980 if (!is_object($activityobjects)) {
984 $link_data = array();
986 $orig_uri = $xpath->query('atom:id/text()', $activityobjects)->item(0)->nodeValue;
988 $links = $xpath->query("atom:link", $activityobjects);
990 $link_data = self::processLinks($links, $item);
993 $orig_body = $xpath->query('atom:content/text()', $activityobjects)->item(0)->nodeValue;
994 $orig_created = $xpath->query('atom:published/text()', $activityobjects)->item(0)->nodeValue;
995 $orig_edited = $xpath->query('atom:updated/text()', $activityobjects)->item(0)->nodeValue;
997 $orig_contact = $contact;
998 $orig_author = self::fetchauthor($xpath, $activityobjects, $importer, $orig_contact, false);
1000 $item["author-name"] = $orig_author["author-name"];
1001 $item["author-link"] = $orig_author["author-link"];
1002 $item["author-avatar"] = $orig_author["author-avatar"];
1004 $item["body"] = html2bbcode($orig_body);
1005 $item["created"] = $orig_created;
1006 $item["edited"] = $orig_edited;
1008 $item["uri"] = $orig_uri;
1010 $item["verb"] = $xpath->query('activity:verb/text()', $activityobjects)->item(0)->nodeValue;
1012 $item["object-type"] = $xpath->query('activity:object-type/text()', $activityobjects)->item(0)->nodeValue;
1014 $inreplyto = $xpath->query('thr:in-reply-to', $activityobjects);
1015 if (is_object($inreplyto->item(0))) {
1016 foreach ($inreplyto->item(0)->attributes AS $attributes) {
1017 if ($attributes->name == "ref") {
1018 $item["parent-uri"] = $attributes->textContent;
1027 * @brief Processes links in the XML
1029 * @param object $links The xml data that contain links
1030 * @param array $item The item array
1032 * @return array with data from the links
1034 private static function processLinks($links, &$item) {
1035 $link_data = array('add_body' => '', 'self' => '');
1037 foreach ($links AS $link) {
1038 $attribute = self::read_attributes($link);
1040 if (($attribute['rel'] != "") && ($attribute['href'] != "")) {
1041 switch ($attribute['rel']) {
1043 $item["plink"] = $attribute['href'];
1044 if (($item["object-type"] == ACTIVITY_OBJ_QUESTION) ||
1045 ($item["object-type"] == ACTIVITY_OBJ_EVENT)) {
1046 $item["body"] .= add_page_info($attribute['href']);
1049 case "ostatus:conversation":
1050 $link_data['conversation'] = $attribute['href'];
1051 $item['conversation-href'] = $link_data['conversation'];
1052 if (!isset($item['conversation-uri'])) {
1053 $item['conversation-uri'] = $item['conversation-href'];
1057 $filetype = strtolower(substr($attribute['type'], 0, strpos($attribute['type'],'/')));
1058 if ($filetype == 'image') {
1059 $link_data['add_body'] .= "\n[img]".$attribute['href'].'[/img]';
1061 if (strlen($item["attach"])) {
1062 $item["attach"] .= ',';
1064 if (!isset($attribute['length'])) {
1065 $attribute['length'] = "0";
1067 $item["attach"] .= '[attach]href="'.$attribute['href'].'" length="'.$attribute['length'].'" type="'.$attribute['type'].'" title="'.$attribute['title'].'"[/attach]';
1071 if ($item["object-type"] != ACTIVITY_OBJ_BOOKMARK) {
1072 if (!isset($item["parent-uri"])) {
1073 $item["parent-uri"] = $attribute['href'];
1075 $link_data['related'] = $attribute['href'];
1077 $item["body"] .= add_page_info($attribute['href']);
1081 if ($item["plink"] == '') {
1082 $item["plink"] = $attribute['href'];
1084 $link_data['self'] = $attribute['href'];
1093 * @brief Create an url out of an uri
1095 * @param string $href URI in the format "parameter1:parameter1:..."
1097 * @return string URL in the format http(s)://....
1099 public static function convert_href($href) {
1100 $elements = explode(":",$href);
1102 if ((count($elements) <= 2) || ($elements[0] != "tag"))
1105 $server = explode(",", $elements[1]);
1106 $conversation = explode("=", $elements[2]);
1108 if ((count($elements) == 4) && ($elements[2] == "post"))
1109 return "http://".$server[0]."/notice/".$elements[3];
1111 if ((count($conversation) != 2) || ($conversation[1] =="")) {
1114 if ($elements[3] == "objectType=thread") {
1115 return "http://".$server[0]."/conversation/".$conversation[1];
1117 return "http://".$server[0]."/notice/".$conversation[1];
1123 * @brief Checks if the current post is a reshare
1125 * @param array $item The item array of thw post
1127 * @return string The guid if the post is a reshare
1129 private static function get_reshared_guid($item) {
1130 $body = trim($item["body"]);
1132 // Skip if it isn't a pure repeated messages
1133 // Does it start with a share?
1134 if (strpos($body, "[share") > 0)
1137 // Does it end with a share?
1138 if (strlen($body) > (strrpos($body, "[/share]") + 8))
1141 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$1",$body);
1142 // Skip if there is no shared message in there
1143 if ($body == $attributes)
1147 preg_match("/guid='(.*?)'/ism", $attributes, $matches);
1148 if ($matches[1] != "")
1149 $guid = $matches[1];
1151 preg_match('/guid="(.*?)"/ism', $attributes, $matches);
1152 if ($matches[1] != "")
1153 $guid = $matches[1];
1159 * @brief Cleans the body of a post if it contains picture links
1161 * @param string $body The body
1163 * @return string The cleaned body
1165 private static function format_picture_post($body) {
1166 $siteinfo = get_attached_data($body);
1168 if (($siteinfo["type"] == "photo")) {
1169 if (isset($siteinfo["preview"]))
1170 $preview = $siteinfo["preview"];
1172 $preview = $siteinfo["image"];
1174 // Is it a remote picture? Then make a smaller preview here
1175 $preview = proxy_url($preview, false, PROXY_SIZE_SMALL);
1177 // Is it a local picture? Then make it smaller here
1178 $preview = str_replace(array("-0.jpg", "-0.png"), array("-2.jpg", "-2.png"), $preview);
1179 $preview = str_replace(array("-1.jpg", "-1.png"), array("-2.jpg", "-2.png"), $preview);
1181 if (isset($siteinfo["url"]))
1182 $url = $siteinfo["url"];
1184 $url = $siteinfo["image"];
1186 $body = trim($siteinfo["text"])." [url]".$url."[/url]\n[img]".$preview."[/img]";
1193 * @brief Adds the header elements to the XML document
1195 * @param object $doc XML document
1196 * @param array $owner Contact data of the poster
1198 * @return object header root element
1200 private static function add_header($doc, $owner) {
1204 $root = $doc->createElementNS(NAMESPACE_ATOM1, 'feed');
1205 $doc->appendChild($root);
1207 $root->setAttribute("xmlns:thr", NAMESPACE_THREAD);
1208 $root->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
1209 $root->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
1210 $root->setAttribute("xmlns:media", NAMESPACE_MEDIA);
1211 $root->setAttribute("xmlns:poco", NAMESPACE_POCO);
1212 $root->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
1213 $root->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
1214 $root->setAttribute("xmlns:mastodon", NAMESPACE_MASTODON);
1216 $attributes = array("uri" => "https://friendi.ca", "version" => FRIENDICA_VERSION."-".DB_UPDATE_VERSION);
1217 xml::add_element($doc, $root, "generator", FRIENDICA_PLATFORM, $attributes);
1218 xml::add_element($doc, $root, "id", System::baseUrl()."/profile/".$owner["nick"]);
1219 xml::add_element($doc, $root, "title", sprintf("%s timeline", $owner["name"]));
1220 xml::add_element($doc, $root, "subtitle", sprintf("Updates from %s on %s", $owner["name"], $a->config["sitename"]));
1221 xml::add_element($doc, $root, "logo", $owner["photo"]);
1222 xml::add_element($doc, $root, "updated", datetime_convert("UTC", "UTC", "now", ATOM_TIME));
1224 $author = self::add_author($doc, $owner);
1225 $root->appendChild($author);
1227 $attributes = array("href" => $owner["url"], "rel" => "alternate", "type" => "text/html");
1228 xml::add_element($doc, $root, "link", "", $attributes);
1230 /// @TODO We have to find out what this is
1231 /// $attributes = array("href" => System::baseUrl()."/sup",
1232 /// "rel" => "http://api.friendfeed.com/2008/03#sup",
1233 /// "type" => "application/json");
1234 /// xml::add_element($doc, $root, "link", "", $attributes);
1236 self::hublinks($doc, $root, $owner["nick"]);
1238 $attributes = array("href" => System::baseUrl()."/salmon/".$owner["nick"], "rel" => "salmon");
1239 xml::add_element($doc, $root, "link", "", $attributes);
1241 $attributes = array("href" => System::baseUrl()."/salmon/".$owner["nick"], "rel" => "http://salmon-protocol.org/ns/salmon-replies");
1242 xml::add_element($doc, $root, "link", "", $attributes);
1244 $attributes = array("href" => System::baseUrl()."/salmon/".$owner["nick"], "rel" => "http://salmon-protocol.org/ns/salmon-mention");
1245 xml::add_element($doc, $root, "link", "", $attributes);
1247 $attributes = array("href" => System::baseUrl()."/api/statuses/user_timeline/".$owner["nick"].".atom",
1248 "rel" => "self", "type" => "application/atom+xml");
1249 xml::add_element($doc, $root, "link", "", $attributes);
1255 * @brief Add the link to the push hubs to the XML document
1257 * @param object $doc XML document
1258 * @param object $root XML root element where the hub links are added
1260 public static function hublinks($doc, $root, $nick) {
1261 $h = System::baseUrl() . '/pubsubhubbub/'.$nick;
1262 xml::add_element($doc, $root, "link", "", array("href" => $h, "rel" => "hub"));
1266 * @brief Adds attachement data to the XML document
1268 * @param object $doc XML document
1269 * @param object $root XML root element where the hub links are added
1270 * @param array $item Data of the item that is to be posted
1272 private static function get_attachment($doc, $root, $item) {
1274 $siteinfo = get_attached_data($item["body"]);
1276 switch ($siteinfo["type"]) {
1278 $imgdata = get_photo_info($siteinfo["image"]);
1279 $attributes = array("rel" => "enclosure",
1280 "href" => $siteinfo["image"],
1281 "type" => $imgdata["mime"],
1282 "length" => intval($imgdata["size"]));
1283 xml::add_element($doc, $root, "link", "", $attributes);
1286 $attributes = array("rel" => "enclosure",
1287 "href" => $siteinfo["url"],
1288 "type" => "text/html; charset=UTF-8",
1290 "title" => $siteinfo["title"]);
1291 xml::add_element($doc, $root, "link", "", $attributes);
1297 if (!Config::get('system', 'ostatus_not_attach_preview') && ($siteinfo["type"] != "photo") && isset($siteinfo["image"])) {
1298 $imgdata = get_photo_info($siteinfo["image"]);
1299 $attributes = array("rel" => "enclosure",
1300 "href" => $siteinfo["image"],
1301 "type" => $imgdata["mime"],
1302 "length" => intval($imgdata["size"]));
1304 xml::add_element($doc, $root, "link", "", $attributes);
1307 $arr = explode('[/attach],', $item['attach']);
1309 foreach ($arr as $r) {
1311 $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"|', $r, $matches);
1313 $attributes = array("rel" => "enclosure",
1314 "href" => $matches[1],
1315 "type" => $matches[3]);
1317 if (intval($matches[2])) {
1318 $attributes["length"] = intval($matches[2]);
1320 if (trim($matches[4]) != "") {
1321 $attributes["title"] = trim($matches[4]);
1323 xml::add_element($doc, $root, "link", "", $attributes);
1330 * @brief Adds the author element to the XML document
1332 * @param object $doc XML document
1333 * @param array $owner Contact data of the poster
1335 * @return object author element
1337 private static function add_author($doc, $owner) {
1339 $r = q("SELECT `homepage`, `publish` FROM `profile` WHERE `uid` = %d AND `is-default` LIMIT 1", intval($owner["uid"]));
1340 if (dbm::is_result($r)) {
1343 $author = $doc->createElement("author");
1344 xml::add_element($doc, $author, "id", $owner["url"]);
1345 xml::add_element($doc, $author, "activity:object-type", ACTIVITY_OBJ_PERSON);
1346 xml::add_element($doc, $author, "uri", $owner["url"]);
1347 xml::add_element($doc, $author, "name", $owner["nick"]);
1348 xml::add_element($doc, $author, "email", $owner["addr"]);
1349 xml::add_element($doc, $author, "summary", bbcode($owner["about"], false, false, 7));
1351 $attributes = array("rel" => "alternate", "type" => "text/html", "href" => $owner["url"]);
1352 xml::add_element($doc, $author, "link", "", $attributes);
1354 $attributes = array(
1356 "type" => "image/jpeg", // To-Do?
1357 "media:width" => 175,
1358 "media:height" => 175,
1359 "href" => $owner["photo"]);
1360 xml::add_element($doc, $author, "link", "", $attributes);
1362 if (isset($owner["thumb"])) {
1363 $attributes = array(
1365 "type" => "image/jpeg", // To-Do?
1366 "media:width" => 80,
1367 "media:height" => 80,
1368 "href" => $owner["thumb"]);
1369 xml::add_element($doc, $author, "link", "", $attributes);
1372 xml::add_element($doc, $author, "poco:preferredUsername", $owner["nick"]);
1373 xml::add_element($doc, $author, "poco:displayName", $owner["name"]);
1374 xml::add_element($doc, $author, "poco:note", bbcode($owner["about"], false, false, 7));
1376 if (trim($owner["location"]) != "") {
1377 $element = $doc->createElement("poco:address");
1378 xml::add_element($doc, $element, "poco:formatted", $owner["location"]);
1379 $author->appendChild($element);
1382 if (trim($profile["homepage"]) != "") {
1383 $urls = $doc->createElement("poco:urls");
1384 xml::add_element($doc, $urls, "poco:type", "homepage");
1385 xml::add_element($doc, $urls, "poco:value", $profile["homepage"]);
1386 xml::add_element($doc, $urls, "poco:primary", "true");
1387 $author->appendChild($urls);
1390 if (count($profile)) {
1391 xml::add_element($doc, $author, "followers", "", array("url" => System::baseUrl()."/viewcontacts/".$owner["nick"]));
1392 xml::add_element($doc, $author, "statusnet:profile_info", "", array("local_id" => $owner["uid"]));
1395 if ($profile["publish"]) {
1396 xml::add_element($doc, $author, "mastodon:scope", "public");
1402 * @TODO Picture attachments should look like this:
1403 * <a href="https://status.pirati.ca/attachment/572819" title="https://status.pirati.ca/file/heluecht-20151202T222602-rd3u49p.gif"
1404 * class="attachment thumbnail" id="attachment-572819" rel="nofollow external">https://status.pirati.ca/attachment/572819</a>
1409 * @brief Returns the given activity if present - otherwise returns the "post" activity
1411 * @param array $item Data of the item that is to be posted
1413 * @return string activity
1415 private static function construct_verb($item) {
1417 return $item['verb'];
1418 return ACTIVITY_POST;
1422 * @brief Returns the given object type if present - otherwise returns the "note" object type
1424 * @param array $item Data of the item that is to be posted
1426 * @return string Object type
1428 private static function construct_objecttype($item) {
1429 if (in_array($item['object-type'], array(ACTIVITY_OBJ_NOTE, ACTIVITY_OBJ_COMMENT)))
1430 return $item['object-type'];
1431 return ACTIVITY_OBJ_NOTE;
1435 * @brief Adds an entry element to the XML document
1437 * @param object $doc XML document
1438 * @param array $item Data of the item that is to be posted
1439 * @param array $owner Contact data of the poster
1440 * @param bool $toplevel
1442 * @return object Entry element
1444 private static function entry($doc, $item, $owner, $toplevel = false) {
1445 $repeated_guid = self::get_reshared_guid($item);
1446 if ($repeated_guid != "")
1447 $xml = self::reshare_entry($doc, $item, $owner, $repeated_guid, $toplevel);
1452 if ($item["verb"] == ACTIVITY_LIKE) {
1453 return self::like_entry($doc, $item, $owner, $toplevel);
1454 } elseif (in_array($item["verb"], array(ACTIVITY_FOLLOW, NAMESPACE_OSTATUS."/unfollow"))) {
1455 return self::follow_entry($doc, $item, $owner, $toplevel);
1457 return self::note_entry($doc, $item, $owner, $toplevel);
1462 * @brief Adds a source entry to the XML document
1464 * @param object $doc XML document
1465 * @param array $contact Array of the contact that is added
1467 * @return object Source element
1469 private static function source_entry($doc, $contact) {
1470 $source = $doc->createElement("source");
1471 xml::add_element($doc, $source, "id", $contact["poll"]);
1472 xml::add_element($doc, $source, "title", $contact["name"]);
1473 xml::add_element($doc, $source, "link", "", array("rel" => "alternate",
1474 "type" => "text/html",
1475 "href" => $contact["alias"]));
1476 xml::add_element($doc, $source, "link", "", array("rel" => "self",
1477 "type" => "application/atom+xml",
1478 "href" => $contact["poll"]));
1479 xml::add_element($doc, $source, "icon", $contact["photo"]);
1480 xml::add_element($doc, $source, "updated", datetime_convert("UTC","UTC",$contact["success_update"]."+00:00",ATOM_TIME));
1486 * @brief Fetches contact data from the contact or the gcontact table
1488 * @param string $url URL of the contact
1489 * @param array $owner Contact data of the poster
1491 * @return array Contact array
1493 private static function contact_entry($url, $owner) {
1495 $r = q("SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` IN (0, %d) ORDER BY `uid` DESC LIMIT 1",
1496 dbesc(normalise_link($url)), intval($owner["uid"]));
1497 if (dbm::is_result($r)) {
1499 $contact["uid"] = -1;
1502 if (!dbm::is_result($r)) {
1503 $r = q("SELECT * FROM `gcontact` WHERE `nurl` = '%s' LIMIT 1",
1504 dbesc(normalise_link($url)));
1505 if (dbm::is_result($r)) {
1507 $contact["uid"] = -1;
1508 $contact["success_update"] = $contact["updated"];
1512 if (!dbm::is_result($r))
1515 if (!isset($contact["poll"])) {
1516 $data = Probe::uri($url);
1517 $contact["poll"] = $data["poll"];
1519 if (!$contact["alias"])
1520 $contact["alias"] = $data["alias"];
1523 if (!isset($contact["alias"]))
1524 $contact["alias"] = $contact["url"];
1530 * @brief Adds an entry element with reshared content
1532 * @param object $doc XML document
1533 * @param array $item Data of the item that is to be posted
1534 * @param array $owner Contact data of the poster
1535 * @param $repeated_guid
1536 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1538 * @return object Entry element
1540 private static function reshare_entry($doc, $item, $owner, $repeated_guid, $toplevel) {
1542 if (($item["id"] != $item["parent"]) && (normalise_link($item["author-link"]) != normalise_link($owner["url"]))) {
1543 logger("OStatus entry is from author ".$owner["url"]." - not from ".$item["author-link"].". Quitting.", LOGGER_DEBUG);
1546 $title = self::entry_header($doc, $entry, $owner, $toplevel);
1548 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' AND NOT `private` AND `network` IN ('%s', '%s', '%s') LIMIT 1",
1549 intval($owner["uid"]), dbesc($repeated_guid),
1550 dbesc(NETWORK_DFRN), dbesc(NETWORK_DIASPORA), dbesc(NETWORK_OSTATUS));
1551 if (dbm::is_result($r)) {
1552 $repeated_item = $r[0];
1556 $contact = self::contact_entry($repeated_item['author-link'], $owner);
1558 $parent_item = (($item['thr-parent']) ? $item['thr-parent'] : $item['parent-uri']);
1560 $title = $owner["nick"]." repeated a notice by ".$contact["nick"];
1562 self::entry_content($doc, $entry, $item, $owner, $title, ACTIVITY_SHARE, false);
1564 $as_object = $doc->createElement("activity:object");
1566 xml::add_element($doc, $as_object, "activity:object-type", NAMESPACE_ACTIVITY_SCHEMA."activity");
1568 self::entry_content($doc, $as_object, $repeated_item, $owner, "", "", false);
1570 $author = self::add_author($doc, $contact);
1571 $as_object->appendChild($author);
1573 $as_object2 = $doc->createElement("activity:object");
1575 xml::add_element($doc, $as_object2, "activity:object-type", self::construct_objecttype($repeated_item));
1577 $title = sprintf("New comment by %s", $contact["nick"]);
1579 self::entry_content($doc, $as_object2, $repeated_item, $owner, $title);
1581 $as_object->appendChild($as_object2);
1583 self::entry_footer($doc, $as_object, $item, $owner, false);
1585 $source = self::source_entry($doc, $contact);
1587 $as_object->appendChild($source);
1589 $entry->appendChild($as_object);
1591 self::entry_footer($doc, $entry, $item, $owner);
1597 * @brief Adds an entry element with a "like"
1599 * @param object $doc XML document
1600 * @param array $item Data of the item that is to be posted
1601 * @param array $owner Contact data of the poster
1602 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1604 * @return object Entry element with "like"
1606 private static function like_entry($doc, $item, $owner, $toplevel) {
1608 if (($item["id"] != $item["parent"]) && (normalise_link($item["author-link"]) != normalise_link($owner["url"]))) {
1609 logger("OStatus entry is from author ".$owner["url"]." - not from ".$item["author-link"].". Quitting.", LOGGER_DEBUG);
1612 $title = self::entry_header($doc, $entry, $owner, $toplevel);
1614 $verb = NAMESPACE_ACTIVITY_SCHEMA."favorite";
1615 self::entry_content($doc, $entry, $item, $owner, "Favorite", $verb, false);
1617 $as_object = $doc->createElement("activity:object");
1619 $parent = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d",
1620 dbesc($item["thr-parent"]), intval($item["uid"]));
1621 $parent_item = (($item['thr-parent']) ? $item['thr-parent'] : $item['parent-uri']);
1623 xml::add_element($doc, $as_object, "activity:object-type", self::construct_objecttype($parent[0]));
1625 self::entry_content($doc, $as_object, $parent[0], $owner, "New entry");
1627 $entry->appendChild($as_object);
1629 self::entry_footer($doc, $entry, $item, $owner);
1635 * @brief Adds the person object element to the XML document
1637 * @param object $doc XML document
1638 * @param array $owner Contact data of the poster
1639 * @param array $contact Contact data of the target
1641 * @return object author element
1643 private static function add_person_object($doc, $owner, $contact) {
1645 $object = $doc->createElement("activity:object");
1646 xml::add_element($doc, $object, "activity:object-type", ACTIVITY_OBJ_PERSON);
1648 if ($contact['network'] == NETWORK_PHANTOM) {
1649 xml::add_element($doc, $object, "id", $contact['url']);
1653 xml::add_element($doc, $object, "id", $contact["alias"]);
1654 xml::add_element($doc, $object, "title", $contact["nick"]);
1656 $attributes = array("rel" => "alternate", "type" => "text/html", "href" => $contact["url"]);
1657 xml::add_element($doc, $object, "link", "", $attributes);
1659 $attributes = array(
1661 "type" => "image/jpeg", // To-Do?
1662 "media:width" => 175,
1663 "media:height" => 175,
1664 "href" => $contact["photo"]);
1665 xml::add_element($doc, $object, "link", "", $attributes);
1667 xml::add_element($doc, $object, "poco:preferredUsername", $contact["nick"]);
1668 xml::add_element($doc, $object, "poco:displayName", $contact["name"]);
1670 if (trim($contact["location"]) != "") {
1671 $element = $doc->createElement("poco:address");
1672 xml::add_element($doc, $element, "poco:formatted", $contact["location"]);
1673 $object->appendChild($element);
1680 * @brief Adds a follow/unfollow entry element
1682 * @param object $doc XML document
1683 * @param array $item Data of the follow/unfollow message
1684 * @param array $owner Contact data of the poster
1685 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1687 * @return object Entry element
1689 private static function follow_entry($doc, $item, $owner, $toplevel) {
1691 $item["id"] = $item["parent"] = 0;
1692 $item["created"] = $item["edited"] = date("c");
1693 $item["private"] = true;
1695 $contact = Probe::uri($item['follow']);
1697 if ($contact['alias'] == '') {
1698 $contact['alias'] = $contact["url"];
1700 $item['follow'] = $contact['alias'];
1703 $r = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `nurl` = '%s'",
1704 intval($owner['uid']), dbesc(normalise_link($contact["url"])));
1706 if (dbm::is_result($r)) {
1707 $connect_id = $r[0]['id'];
1712 if ($item['verb'] == ACTIVITY_FOLLOW) {
1713 $message = t('%s is now following %s.');
1714 $title = t('following');
1715 $action = "subscription";
1717 $message = t('%s stopped following %s.');
1718 $title = t('stopped following');
1719 $action = "unfollow";
1722 $item["uri"] = $item['parent-uri'] = $item['thr-parent'] =
1723 'tag:'.get_app()->get_hostname().
1724 ','.date('Y-m-d').':'.$action.':'.$owner['uid'].
1725 ':person:'.$connect_id.':'.$item['created'];
1727 $item["body"] = sprintf($message, $owner["nick"], $contact["nick"]);
1729 self::entry_header($doc, $entry, $owner, $toplevel);
1731 self::entry_content($doc, $entry, $item, $owner, $title);
1733 $object = self::add_person_object($doc, $owner, $contact);
1734 $entry->appendChild($object);
1736 self::entry_footer($doc, $entry, $item, $owner);
1742 * @brief Adds a regular entry element
1744 * @param object $doc XML document
1745 * @param array $item Data of the item that is to be posted
1746 * @param array $owner Contact data of the poster
1747 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1749 * @return object Entry element
1751 private static function note_entry($doc, $item, $owner, $toplevel) {
1753 if (($item["id"] != $item["parent"]) && (normalise_link($item["author-link"]) != normalise_link($owner["url"]))) {
1754 logger("OStatus entry is from author ".$owner["url"]." - not from ".$item["author-link"].". Quitting.", LOGGER_DEBUG);
1757 $title = self::entry_header($doc, $entry, $owner, $toplevel);
1759 xml::add_element($doc, $entry, "activity:object-type", ACTIVITY_OBJ_NOTE);
1761 self::entry_content($doc, $entry, $item, $owner, $title);
1763 self::entry_footer($doc, $entry, $item, $owner);
1769 * @brief Adds a header element to the XML document
1771 * @param object $doc XML document
1772 * @param object $entry The entry element where the elements are added
1773 * @param array $owner Contact data of the poster
1774 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1776 * @return string The title for the element
1778 private static function entry_header($doc, &$entry, $owner, $toplevel) {
1779 /// @todo Check if this title stuff is really needed (I guess not)
1781 $entry = $doc->createElement("entry");
1782 $title = sprintf("New note by %s", $owner["nick"]);
1784 $entry = $doc->createElementNS(NAMESPACE_ATOM1, "entry");
1786 $entry->setAttribute("xmlns:thr", NAMESPACE_THREAD);
1787 $entry->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
1788 $entry->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
1789 $entry->setAttribute("xmlns:media", NAMESPACE_MEDIA);
1790 $entry->setAttribute("xmlns:poco", NAMESPACE_POCO);
1791 $entry->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
1792 $entry->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
1793 $entry->setAttribute("xmlns:mastodon", NAMESPACE_MASTODON);
1795 $author = self::add_author($doc, $owner);
1796 $entry->appendChild($author);
1798 $title = sprintf("New comment by %s", $owner["nick"]);
1804 * @brief Adds elements to the XML document
1806 * @param object $doc XML document
1807 * @param object $entry Entry element where the content is added
1808 * @param array $item Data of the item that is to be posted
1809 * @param array $owner Contact data of the poster
1810 * @param string $title Title for the post
1811 * @param string $verb The activity verb
1812 * @param bool $complete Add the "status_net" element?
1814 private static function entry_content($doc, $entry, $item, $owner, $title, $verb = "", $complete = true) {
1817 $verb = self::construct_verb($item);
1819 xml::add_element($doc, $entry, "id", $item["uri"]);
1820 xml::add_element($doc, $entry, "title", $title);
1822 $body = self::format_picture_post($item['body']);
1824 if ($item['title'] != "")
1825 $body = "[b]".$item['title']."[/b]\n\n".$body;
1827 $body = bbcode($body, false, false, 7);
1829 xml::add_element($doc, $entry, "content", $body, array("type" => "html"));
1831 xml::add_element($doc, $entry, "link", "", array("rel" => "alternate", "type" => "text/html",
1832 "href" => System::baseUrl()."/display/".$item["guid"]));
1834 if ($complete && ($item["id"] > 0))
1835 xml::add_element($doc, $entry, "status_net", "", array("notice_id" => $item["id"]));
1837 xml::add_element($doc, $entry, "activity:verb", $verb);
1839 xml::add_element($doc, $entry, "published", datetime_convert("UTC","UTC",$item["created"]."+00:00",ATOM_TIME));
1840 xml::add_element($doc, $entry, "updated", datetime_convert("UTC","UTC",$item["edited"]."+00:00",ATOM_TIME));
1844 * @brief Adds the elements at the foot of an entry to the XML document
1846 * @param object $doc XML document
1847 * @param object $entry The entry element where the elements are added
1848 * @param array $item Data of the item that is to be posted
1849 * @param array $owner Contact data of the poster
1852 private static function entry_footer($doc, $entry, $item, $owner, $complete = true) {
1854 $mentioned = array();
1856 if (($item['parent'] != $item['id']) || ($item['parent-uri'] !== $item['uri']) || (($item['thr-parent'] !== '') && ($item['thr-parent'] !== $item['uri']))) {
1857 $parent = q("SELECT `guid`, `author-link`, `owner-link` FROM `item` WHERE `id` = %d", intval($item["parent"]));
1858 $parent_item = (($item['thr-parent']) ? $item['thr-parent'] : $item['parent-uri']);
1860 $thrparent = q("SELECT `guid`, `author-link`, `owner-link`, `plink` FROM `item` WHERE `uid` = %d AND `uri` = '%s'",
1861 intval($owner["uid"]),
1862 dbesc($parent_item));
1864 $mentioned[$thrparent[0]["author-link"]] = $thrparent[0]["author-link"];
1865 $mentioned[$thrparent[0]["owner-link"]] = $thrparent[0]["owner-link"];
1866 $parent_plink = $thrparent[0]["plink"];
1868 $mentioned[$parent[0]["author-link"]] = $parent[0]["author-link"];
1869 $mentioned[$parent[0]["owner-link"]] = $parent[0]["owner-link"];
1870 $parent_plink = System::baseUrl()."/display/".$parent[0]["guid"];
1873 $attributes = array(
1874 "ref" => $parent_item,
1875 "href" => $parent_plink);
1876 xml::add_element($doc, $entry, "thr:in-reply-to", "", $attributes);
1878 $attributes = array(
1880 "href" => $parent_plink);
1881 xml::add_element($doc, $entry, "link", "", $attributes);
1884 if (intval($item["parent"]) > 0) {
1885 $conversation_href = System::baseUrl()."/display/".$owner["nick"]."/".$item["parent"];
1886 $conversation_uri = $conversation_href;
1888 if (isset($parent_item)) {
1889 $r = dba::fetch_first("SELECT `conversation-uri`, `conversation-href` FROM `conversation` WHERE `item-uri` = ?", $parent_item);
1890 if (dbm::is_result($r)) {
1891 if ($r['conversation-uri'] != '') {
1892 $conversation_uri = $r['conversation-uri'];
1894 if ($r['conversation-href'] != '') {
1895 $conversation_href = $r['conversation-href'];
1900 xml::add_element($doc, $entry, "link", "", array("rel" => "ostatus:conversation", "href" => $conversation_href));
1902 $attributes = array(
1903 "href" => $conversation_href,
1904 "local_id" => $item["parent"],
1905 "ref" => $conversation_uri);
1907 xml::add_element($doc, $entry, "ostatus:conversation", $conversation_uri, $attributes);
1910 $tags = item_getfeedtags($item);
1913 foreach ($tags as $t)
1915 $mentioned[$t[1]] = $t[1];
1917 // Make sure that mentions are accepted (GNU Social has problems with mixing HTTP and HTTPS)
1918 $newmentions = array();
1919 foreach ($mentioned AS $mention) {
1920 $newmentions[str_replace("http://", "https://", $mention)] = str_replace("http://", "https://", $mention);
1921 $newmentions[str_replace("https://", "http://", $mention)] = str_replace("https://", "http://", $mention);
1923 $mentioned = $newmentions;
1925 foreach ($mentioned AS $mention) {
1926 $r = q("SELECT `forum`, `prv` FROM `contact` WHERE `uid` = %d AND `nurl` = '%s'",
1927 intval($owner["uid"]),
1928 dbesc(normalise_link($mention)));
1929 if ($r[0]["forum"] || $r[0]["prv"])
1930 xml::add_element($doc, $entry, "link", "", array("rel" => "mentioned",
1931 "ostatus:object-type" => ACTIVITY_OBJ_GROUP,
1932 "href" => $mention));
1934 xml::add_element($doc, $entry, "link", "", array("rel" => "mentioned",
1935 "ostatus:object-type" => ACTIVITY_OBJ_PERSON,
1936 "href" => $mention));
1939 if (!$item["private"]) {
1940 xml::add_element($doc, $entry, "link", "", array("rel" => "ostatus:attention",
1941 "href" => "http://activityschema.org/collection/public"));
1942 xml::add_element($doc, $entry, "link", "", array("rel" => "mentioned",
1943 "ostatus:object-type" => "http://activitystrea.ms/schema/1.0/collection",
1944 "href" => "http://activityschema.org/collection/public"));
1945 xml::add_element($doc, $entry, "mastodon:scope", "public");
1949 foreach ($tags as $t)
1951 xml::add_element($doc, $entry, "category", "", array("term" => $t[2]));
1953 self::get_attachment($doc, $entry, $item);
1955 if ($complete && ($item["id"] > 0)) {
1956 $app = $item["app"];
1960 $attributes = array("local_id" => $item["id"], "source" => $app);
1962 if (isset($parent["id"]))
1963 $attributes["repeat_of"] = $parent["id"];
1965 if ($item["coord"] != "")
1966 xml::add_element($doc, $entry, "georss:point", $item["coord"]);
1968 xml::add_element($doc, $entry, "statusnet:notice_info", "", $attributes);
1973 * @brief Creates the XML feed for a given nickname
1975 * @param App $a The application class
1976 * @param string $owner_nick Nickname of the feed owner
1977 * @param string $last_update Date of the last update
1978 * @param integer $max_items Number of maximum items to fetch
1980 * @return string XML feed
1982 public static function feed(App $a, $owner_nick, &$last_update, $max_items = 300) {
1983 $stamp = microtime(true);
1985 $cachekey = "ostatus:feed:".$owner_nick.":".$last_update;
1987 $previous_created = $last_update;
1989 $result = Cache::get($cachekey);
1990 if (!is_null($result)) {
1991 logger('Feed duration: '.number_format(microtime(true) - $stamp, 3).' - '.$owner_nick.' - '.$previous_created.' (cached)', LOGGER_DEBUG);
1992 $last_update = $result['last_update'];
1993 return $result['feed'];
1996 $r = q("SELECT `contact`.*, `user`.`nickname`, `user`.`timezone`, `user`.`page-flags`
1997 FROM `contact` INNER JOIN `user` ON `user`.`uid` = `contact`.`uid`
1998 WHERE `contact`.`self` AND `user`.`nickname` = '%s' LIMIT 1",
1999 dbesc($owner_nick));
2000 if (!dbm::is_result($r)) {
2006 if (!strlen($last_update)) {
2007 $last_update = 'now -30 days';
2010 $check_date = datetime_convert('UTC','UTC',$last_update,'Y-m-d H:i:s');
2011 $authorid = get_contact($owner["url"], 0);
2013 $items = q("SELECT `item`.*, `item`.`id` AS `item_id` FROM `item` USE INDEX (`uid_contactid_created`)
2014 STRAIGHT_JOIN `thread` ON `thread`.`iid` = `item`.`parent`
2015 WHERE `item`.`uid` = %d AND `item`.`contact-id` = %d AND
2016 `item`.`author-id` = %d AND `item`.`created` > '%s' AND
2017 NOT `item`.`deleted` AND NOT `item`.`private` AND
2018 `thread`.`network` IN ('%s', '%s')
2019 ORDER BY `item`.`created` DESC LIMIT %d",
2020 intval($owner["uid"]), intval($owner["id"]),
2021 intval($authorid), dbesc($check_date),
2022 dbesc(NETWORK_OSTATUS), dbesc(NETWORK_DFRN), intval($max_items));
2024 $doc = new DOMDocument('1.0', 'utf-8');
2025 $doc->formatOutput = true;
2027 $root = self::add_header($doc, $owner);
2029 foreach ($items AS $item) {
2030 if (Config::get('system', 'ostatus_debug')) {
2031 $item['body'] .= '🍼';
2033 $entry = self::entry($doc, $item, $owner);
2034 $root->appendChild($entry);
2036 if ($last_update < $item['created']) {
2037 $last_update = $item['created'];
2041 $feeddata = trim($doc->saveXML());
2043 $msg = array('feed' => $feeddata, 'last_update' => $last_update);
2044 Cache::set($cachekey, $msg, CACHE_QUARTER_HOUR);
2046 logger('Feed duration: '.number_format(microtime(true) - $stamp, 3).' - '.$owner_nick.' - '.$previous_created, LOGGER_DEBUG);
2052 * @brief Creates the XML for a salmon message
2054 * @param array $item Data of the item that is to be posted
2055 * @param array $owner Contact data of the poster
2057 * @return string XML for the salmon
2059 public static function salmon($item,$owner) {
2061 $doc = new DOMDocument('1.0', 'utf-8');
2062 $doc->formatOutput = true;
2064 if (Config::get('system', 'ostatus_debug')) {
2065 $item['body'] .= '🐟';
2068 $entry = self::entry($doc, $item, $owner, true);
2070 $doc->appendChild($entry);
2072 return trim($doc->saveXML());