3 * @file src/Protocol/OStatus.php
5 namespace Friendica\Protocol;
8 use Friendica\Core\Cache;
9 use Friendica\Core\Config;
10 use Friendica\Core\System;
11 use Friendica\Database\DBM;
12 use Friendica\Model\Contact;
13 use Friendica\Model\GContact;
14 use Friendica\Network\Probe;
15 use Friendica\Object\Image;
16 use Friendica\Util\Lock;
17 use Friendica\Util\XML;
22 require_once 'include/dba.php';
23 require_once 'include/threads.php';
24 require_once 'include/html2bbcode.php';
25 require_once 'include/bbcode.php';
26 require_once 'include/items.php';
27 require_once 'mod/share.php';
28 require_once 'include/enotify.php';
29 require_once 'include/api.php';
30 require_once 'mod/proxy.php';
33 * @brief This class contain functions for the OStatus protocol
37 private static $itemlist;
38 private static $conv_list = [];
41 * @brief Fetches author data
43 * @param object $xpath The xpath object
44 * @param object $context The xml context of the author details
45 * @param array $importer user record of the importing user
46 * @param array $contact Called by reference, will contain the fetched contact
47 * @param bool $onlyfetch Only fetch the header without updating the contact entries
49 * @return array Array of author related entries for the item
51 private static function fetchAuthor($xpath, $context, $importer, &$contact, $onlyfetch)
54 $author["author-link"] = $xpath->evaluate('atom:author/atom:uri/text()', $context)->item(0)->nodeValue;
55 $author["author-name"] = $xpath->evaluate('atom:author/atom:name/text()', $context)->item(0)->nodeValue;
56 $addr = $xpath->evaluate('atom:author/atom:email/text()', $context)->item(0)->nodeValue;
58 $aliaslink = $author["author-link"];
60 $alternate = $xpath->query("atom:author/atom:link[@rel='alternate']", $context)->item(0)->attributes;
61 if (is_object($alternate)) {
62 foreach ($alternate as $attributes) {
63 if (($attributes->name == "href") && ($attributes->textContent != "")) {
64 $author["author-link"] = $attributes->textContent;
68 $author["contact-id"] = $contact["id"];
72 if ($aliaslink != '') {
73 $condition = ["`uid` = ? AND `alias` = ? AND `network` != ?",
74 $importer["uid"], $aliaslink, NETWORK_STATUSNET];
75 $r = dba::selectFirst('contact', [], $condition);
77 if (DBM::is_result($r)) {
83 $author["contact-id"] = $r["id"];
87 if (!$found && ($author["author-link"] != "")) {
88 if ($aliaslink == "") {
89 $aliaslink = $author["author-link"];
92 $condition = ["`uid` = ? AND `nurl` IN (?, ?) AND `network` != ?", $importer["uid"],
93 normalise_link($author["author-link"]), normalise_link($aliaslink), NETWORK_STATUSNET];
94 $r = dba::selectFirst('contact', [], $condition);
96 if (DBM::is_result($r)) {
102 $author["contact-id"] = $r["id"];
106 if (!$found && ($addr != "")) {
107 $condition = ["`uid` = ? AND `addr` = ? AND `network` != ?",
108 $importer["uid"], $addr, NETWORK_STATUSNET];
109 $r = dba::selectFirst('contact', [], $condition);
111 if (DBM::is_result($r)) {
117 $author["contact-id"] = $r["id"];
122 $avatars = $xpath->query("atom:author/atom:link[@rel='avatar']", $context);
123 foreach ($avatars as $avatar) {
126 foreach ($avatar->attributes as $attributes) {
127 if ($attributes->name == "href") {
128 $href = $attributes->textContent;
130 if ($attributes->name == "width") {
131 $width = $attributes->textContent;
135 $avatarlist[$width] = $href;
138 if (count($avatarlist) > 0) {
140 $author["author-avatar"] = Probe::fixAvatar(current($avatarlist), $author["author-link"]);
143 $displayname = $xpath->evaluate('atom:author/poco:displayName/text()', $context)->item(0)->nodeValue;
144 if ($displayname != "") {
145 $author["author-name"] = $displayname;
148 $author["owner-name"] = $author["author-name"];
149 $author["owner-link"] = $author["author-link"];
150 $author["owner-avatar"] = $author["author-avatar"];
152 // Only update the contacts if it is an OStatus contact
153 if ($r && ($r['id'] > 0) && !$onlyfetch && ($contact["network"] == NETWORK_OSTATUS)) {
155 // Update contact data
157 unset($current['name-date']);
159 // This query doesn't seem to work
160 // $value = $xpath->query("atom:link[@rel='salmon']", $context)->item(0)->nodeValue;
162 // $contact["notify"] = $value;
164 // This query doesn't seem to work as well - I hate these queries
165 // $value = $xpath->query("atom:link[@rel='self' and @type='application/atom+xml']", $context)->item(0)->nodeValue;
167 // $contact["poll"] = $value;
169 $contact['url'] = $author["author-link"];
170 $contact['nurl'] = normalise_link($contact['url']);
172 $value = $xpath->evaluate('atom:author/atom:uri/text()', $context)->item(0)->nodeValue;
174 $contact["alias"] = $value;
177 $value = $xpath->evaluate('atom:author/poco:displayName/text()', $context)->item(0)->nodeValue;
179 $contact["name"] = $value;
182 $value = $xpath->evaluate('atom:author/poco:preferredUsername/text()', $context)->item(0)->nodeValue;
184 $contact["nick"] = $value;
187 $value = $xpath->evaluate('atom:author/poco:note/text()', $context)->item(0)->nodeValue;
189 $contact["about"] = html2bbcode($value);
192 $value = $xpath->evaluate('atom:author/poco:address/poco:formatted/text()', $context)->item(0)->nodeValue;
194 $contact["location"] = $value;
197 $contact['name-date'] = datetime_convert();
199 dba::update('contact', $contact, ['id' => $contact["id"]], $current);
201 if (!empty($author["author-avatar"]) && ($author["author-avatar"] != $current['avatar'])) {
202 logger("Update profile picture for contact ".$contact["id"], LOGGER_DEBUG);
203 Contact::updateAvatar($author["author-avatar"], $importer["uid"], $contact["id"]);
206 // Ensure that we are having this contact (with uid=0)
207 $cid = Contact::getIdForURL($aliaslink, 0);
210 $fields = ['url', 'nurl', 'name', 'nick', 'alias', 'about', 'location'];
211 $old_contact = dba::selectFirst('contact', $fields, ['id' => $cid]);
213 // Update it with the current values
214 $fields = ['url' => $author["author-link"], 'name' => $contact["name"],
215 'nurl' => normalise_link($author["author-link"]),
216 'nick' => $contact["nick"], 'alias' => $contact["alias"],
217 'about' => $contact["about"], 'location' => $contact["location"],
218 'success_update' => datetime_convert(), 'last-update' => datetime_convert()];
220 dba::update('contact', $fields, ['id' => $cid], $old_contact);
223 Contact::updateAvatar($author["author-avatar"], 0, $cid);
226 $contact["generation"] = 2;
227 $contact["hide"] = false; // OStatus contacts are never hidden
228 $contact["photo"] = $author["author-avatar"];
229 $gcid = GContact::update($contact);
231 GContact::link($gcid, $contact["uid"], $contact["id"]);
238 * @brief Fetches author data from a given XML string
240 * @param string $xml The XML
241 * @param array $importer user record of the importing user
243 * @return array Array of author related entries for the item
245 public static function salmonAuthor($xml, $importer)
251 $doc = new DOMDocument();
252 @$doc->loadXML($xml);
254 $xpath = new DOMXPath($doc);
255 $xpath->registerNamespace('atom', NAMESPACE_ATOM1);
256 $xpath->registerNamespace('thr', NAMESPACE_THREAD);
257 $xpath->registerNamespace('georss', NAMESPACE_GEORSS);
258 $xpath->registerNamespace('activity', NAMESPACE_ACTIVITY);
259 $xpath->registerNamespace('media', NAMESPACE_MEDIA);
260 $xpath->registerNamespace('poco', NAMESPACE_POCO);
261 $xpath->registerNamespace('ostatus', NAMESPACE_OSTATUS);
262 $xpath->registerNamespace('statusnet', NAMESPACE_STATUSNET);
264 $entries = $xpath->query('/atom:entry');
266 foreach ($entries as $entry) {
268 $author = self::fetchAuthor($xpath, $entry, $importer, $contact, true);
274 * @brief Read attributes from element
276 * @param object $element Element object
278 * @return array attributes
280 private static function readAttributes($element)
284 foreach ($element->attributes as $attributes) {
285 $attribute[$attributes->name] = $attributes->textContent;
292 * @brief Imports an XML string containing OStatus elements
294 * @param string $xml The XML
295 * @param array $importer user record of the importing user
296 * @param array $contact contact
297 * @param string $hub Called by reference, returns the fetched hub data
300 public static function import($xml, $importer, &$contact, &$hub)
302 self::process($xml, $importer, $contact, $hub);
306 * @brief Internal feed processing
308 * @param string $xml The XML
309 * @param array $importer user record of the importing user
310 * @param array $contact contact
311 * @param string $hub Called by reference, returns the fetched hub data
312 * @param boolean $stored Is the post fresh imported or from the database?
313 * @param boolean $initialize Is it the leading post so that data has to be initialized?
315 * @return boolean Could the XML be processed?
317 private static function process($xml, $importer, &$contact, &$hub, $stored = false, $initialize = true)
320 self::$itemlist = [];
321 self::$conv_list = [];
324 logger("Import OStatus message", LOGGER_DEBUG);
329 $doc = new DOMDocument();
330 @$doc->loadXML($xml);
332 $xpath = new DOMXPath($doc);
333 $xpath->registerNamespace('atom', NAMESPACE_ATOM1);
334 $xpath->registerNamespace('thr', NAMESPACE_THREAD);
335 $xpath->registerNamespace('georss', NAMESPACE_GEORSS);
336 $xpath->registerNamespace('activity', NAMESPACE_ACTIVITY);
337 $xpath->registerNamespace('media', NAMESPACE_MEDIA);
338 $xpath->registerNamespace('poco', NAMESPACE_POCO);
339 $xpath->registerNamespace('ostatus', NAMESPACE_OSTATUS);
340 $xpath->registerNamespace('statusnet', NAMESPACE_STATUSNET);
343 $hub_attributes = $xpath->query("/atom:feed/atom:link[@rel='hub']")->item(0)->attributes;
344 if (is_object($hub_attributes)) {
345 foreach ($hub_attributes as $hub_attribute) {
346 if ($hub_attribute->name == "href") {
347 $hub = $hub_attribute->textContent;
348 logger("Found hub ".$hub, LOGGER_DEBUG);
354 $header["uid"] = $importer["uid"];
355 $header["network"] = NETWORK_OSTATUS;
356 $header["type"] = "remote";
358 $header["origin"] = 0;
359 $header["gravity"] = GRAVITY_PARENT;
361 $first_child = $doc->firstChild->tagName;
363 if ($first_child == "feed") {
364 $entries = $xpath->query('/atom:feed/atom:entry');
366 $entries = $xpath->query('/atom:entry');
369 if ($entries->length == 1) {
370 // We reformat the XML to make it better readable
371 $doc2 = new DOMDocument();
372 $doc2->loadXML($xml);
373 $doc2->preserveWhiteSpace = false;
374 $doc2->formatOutput = true;
375 $xml2 = $doc2->saveXML();
377 $header["protocol"] = PROTOCOL_OSTATUS_SALMON;
378 $header["source"] = $xml2;
379 } elseif (!$initialize) {
383 // Fetch the first author
384 $authordata = $xpath->query('//author')->item(0);
385 $author = self::fetchAuthor($xpath, $authordata, $importer, $contact, $stored);
387 $entry = $xpath->query('/atom:entry');
389 // Reverse the order of the entries
392 foreach ($entries as $entry) {
393 $entrylist[] = $entry;
396 foreach (array_reverse($entrylist) as $entry) {
398 $authorelement = $xpath->query('/atom:entry/atom:author', $entry);
400 if ($authorelement->length == 0) {
401 $authorelement = $xpath->query('atom:author', $entry);
404 if ($authorelement->length > 0) {
405 $author = self::fetchAuthor($xpath, $entry, $importer, $contact, $stored);
408 $value = $xpath->evaluate('atom:author/poco:preferredUsername/text()', $entry)->item(0)->nodeValue;
412 $nickname = $author["author-name"];
415 $item = array_merge($header, $author);
417 $item["uri"] = $xpath->query('atom:id/text()', $entry)->item(0)->nodeValue;
419 $item["verb"] = $xpath->query('activity:verb/text()', $entry)->item(0)->nodeValue;
422 if (in_array($item["verb"], ['qvitter-delete-notice', ACTIVITY_DELETE, 'delete'])) {
423 self::deleteNotice($item);
427 if (in_array($item["verb"], [NAMESPACE_OSTATUS."/unfavorite", ACTIVITY_UNFAVORITE])) {
428 // Ignore "Unfavorite" message
429 logger("Ignore unfavorite message ".print_r($item, true), LOGGER_DEBUG);
433 // Deletions come with the same uri, so we check for duplicates after processing deletions
434 if (dba::exists('item', ['uid' => $importer["uid"], 'uri' => $item["uri"]])) {
435 logger('Post with URI '.$item["uri"].' already existed for user '.$importer["uid"].'.', LOGGER_DEBUG);
438 logger('Processing post with URI '.$item["uri"].' for user '.$importer["uid"].'.', LOGGER_DEBUG);
441 if ($item["verb"] == ACTIVITY_JOIN) {
442 // ignore "Join" messages
443 logger("Ignore join message ".print_r($item, true), LOGGER_DEBUG);
447 if ($item["verb"] == "http://mastodon.social/schema/1.0/block") {
448 // ignore mastodon "block" messages
449 logger("Ignore block message ".print_r($item, true), LOGGER_DEBUG);
453 if ($item["verb"] == ACTIVITY_FOLLOW) {
454 new_follower($importer, $contact, $item, $nickname);
458 if ($item["verb"] == NAMESPACE_OSTATUS."/unfollow") {
459 lose_follower($importer, $contact, $item, $dummy);
463 if ($item["verb"] == ACTIVITY_FAVORITE) {
464 $orig_uri = $xpath->query("activity:object/atom:id", $entry)->item(0)->nodeValue;
465 logger("Favorite ".$orig_uri." ".print_r($item, true));
467 $item["verb"] = ACTIVITY_LIKE;
468 $item["parent-uri"] = $orig_uri;
469 $item["gravity"] = GRAVITY_LIKE;
472 // http://activitystrea.ms/schema/1.0/rsvp-yes
473 if (!in_array($item["verb"], [ACTIVITY_POST, ACTIVITY_LIKE, ACTIVITY_SHARE])) {
474 logger("Unhandled verb ".$item["verb"]." ".print_r($item, true), LOGGER_DEBUG);
477 self::processPost($xpath, $entry, $item, $importer);
479 if ($initialize && (count(self::$itemlist) > 0)) {
480 if (self::$itemlist[0]['uri'] == self::$itemlist[0]['parent-uri']) {
481 // We will import it everytime, when it is started by our contacts
482 $valid = !empty(self::$itemlist[0]['contact-id']);
484 // If not, then it depends on this setting
485 $valid = !Config::get('system', 'ostatus_full_threads');
488 // Never post a thread when the only interaction by our contact was a like
490 $verbs = [ACTIVITY_POST, ACTIVITY_SHARE];
491 foreach (self::$itemlist as $item) {
492 if (!empty($item['contact-id']) && in_array($item['verb'], $verbs)) {
498 // But we will only import complete threads
499 $valid = dba::exists('item', ['uid' => $importer["uid"], 'uri' => self::$itemlist[0]['parent-uri']]);
503 $default_contact = 0;
504 $key = count(self::$itemlist);
505 for ($key = count(self::$itemlist) - 1; $key >= 0; $key--) {
506 if (empty(self::$itemlist[$key]['contact-id'])) {
507 self::$itemlist[$key]['contact-id'] = $default_contact;
509 $default_contact = $item['contact-id'];
512 foreach (self::$itemlist as $item) {
513 $found = dba::exists('item', ['uid' => $importer["uid"], 'uri' => $item["uri"]]);
515 logger("Item with uri ".$item["uri"]." for user ".$importer["uid"]." already exists.", LOGGER_DEBUG);
516 } elseif ($item['contact-id'] < 0) {
517 logger("Item with uri ".$item["uri"]." is from a blocked contact.", LOGGER_DEBUG);
519 // We are having duplicated entries. Hopefully this solves it.
520 if (Lock::set('ostatus_process_item_store')) {
521 $ret = item_store($item);
522 Lock::remove('ostatus_process_item_store');
523 logger("Item with uri ".$item["uri"]." for user ".$importer["uid"].' stored. Return value: '.$ret);
525 $ret = item_store($item);
526 logger("We couldn't lock - but tried to store the item anyway. Return value is ".$ret);
531 self::$itemlist = [];
533 logger('Processing done for post with URI '.$item["uri"].' for user '.$importer["uid"].'.', LOGGER_DEBUG);
539 * @param object $item item
542 private static function deleteNotice($item)
544 $condition = ['uid' => $item['uid'], 'author-link' => $item['author-link'], 'uri' => $item['uri']];
545 $deleted = dba::selectFirst('item', ['id', 'parent-uri'], $condition);
546 if (!DBM::is_result($deleted)) {
547 logger('Item from '.$item['author-link'].' with uri '.$item['uri'].' for user '.$item['uid']." wasn't found. We don't delete it. ");
551 // Currently we don't have a central deletion function that we could use in this case
552 // The function "item_drop" doesn't work for that case
555 ['deleted' => true, 'title' => '', 'body' => '',
556 'edited' => datetime_convert(), 'changed' => datetime_convert()],
557 ['id' => $deleted["id"]]
560 delete_thread($deleted["id"], $deleted["parent-uri"]);
562 logger('Deleted item with uri '.$item['uri'].' for user '.$item['uid']);
566 * @brief Processes the XML for a post
568 * @param object $xpath The xpath object
569 * @param object $entry The xml entry that is processed
570 * @param array $item The item array
571 * @param array $importer user record of the importing user
574 private static function processPost($xpath, $entry, &$item, $importer)
576 $item["body"] = html2bbcode($xpath->query('atom:content/text()', $entry)->item(0)->nodeValue);
577 $item["object-type"] = $xpath->query('activity:object-type/text()', $entry)->item(0)->nodeValue;
578 if (($item["object-type"] == ACTIVITY_OBJ_BOOKMARK) || ($item["object-type"] == ACTIVITY_OBJ_EVENT)) {
579 $item["title"] = $xpath->query('atom:title/text()', $entry)->item(0)->nodeValue;
580 $item["body"] = $xpath->query('atom:summary/text()', $entry)->item(0)->nodeValue;
581 } elseif ($item["object-type"] == ACTIVITY_OBJ_QUESTION) {
582 $item["title"] = $xpath->query('atom:title/text()', $entry)->item(0)->nodeValue;
585 $item["created"] = $xpath->query('atom:published/text()', $entry)->item(0)->nodeValue;
586 $item["edited"] = $xpath->query('atom:updated/text()', $entry)->item(0)->nodeValue;
587 $conversation = $xpath->query('ostatus:conversation/text()', $entry)->item(0)->nodeValue;
588 $item['conversation-uri'] = $conversation;
590 $conv = $xpath->query('ostatus:conversation', $entry);
591 if (is_object($conv->item(0))) {
592 foreach ($conv->item(0)->attributes as $attributes) {
593 if ($attributes->name == "ref") {
594 $item['conversation-uri'] = $attributes->textContent;
596 if ($attributes->name == "href") {
597 $item['conversation-href'] = $attributes->textContent;
604 $inreplyto = $xpath->query('thr:in-reply-to', $entry);
605 if (is_object($inreplyto->item(0))) {
606 foreach ($inreplyto->item(0)->attributes as $attributes) {
607 if ($attributes->name == "ref") {
608 $item["parent-uri"] = $attributes->textContent;
610 if ($attributes->name == "href") {
611 $related = $attributes->textContent;
616 $georsspoint = $xpath->query('georss:point', $entry);
617 if (!empty($georsspoint) && ($georsspoint->length > 0)) {
618 $item["coord"] = $georsspoint->item(0)->nodeValue;
621 $categories = $xpath->query('atom:category', $entry);
623 foreach ($categories as $category) {
624 foreach ($category->attributes as $attributes) {
625 if ($attributes->name == "term") {
626 $term = $attributes->textContent;
627 if (strlen($item["tag"])) {
630 $item["tag"] .= "#[url=".System::baseUrl()."/search?tag=".$term."]".$term."[/url]";
639 $links = $xpath->query('atom:link', $entry);
641 $link_data = self::processLinks($links, $item);
642 $self = $link_data['self'];
643 $add_body = $link_data['add_body'];
648 $notice_info = $xpath->query('statusnet:notice_info', $entry);
649 if ($notice_info && ($notice_info->length > 0)) {
650 foreach ($notice_info->item(0)->attributes as $attributes) {
651 if ($attributes->name == "source") {
652 $item["app"] = strip_tags($attributes->textContent);
654 if ($attributes->name == "repeat_of") {
655 $repeat_of = $attributes->textContent;
659 // Is it a repeated post?
660 if (($repeat_of != "") || ($item["verb"] == ACTIVITY_SHARE)) {
661 $link_data = self::processRepeatedItem($xpath, $entry, $item, $importer);
662 if (!empty($link_data['add_body'])) {
663 $add_body .= $link_data['add_body'];
667 $item["body"] .= $add_body;
669 // Only add additional data when there is no picture in the post
670 if (!strstr($item["body"], '[/img]')) {
671 $item["body"] = add_page_info_to_body($item["body"]);
674 // Mastodon Content Warning
675 if (($item["verb"] == ACTIVITY_POST) && $xpath->evaluate('boolean(atom:summary)', $entry)) {
676 $clear_text = $xpath->query('atom:summary/text()', $entry)->item(0)->nodeValue;
678 $item["body"] = html2bbcode($clear_text) . '[spoiler]' . $item["body"] . '[/spoiler]';
681 if (($self != '') && empty($item['protocol'])) {
682 self::fetchSelf($self, $item);
685 if (!empty($item["conversation-href"])) {
686 self::fetchConversation($item['conversation-href'], $item['conversation-uri']);
689 if (isset($item["parent-uri"]) && ($related != '')) {
690 if (!dba::exists('item', ['uid' => $importer["uid"], 'uri' => $item['parent-uri']])) {
691 self::fetchRelated($related, $item["parent-uri"], $importer);
693 logger('Reply with URI '.$item["uri"].' already existed for user '.$importer["uid"].'.', LOGGER_DEBUG);
696 $item["type"] = 'remote-comment';
697 $item["gravity"] = GRAVITY_COMMENT;
699 $item["parent-uri"] = $item["uri"];
702 if (($item['author-link'] != '') && !empty($item['protocol'])) {
703 $item = store_conversation($item);
706 self::$itemlist[] = $item;
710 * @brief Fetch the conversation for posts
712 * @param string $conversation The link to the conversation
713 * @param string $conversation_uri The conversation in "uri" format
716 private static function fetchConversation($conversation, $conversation_uri)
718 // Ensure that we only store a conversation once in a process
719 if (isset(self::$conv_list[$conversation])) {
723 self::$conv_list[$conversation] = true;
725 $conversation_data = z_fetch_url($conversation, false, $redirects, ['accept_content' => 'application/atom+xml, text/html']);
727 if (!$conversation_data['success']) {
733 if (stristr($conversation_data['header'], 'Content-Type: application/atom+xml')) {
734 $xml = $conversation_data['body'];
738 $doc = new DOMDocument();
739 if (!@$doc->loadHTML($conversation_data['body'])) {
742 $xpath = new DOMXPath($doc);
744 $links = $xpath->query('//link');
746 foreach ($links as $link) {
747 $attribute = self::readAttributes($link);
748 if (($attribute['rel'] == 'alternate') && ($attribute['type'] == 'application/atom+xml')) {
749 $file = $attribute['href'];
753 $conversation_atom = z_fetch_url($attribute['href']);
755 if ($conversation_atom['success']) {
756 $xml = $conversation_atom['body'];
766 self::storeConversation($xml, $conversation, $conversation_uri);
770 * @brief Store a feed in several conversation entries
772 * @param string $xml The feed
773 * @param string $conversation conversation
774 * @param string $conversation_uri conversation uri
777 private static function storeConversation($xml, $conversation = '', $conversation_uri = '')
779 $doc = new DOMDocument();
780 @$doc->loadXML($xml);
782 $xpath = new DOMXPath($doc);
783 $xpath->registerNamespace('atom', NAMESPACE_ATOM1);
784 $xpath->registerNamespace('thr', NAMESPACE_THREAD);
785 $xpath->registerNamespace('ostatus', NAMESPACE_OSTATUS);
787 $entries = $xpath->query('/atom:feed/atom:entry');
789 // Now store the entries
790 foreach ($entries as $entry) {
791 $doc2 = new DOMDocument();
792 $doc2->preserveWhiteSpace = false;
793 $doc2->formatOutput = true;
797 $conv_data['protocol'] = PROTOCOL_SPLITTED_CONV;
798 $conv_data['network'] = NETWORK_OSTATUS;
799 $conv_data['uri'] = $xpath->query('atom:id/text()', $entry)->item(0)->nodeValue;
801 $inreplyto = $xpath->query('thr:in-reply-to', $entry);
802 if (is_object($inreplyto->item(0))) {
803 foreach ($inreplyto->item(0)->attributes as $attributes) {
804 if ($attributes->name == "ref") {
805 $conv_data['reply-to-uri'] = $attributes->textContent;
810 $conv = $xpath->query('ostatus:conversation/text()', $entry)->item(0)->nodeValue;
811 $conv_data['conversation-uri'] = $conv;
813 $conv = $xpath->query('ostatus:conversation', $entry);
814 if (is_object($conv->item(0))) {
815 foreach ($conv->item(0)->attributes as $attributes) {
816 if ($attributes->name == "ref") {
817 $conv_data['conversation-uri'] = $attributes->textContent;
819 if ($attributes->name == "href") {
820 $conv_data['conversation-href'] = $attributes->textContent;
825 if ($conversation != '') {
826 $conv_data['conversation-uri'] = $conversation;
829 if ($conversation_uri != '') {
830 $conv_data['conversation-uri'] = $conversation_uri;
833 $entry = $doc2->importNode($entry, true);
835 $doc2->appendChild($entry);
837 $conv_data['source'] = $doc2->saveXML();
839 $condition = ['item-uri' => $conv_data['uri'],'protocol' => PROTOCOL_OSTATUS_FEED];
840 if (dba::exists('conversation', $condition)) {
841 logger('Delete deprecated entry for URI '.$conv_data['uri'], LOGGER_DEBUG);
842 dba::delete('conversation', ['item-uri' => $conv_data['uri']]);
845 logger('Store conversation data for uri '.$conv_data['uri'], LOGGER_DEBUG);
846 store_conversation($conv_data);
851 * @brief Fetch the own post so that it can be stored later
853 * We want to store the original data for later processing.
854 * This function is meant for cases where we process a feed with multiple entries.
855 * In that case we need to fetch the single posts here.
857 * @param string $self The link to the self item
858 * @param array $item The item array
861 private static function fetchSelf($self, &$item)
863 $condition = ['`item-uri` = ? AND `protocol` IN (?, ?)', $self, PROTOCOL_DFRN, PROTOCOL_OSTATUS_SALMON];
864 if (dba::exists('conversation', $condition)) {
865 logger('Conversation '.$item['uri'].' is already stored.', LOGGER_DEBUG);
869 $self_data = z_fetch_url($self);
871 if (!$self_data['success']) {
875 // We reformat the XML to make it better readable
876 $doc = new DOMDocument();
877 $doc->loadXML($self_data['body']);
878 $doc->preserveWhiteSpace = false;
879 $doc->formatOutput = true;
880 $xml = $doc->saveXML();
882 $item["protocol"] = PROTOCOL_OSTATUS_SALMON;
883 $item["source"] = $xml;
885 logger('Conversation '.$item['uri'].' is now fetched.', LOGGER_DEBUG);
889 * @brief Fetch related posts and processes them
891 * @param string $related The link to the related item
892 * @param string $related_uri The related item in "uri" format
893 * @param array $importer user record of the importing user
896 private static function fetchRelated($related, $related_uri, $importer)
898 $condition = ['`item-uri` = ? AND `protocol` IN (?, ?)', $related_uri, PROTOCOL_DFRN, PROTOCOL_OSTATUS_SALMON];
899 $conversation = dba::selectFirst('conversation', ['source', 'protocol'], $condition);
900 if (DBM::is_result($conversation)) {
902 $xml = $conversation['source'];
903 if (self::process($xml, $importer, $contact, $hub, $stored, false)) {
904 logger('Got valid cached XML for URI '.$related_uri, LOGGER_DEBUG);
907 if ($conversation['protocol'] == PROTOCOL_OSTATUS_SALMON) {
908 logger('Delete invalid cached XML for URI '.$related_uri, LOGGER_DEBUG);
909 dba::delete('conversation', ['item-uri' => $related_uri]);
914 $related_data = z_fetch_url($related, false, $redirects, ['accept_content' => 'application/atom+xml, text/html']);
916 if (!$related_data['success']) {
922 if (stristr($related_data['header'], 'Content-Type: application/atom+xml')) {
923 logger('Directly fetched XML for URI '.$related_uri, LOGGER_DEBUG);
924 $xml = $related_data['body'];
928 $doc = new DOMDocument();
929 if (!@$doc->loadHTML($related_data['body'])) {
932 $xpath = new DOMXPath($doc);
936 $links = $xpath->query('//link');
938 foreach ($links as $link) {
939 $attribute = self::readAttributes($link);
940 if (($attribute['rel'] == 'alternate') && ($attribute['type'] == 'application/atom+xml')) {
941 $atom_file = $attribute['href'];
944 if ($atom_file != '') {
945 $related_atom = z_fetch_url($atom_file);
947 if ($related_atom['success']) {
948 logger('Fetched XML for URI '.$related_uri, LOGGER_DEBUG);
949 $xml = $related_atom['body'];
955 // Workaround for older GNU Social servers
956 if (($xml == '') && strstr($related, '/notice/')) {
957 $related_atom = z_fetch_url(str_replace('/notice/', '/api/statuses/show/', $related).'.atom');
959 if ($related_atom['success']) {
960 logger('GNU Social workaround to fetch XML for URI '.$related_uri, LOGGER_DEBUG);
961 $xml = $related_atom['body'];
965 // Even more worse workaround for GNU Social ;-)
967 $related_guess = OStatus::convertHref($related_uri);
968 $related_atom = z_fetch_url(str_replace('/notice/', '/api/statuses/show/', $related_guess).'.atom');
970 if ($related_atom['success']) {
971 logger('GNU Social workaround 2 to fetch XML for URI '.$related_uri, LOGGER_DEBUG);
972 $xml = $related_atom['body'];
976 // Finally we take the data that we fetched from "ostatus:conversation"
978 $condition = ['item-uri' => $related_uri, 'protocol' => PROTOCOL_SPLITTED_CONV];
979 $conversation = dba::selectFirst('conversation', ['source'], $condition);
980 if (DBM::is_result($conversation)) {
982 logger('Got cached XML from conversation for URI '.$related_uri, LOGGER_DEBUG);
983 $xml = $conversation['source'];
988 self::process($xml, $importer, $contact, $hub, $stored, false);
990 logger("XML couldn't be fetched for URI: ".$related_uri." - href: ".$related, LOGGER_DEBUG);
996 * @brief Processes the XML for a repeated post
998 * @param object $xpath The xpath object
999 * @param object $entry The xml entry that is processed
1000 * @param array $item The item array
1001 * @param array $importer user record of the importing user
1003 * @return array with data from links
1005 private static function processRepeatedItem($xpath, $entry, &$item, $importer)
1007 $activityobjects = $xpath->query('activity:object', $entry)->item(0);
1009 if (!is_object($activityobjects)) {
1015 $orig_uri = $xpath->query('atom:id/text()', $activityobjects)->item(0)->nodeValue;
1017 $links = $xpath->query("atom:link", $activityobjects);
1019 $link_data = self::processLinks($links, $item);
1022 $orig_body = $xpath->query('atom:content/text()', $activityobjects)->item(0)->nodeValue;
1023 $orig_created = $xpath->query('atom:published/text()', $activityobjects)->item(0)->nodeValue;
1024 $orig_edited = $xpath->query('atom:updated/text()', $activityobjects)->item(0)->nodeValue;
1026 $orig_author = self::fetchAuthor($xpath, $activityobjects, $importer, $dummy, false);
1028 $item["author-name"] = $orig_author["author-name"];
1029 $item["author-link"] = $orig_author["author-link"];
1030 $item["author-avatar"] = $orig_author["author-avatar"];
1032 $item["body"] = html2bbcode($orig_body);
1033 $item["created"] = $orig_created;
1034 $item["edited"] = $orig_edited;
1036 $item["uri"] = $orig_uri;
1038 $item["verb"] = $xpath->query('activity:verb/text()', $activityobjects)->item(0)->nodeValue;
1040 $item["object-type"] = $xpath->query('activity:object-type/text()', $activityobjects)->item(0)->nodeValue;
1042 $inreplyto = $xpath->query('thr:in-reply-to', $activityobjects);
1043 if (is_object($inreplyto->item(0))) {
1044 foreach ($inreplyto->item(0)->attributes as $attributes) {
1045 if ($attributes->name == "ref") {
1046 $item["parent-uri"] = $attributes->textContent;
1055 * @brief Processes links in the XML
1057 * @param object $links The xml data that contain links
1058 * @param array $item The item array
1060 * @return array with data from the links
1062 private static function processLinks($links, &$item)
1064 $link_data = ['add_body' => '', 'self' => ''];
1066 foreach ($links as $link) {
1067 $attribute = self::readAttributes($link);
1069 if (($attribute['rel'] != "") && ($attribute['href'] != "")) {
1070 switch ($attribute['rel']) {
1072 $item["plink"] = $attribute['href'];
1073 if (($item["object-type"] == ACTIVITY_OBJ_QUESTION)
1074 || ($item["object-type"] == ACTIVITY_OBJ_EVENT)
1076 $item["body"] .= add_page_info($attribute['href']);
1079 case "ostatus:conversation":
1080 $link_data['conversation'] = $attribute['href'];
1081 $item['conversation-href'] = $link_data['conversation'];
1082 if (!isset($item['conversation-uri'])) {
1083 $item['conversation-uri'] = $item['conversation-href'];
1087 $filetype = strtolower(substr($attribute['type'], 0, strpos($attribute['type'], '/')));
1088 if ($filetype == 'image') {
1089 $link_data['add_body'] .= "\n[img]".$attribute['href'].'[/img]';
1091 if (strlen($item["attach"])) {
1092 $item["attach"] .= ',';
1094 if (!isset($attribute['length'])) {
1095 $attribute['length'] = "0";
1097 $item["attach"] .= '[attach]href="'.$attribute['href'].'" length="'.$attribute['length'].'" type="'.$attribute['type'].'" title="'.$attribute['title'].'"[/attach]';
1101 if ($item["object-type"] != ACTIVITY_OBJ_BOOKMARK) {
1102 if (!isset($item["parent-uri"])) {
1103 $item["parent-uri"] = $attribute['href'];
1105 $link_data['related'] = $attribute['href'];
1107 $item["body"] .= add_page_info($attribute['href']);
1111 if ($item["plink"] == '') {
1112 $item["plink"] = $attribute['href'];
1114 $link_data['self'] = $attribute['href'];
1123 * @brief Create an url out of an uri
1125 * @param string $href URI in the format "parameter1:parameter1:..."
1127 * @return string URL in the format http(s)://....
1129 public static function convertHref($href)
1131 $elements = explode(":", $href);
1133 if ((count($elements) <= 2) || ($elements[0] != "tag")) {
1137 $server = explode(",", $elements[1]);
1138 $conversation = explode("=", $elements[2]);
1140 if ((count($elements) == 4) && ($elements[2] == "post")) {
1141 return "http://".$server[0]."/notice/".$elements[3];
1144 if ((count($conversation) != 2) || ($conversation[1] =="")) {
1147 if ($elements[3] == "objectType=thread") {
1148 return "http://".$server[0]."/conversation/".$conversation[1];
1150 return "http://".$server[0]."/notice/".$conversation[1];
1156 * @brief Checks if the current post is a reshare
1158 * @param array $item The item array of thw post
1160 * @return string The guid if the post is a reshare
1162 private static function getResharedGuid($item)
1164 $body = trim($item["body"]);
1166 // Skip if it isn't a pure repeated messages
1167 // Does it start with a share?
1168 if (strpos($body, "[share") > 0) {
1172 // Does it end with a share?
1173 if (strlen($body) > (strrpos($body, "[/share]") + 8)) {
1177 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "$1", $body);
1178 // Skip if there is no shared message in there
1179 if ($body == $attributes) {
1184 preg_match("/guid='(.*?)'/ism", $attributes, $matches);
1185 if ($matches[1] != "") {
1186 $guid = $matches[1];
1189 preg_match('/guid="(.*?)"/ism', $attributes, $matches);
1190 if ($matches[1] != "") {
1191 $guid = $matches[1];
1198 * @brief Cleans the body of a post if it contains picture links
1200 * @param string $body The body
1202 * @return string The cleaned body
1204 private static function formatPicturePost($body)
1206 $siteinfo = get_attached_data($body);
1208 if (($siteinfo["type"] == "photo")) {
1209 if (isset($siteinfo["preview"])) {
1210 $preview = $siteinfo["preview"];
1212 $preview = $siteinfo["image"];
1215 // Is it a remote picture? Then make a smaller preview here
1216 $preview = proxy_url($preview, false, PROXY_SIZE_SMALL);
1218 // Is it a local picture? Then make it smaller here
1219 $preview = str_replace(["-0.jpg", "-0.png"], ["-2.jpg", "-2.png"], $preview);
1220 $preview = str_replace(["-1.jpg", "-1.png"], ["-2.jpg", "-2.png"], $preview);
1222 if (isset($siteinfo["url"])) {
1223 $url = $siteinfo["url"];
1225 $url = $siteinfo["image"];
1228 $body = trim($siteinfo["text"])." [url]".$url."[/url]\n[img]".$preview."[/img]";
1235 * @brief Adds the header elements to the XML document
1237 * @param object $doc XML document
1238 * @param array $owner Contact data of the poster
1239 * @param string $filter The related feed filter (activity, posts or comments)
1241 * @return object header root element
1243 private static function addHeader($doc, $owner, $filter)
1247 $root = $doc->createElementNS(NAMESPACE_ATOM1, 'feed');
1248 $doc->appendChild($root);
1250 $root->setAttribute("xmlns:thr", NAMESPACE_THREAD);
1251 $root->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
1252 $root->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
1253 $root->setAttribute("xmlns:media", NAMESPACE_MEDIA);
1254 $root->setAttribute("xmlns:poco", NAMESPACE_POCO);
1255 $root->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
1256 $root->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
1257 $root->setAttribute("xmlns:mastodon", NAMESPACE_MASTODON);
1260 case 'activity': $title = t('%s\'s timeline', $owner['name']); break;
1261 case 'posts' : $title = t('%s\'s posts' , $owner['name']); break;
1262 case 'comments': $title = t('%s\'s comments', $owner['name']); break;
1265 $attributes = ["uri" => "https://friendi.ca", "version" => FRIENDICA_VERSION . "-" . DB_UPDATE_VERSION];
1266 XML::addElement($doc, $root, "generator", FRIENDICA_PLATFORM, $attributes);
1267 XML::addElement($doc, $root, "id", System::baseUrl() . "/profile/" . $owner["nick"]);
1268 XML::addElement($doc, $root, "title", $title);
1269 XML::addElement($doc, $root, "subtitle", sprintf("Updates from %s on %s", $owner["name"], $a->config["sitename"]));
1270 XML::addElement($doc, $root, "logo", $owner["photo"]);
1271 XML::addElement($doc, $root, "updated", datetime_convert("UTC", "UTC", "now", ATOM_TIME));
1273 $author = self::addAuthor($doc, $owner);
1274 $root->appendChild($author);
1276 $attributes = ["href" => $owner["url"], "rel" => "alternate", "type" => "text/html"];
1277 XML::addElement($doc, $root, "link", "", $attributes);
1279 /// @TODO We have to find out what this is
1280 /// $attributes = array("href" => System::baseUrl()."/sup",
1281 /// "rel" => "http://api.friendfeed.com/2008/03#sup",
1282 /// "type" => "application/json");
1283 /// XML::addElement($doc, $root, "link", "", $attributes);
1285 self::hublinks($doc, $root, $owner["nick"]);
1287 $attributes = ["href" => System::baseUrl() . "/salmon/" . $owner["nick"], "rel" => "salmon"];
1288 XML::addElement($doc, $root, "link", "", $attributes);
1290 $attributes = ["href" => System::baseUrl() . "/salmon/" . $owner["nick"], "rel" => "http://salmon-protocol.org/ns/salmon-replies"];
1291 XML::addElement($doc, $root, "link", "", $attributes);
1293 $attributes = ["href" => System::baseUrl() . "/salmon/" . $owner["nick"], "rel" => "http://salmon-protocol.org/ns/salmon-mention"];
1294 XML::addElement($doc, $root, "link", "", $attributes);
1296 $attributes = ["href" => System::baseUrl() . "/api/statuses/user_timeline/" . $owner["nick"] . ".atom",
1297 "rel" => "self", "type" => "application/atom+xml"];
1298 XML::addElement($doc, $root, "link", "", $attributes);
1304 * @brief Add the link to the push hubs to the XML document
1306 * @param object $doc XML document
1307 * @param object $root XML root element where the hub links are added
1308 * @param object $nick nick
1311 public static function hublinks($doc, $root, $nick)
1313 $h = System::baseUrl() . '/pubsubhubbub/'.$nick;
1314 XML::addElement($doc, $root, "link", "", ["href" => $h, "rel" => "hub"]);
1318 * @brief Adds attachement data to the XML document
1320 * @param object $doc XML document
1321 * @param object $root XML root element where the hub links are added
1322 * @param array $item Data of the item that is to be posted
1325 private static function getAttachment($doc, $root, $item)
1328 $siteinfo = get_attached_data($item["body"]);
1330 switch ($siteinfo["type"]) {
1332 $imgdata = Image::getInfoFromURL($siteinfo["image"]);
1333 $attributes = ["rel" => "enclosure",
1334 "href" => $siteinfo["image"],
1335 "type" => $imgdata["mime"],
1336 "length" => intval($imgdata["size"])];
1337 XML::addElement($doc, $root, "link", "", $attributes);
1340 $attributes = ["rel" => "enclosure",
1341 "href" => $siteinfo["url"],
1342 "type" => "text/html; charset=UTF-8",
1344 "title" => $siteinfo["title"]];
1345 XML::addElement($doc, $root, "link", "", $attributes);
1351 if (!Config::get('system', 'ostatus_not_attach_preview') && ($siteinfo["type"] != "photo") && isset($siteinfo["image"])) {
1352 $imgdata = Image::getInfoFromURL($siteinfo["image"]);
1353 $attributes = ["rel" => "enclosure",
1354 "href" => $siteinfo["image"],
1355 "type" => $imgdata["mime"],
1356 "length" => intval($imgdata["size"])];
1358 XML::addElement($doc, $root, "link", "", $attributes);
1361 $arr = explode('[/attach],', $item['attach']);
1363 foreach ($arr as $r) {
1365 $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"|', $r, $matches);
1367 $attributes = ["rel" => "enclosure",
1368 "href" => $matches[1],
1369 "type" => $matches[3]];
1371 if (intval($matches[2])) {
1372 $attributes["length"] = intval($matches[2]);
1374 if (trim($matches[4]) != "") {
1375 $attributes["title"] = trim($matches[4]);
1377 XML::addElement($doc, $root, "link", "", $attributes);
1384 * @brief Adds the author element to the XML document
1386 * @param object $doc XML document
1387 * @param array $owner Contact data of the poster
1389 * @return object author element
1391 private static function addAuthor($doc, $owner)
1393 $r = q("SELECT `homepage`, `publish` FROM `profile` WHERE `uid` = %d AND `is-default` LIMIT 1", intval($owner["uid"]));
1394 if (DBM::is_result($r)) {
1397 $author = $doc->createElement("author");
1398 XML::addElement($doc, $author, "id", $owner["url"]);
1399 XML::addElement($doc, $author, "activity:object-type", ACTIVITY_OBJ_PERSON);
1400 XML::addElement($doc, $author, "uri", $owner["url"]);
1401 XML::addElement($doc, $author, "name", $owner["nick"]);
1402 XML::addElement($doc, $author, "email", $owner["addr"]);
1403 XML::addElement($doc, $author, "summary", bbcode($owner["about"], false, false, 7));
1405 $attributes = ["rel" => "alternate", "type" => "text/html", "href" => $owner["url"]];
1406 XML::addElement($doc, $author, "link", "", $attributes);
1410 "type" => "image/jpeg", // To-Do?
1411 "media:width" => 175,
1412 "media:height" => 175,
1413 "href" => $owner["photo"]];
1414 XML::addElement($doc, $author, "link", "", $attributes);
1416 if (isset($owner["thumb"])) {
1419 "type" => "image/jpeg", // To-Do?
1420 "media:width" => 80,
1421 "media:height" => 80,
1422 "href" => $owner["thumb"]];
1423 XML::addElement($doc, $author, "link", "", $attributes);
1426 XML::addElement($doc, $author, "poco:preferredUsername", $owner["nick"]);
1427 XML::addElement($doc, $author, "poco:displayName", $owner["name"]);
1428 XML::addElement($doc, $author, "poco:note", bbcode($owner["about"], false, false, 7));
1430 if (trim($owner["location"]) != "") {
1431 $element = $doc->createElement("poco:address");
1432 XML::addElement($doc, $element, "poco:formatted", $owner["location"]);
1433 $author->appendChild($element);
1436 if (trim($profile["homepage"]) != "") {
1437 $urls = $doc->createElement("poco:urls");
1438 XML::addElement($doc, $urls, "poco:type", "homepage");
1439 XML::addElement($doc, $urls, "poco:value", $profile["homepage"]);
1440 XML::addElement($doc, $urls, "poco:primary", "true");
1441 $author->appendChild($urls);
1444 if (count($profile)) {
1445 XML::addElement($doc, $author, "followers", "", ["url" => System::baseUrl()."/viewcontacts/".$owner["nick"]]);
1446 XML::addElement($doc, $author, "statusnet:profile_info", "", ["local_id" => $owner["uid"]]);
1449 if ($profile["publish"]) {
1450 XML::addElement($doc, $author, "mastodon:scope", "public");
1456 * @TODO Picture attachments should look like this:
1457 * <a href="https://status.pirati.ca/attachment/572819" title="https://status.pirati.ca/file/heluecht-20151202T222602-rd3u49p.gif"
1458 * class="attachment thumbnail" id="attachment-572819" rel="nofollow external">https://status.pirati.ca/attachment/572819</a>
1462 * @brief Returns the given activity if present - otherwise returns the "post" activity
1464 * @param array $item Data of the item that is to be posted
1466 * @return string activity
1468 private static function constructVerb($item)
1470 if ($item['verb']) {
1471 return $item['verb'];
1474 return ACTIVITY_POST;
1478 * @brief Returns the given object type if present - otherwise returns the "note" object type
1480 * @param array $item Data of the item that is to be posted
1482 * @return string Object type
1484 private static function constructObjecttype($item)
1486 if (in_array($item['object-type'], [ACTIVITY_OBJ_NOTE, ACTIVITY_OBJ_COMMENT]))
1487 return $item['object-type'];
1488 return ACTIVITY_OBJ_NOTE;
1492 * @brief Adds an entry element to the XML document
1494 * @param object $doc XML document
1495 * @param array $item Data of the item that is to be posted
1496 * @param array $owner Contact data of the poster
1497 * @param bool $toplevel optional default false
1499 * @return object Entry element
1501 private static function entry($doc, $item, $owner, $toplevel = false)
1503 $repeated_guid = self::getResharedGuid($item);
1504 if ($repeated_guid != "") {
1505 $xml = self::reshareEntry($doc, $item, $owner, $repeated_guid, $toplevel);
1512 if ($item["verb"] == ACTIVITY_LIKE) {
1513 return self::likeEntry($doc, $item, $owner, $toplevel);
1514 } elseif (in_array($item["verb"], [ACTIVITY_FOLLOW, NAMESPACE_OSTATUS."/unfollow"])) {
1515 return self::followEntry($doc, $item, $owner, $toplevel);
1517 return self::noteEntry($doc, $item, $owner, $toplevel);
1522 * @brief Adds a source entry to the XML document
1524 * @param object $doc XML document
1525 * @param array $contact Array of the contact that is added
1527 * @return object Source element
1529 private static function sourceEntry($doc, $contact)
1531 $source = $doc->createElement("source");
1532 XML::addElement($doc, $source, "id", $contact["poll"]);
1533 XML::addElement($doc, $source, "title", $contact["name"]);
1534 XML::addElement($doc, $source, "link", "", ["rel" => "alternate", "type" => "text/html", "href" => $contact["alias"]]);
1535 XML::addElement($doc, $source, "link", "", ["rel" => "self", "type" => "application/atom+xml", "href" => $contact["poll"]]);
1536 XML::addElement($doc, $source, "icon", $contact["photo"]);
1537 XML::addElement($doc, $source, "updated", datetime_convert("UTC", "UTC", $contact["success_update"]."+00:00", ATOM_TIME));
1543 * @brief Fetches contact data from the contact or the gcontact table
1545 * @param string $url URL of the contact
1546 * @param array $owner Contact data of the poster
1548 * @return array Contact array
1550 private static function contactEntry($url, $owner)
1553 "SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` IN (0, %d) ORDER BY `uid` DESC LIMIT 1",
1554 dbesc(normalise_link($url)),
1555 intval($owner["uid"])
1557 if (DBM::is_result($r)) {
1559 $contact["uid"] = -1;
1562 if (!DBM::is_result($r)) {
1564 "SELECT * FROM `gcontact` WHERE `nurl` = '%s' LIMIT 1",
1565 dbesc(normalise_link($url))
1567 if (DBM::is_result($r)) {
1569 $contact["uid"] = -1;
1570 $contact["success_update"] = $contact["updated"];
1574 if (!DBM::is_result($r)) {
1578 if (!isset($contact["poll"])) {
1579 $data = Probe::uri($url);
1580 $contact["poll"] = $data["poll"];
1582 if (!$contact["alias"]) {
1583 $contact["alias"] = $data["alias"];
1587 if (!isset($contact["alias"])) {
1588 $contact["alias"] = $contact["url"];
1595 * @brief Adds an entry element with reshared content
1597 * @param object $doc XML document
1598 * @param array $item Data of the item that is to be posted
1599 * @param array $owner Contact data of the poster
1600 * @param string $repeated_guid guid
1601 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1603 * @return object Entry element
1605 private static function reshareEntry($doc, $item, $owner, $repeated_guid, $toplevel)
1607 if (($item["id"] != $item["parent"]) && (normalise_link($item["author-link"]) != normalise_link($owner["url"]))) {
1608 logger("OStatus entry is from author ".$owner["url"]." - not from ".$item["author-link"].". Quitting.", LOGGER_DEBUG);
1611 $title = self::entryHeader($doc, $entry, $owner, $toplevel);
1614 "SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' AND NOT `private` AND `network` IN ('%s', '%s', '%s') LIMIT 1",
1615 intval($owner["uid"]),
1616 dbesc($repeated_guid),
1617 dbesc(NETWORK_DFRN),
1618 dbesc(NETWORK_DIASPORA),
1619 dbesc(NETWORK_OSTATUS)
1621 if (DBM::is_result($r)) {
1622 $repeated_item = $r[0];
1626 $contact = self::contactEntry($repeated_item['author-link'], $owner);
1628 $parent_item = (($item['thr-parent']) ? $item['thr-parent'] : $item['parent-uri']);
1630 $title = $owner["nick"]." repeated a notice by ".$contact["nick"];
1632 self::entryContent($doc, $entry, $item, $owner, $title, ACTIVITY_SHARE, false);
1634 $as_object = $doc->createElement("activity:object");
1636 XML::addElement($doc, $as_object, "activity:object-type", NAMESPACE_ACTIVITY_SCHEMA."activity");
1638 self::entryContent($doc, $as_object, $repeated_item, $owner, "", "", false);
1640 $author = self::addAuthor($doc, $contact);
1641 $as_object->appendChild($author);
1643 $as_object2 = $doc->createElement("activity:object");
1645 XML::addElement($doc, $as_object2, "activity:object-type", self::constructObjecttype($repeated_item));
1647 $title = sprintf("New comment by %s", $contact["nick"]);
1649 self::entryContent($doc, $as_object2, $repeated_item, $owner, $title);
1651 $as_object->appendChild($as_object2);
1653 self::entryFooter($doc, $as_object, $item, $owner, false);
1655 $source = self::sourceEntry($doc, $contact);
1657 $as_object->appendChild($source);
1659 $entry->appendChild($as_object);
1661 self::entryFooter($doc, $entry, $item, $owner);
1667 * @brief Adds an entry element with a "like"
1669 * @param object $doc XML document
1670 * @param array $item Data of the item that is to be posted
1671 * @param array $owner Contact data of the poster
1672 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1674 * @return object Entry element with "like"
1676 private static function likeEntry($doc, $item, $owner, $toplevel)
1678 if (($item["id"] != $item["parent"]) && (normalise_link($item["author-link"]) != normalise_link($owner["url"]))) {
1679 logger("OStatus entry is from author ".$owner["url"]." - not from ".$item["author-link"].". Quitting.", LOGGER_DEBUG);
1682 $title = self::entryHeader($doc, $entry, $owner, $toplevel);
1684 $verb = NAMESPACE_ACTIVITY_SCHEMA."favorite";
1685 self::entryContent($doc, $entry, $item, $owner, "Favorite", $verb, false);
1687 $as_object = $doc->createElement("activity:object");
1690 "SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d",
1691 dbesc($item["thr-parent"]),
1692 intval($item["uid"])
1694 $parent_item = (($item['thr-parent']) ? $item['thr-parent'] : $item['parent-uri']);
1696 XML::addElement($doc, $as_object, "activity:object-type", self::constructObjecttype($parent[0]));
1698 self::entryContent($doc, $as_object, $parent[0], $owner, "New entry");
1700 $entry->appendChild($as_object);
1702 self::entryFooter($doc, $entry, $item, $owner);
1708 * @brief Adds the person object element to the XML document
1710 * @param object $doc XML document
1711 * @param array $owner Contact data of the poster
1712 * @param array $contact Contact data of the target
1714 * @return object author element
1716 private static function addPersonObject($doc, $owner, $contact)
1718 $object = $doc->createElement("activity:object");
1719 XML::addElement($doc, $object, "activity:object-type", ACTIVITY_OBJ_PERSON);
1721 if ($contact['network'] == NETWORK_PHANTOM) {
1722 XML::addElement($doc, $object, "id", $contact['url']);
1726 XML::addElement($doc, $object, "id", $contact["alias"]);
1727 XML::addElement($doc, $object, "title", $contact["nick"]);
1729 $attributes = ["rel" => "alternate", "type" => "text/html", "href" => $contact["url"]];
1730 XML::addElement($doc, $object, "link", "", $attributes);
1734 "type" => "image/jpeg", // To-Do?
1735 "media:width" => 175,
1736 "media:height" => 175,
1737 "href" => $contact["photo"]];
1738 XML::addElement($doc, $object, "link", "", $attributes);
1740 XML::addElement($doc, $object, "poco:preferredUsername", $contact["nick"]);
1741 XML::addElement($doc, $object, "poco:displayName", $contact["name"]);
1743 if (trim($contact["location"]) != "") {
1744 $element = $doc->createElement("poco:address");
1745 XML::addElement($doc, $element, "poco:formatted", $contact["location"]);
1746 $object->appendChild($element);
1753 * @brief Adds a follow/unfollow entry element
1755 * @param object $doc XML document
1756 * @param array $item Data of the follow/unfollow message
1757 * @param array $owner Contact data of the poster
1758 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1760 * @return object Entry element
1762 private static function followEntry($doc, $item, $owner, $toplevel)
1764 $item["id"] = $item["parent"] = 0;
1765 $item["created"] = $item["edited"] = date("c");
1766 $item["private"] = true;
1768 $contact = Probe::uri($item['follow']);
1770 if ($contact['alias'] == '') {
1771 $contact['alias'] = $contact["url"];
1773 $item['follow'] = $contact['alias'];
1777 "SELECT `id` FROM `contact` WHERE `uid` = %d AND `nurl` = '%s'",
1778 intval($owner['uid']),
1779 dbesc(normalise_link($contact["url"]))
1782 if (DBM::is_result($r)) {
1783 $connect_id = $r[0]['id'];
1788 if ($item['verb'] == ACTIVITY_FOLLOW) {
1789 $message = t('%s is now following %s.');
1790 $title = t('following');
1791 $action = "subscription";
1793 $message = t('%s stopped following %s.');
1794 $title = t('stopped following');
1795 $action = "unfollow";
1798 $item["uri"] = $item['parent-uri'] = $item['thr-parent']
1799 = 'tag:'.get_app()->get_hostname().
1800 ','.date('Y-m-d').':'.$action.':'.$owner['uid'].
1801 ':person:'.$connect_id.':'.$item['created'];
1803 $item["body"] = sprintf($message, $owner["nick"], $contact["nick"]);
1805 self::entryHeader($doc, $entry, $owner, $toplevel);
1807 self::entryContent($doc, $entry, $item, $owner, $title);
1809 $object = self::addPersonObject($doc, $owner, $contact);
1810 $entry->appendChild($object);
1812 self::entryFooter($doc, $entry, $item, $owner);
1818 * @brief Adds a regular entry element
1820 * @param object $doc XML document
1821 * @param array $item Data of the item that is to be posted
1822 * @param array $owner Contact data of the poster
1823 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1825 * @return object Entry element
1827 private static function noteEntry($doc, $item, $owner, $toplevel)
1829 if (($item["id"] != $item["parent"]) && (normalise_link($item["author-link"]) != normalise_link($owner["url"]))) {
1830 logger("OStatus entry is from author ".$owner["url"]." - not from ".$item["author-link"].". Quitting.", LOGGER_DEBUG);
1833 $title = self::entryHeader($doc, $entry, $owner, $toplevel);
1835 XML::addElement($doc, $entry, "activity:object-type", ACTIVITY_OBJ_NOTE);
1837 self::entryContent($doc, $entry, $item, $owner, $title);
1839 self::entryFooter($doc, $entry, $item, $owner);
1845 * @brief Adds a header element to the XML document
1847 * @param object $doc XML document
1848 * @param object $entry The entry element where the elements are added
1849 * @param array $owner Contact data of the poster
1850 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1852 * @return string The title for the element
1854 private static function entryHeader($doc, &$entry, $owner, $toplevel)
1856 /// @todo Check if this title stuff is really needed (I guess not)
1858 $entry = $doc->createElement("entry");
1859 $title = sprintf("New note by %s", $owner["nick"]);
1861 $entry = $doc->createElementNS(NAMESPACE_ATOM1, "entry");
1863 $entry->setAttribute("xmlns:thr", NAMESPACE_THREAD);
1864 $entry->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
1865 $entry->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
1866 $entry->setAttribute("xmlns:media", NAMESPACE_MEDIA);
1867 $entry->setAttribute("xmlns:poco", NAMESPACE_POCO);
1868 $entry->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
1869 $entry->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
1870 $entry->setAttribute("xmlns:mastodon", NAMESPACE_MASTODON);
1872 $author = self::addAuthor($doc, $owner);
1873 $entry->appendChild($author);
1875 $title = sprintf("New comment by %s", $owner["nick"]);
1881 * @brief Adds elements to the XML document
1883 * @param object $doc XML document
1884 * @param object $entry Entry element where the content is added
1885 * @param array $item Data of the item that is to be posted
1886 * @param array $owner Contact data of the poster
1887 * @param string $title Title for the post
1888 * @param string $verb The activity verb
1889 * @param bool $complete Add the "status_net" element?
1892 private static function entryContent($doc, $entry, $item, $owner, $title, $verb = "", $complete = true)
1895 $verb = self::constructVerb($item);
1898 XML::addElement($doc, $entry, "id", $item["uri"]);
1899 XML::addElement($doc, $entry, "title", $title);
1901 $body = self::formatPicturePost($item['body']);
1903 if ($item['title'] != "") {
1904 $body = "[b]".$item['title']."[/b]\n\n".$body;
1907 $body = bbcode($body, false, false, 7);
1909 XML::addElement($doc, $entry, "content", $body, ["type" => "html"]);
1911 XML::addElement($doc, $entry, "link", "", ["rel" => "alternate", "type" => "text/html",
1912 "href" => System::baseUrl()."/display/".$item["guid"]]
1915 if ($complete && ($item["id"] > 0)) {
1916 XML::addElement($doc, $entry, "status_net", "", ["notice_id" => $item["id"]]);
1919 XML::addElement($doc, $entry, "activity:verb", $verb);
1921 XML::addElement($doc, $entry, "published", datetime_convert("UTC", "UTC", $item["created"]."+00:00", ATOM_TIME));
1922 XML::addElement($doc, $entry, "updated", datetime_convert("UTC", "UTC", $item["edited"]."+00:00", ATOM_TIME));
1926 * @brief Adds the elements at the foot of an entry to the XML document
1928 * @param object $doc XML document
1929 * @param object $entry The entry element where the elements are added
1930 * @param array $item Data of the item that is to be posted
1931 * @param array $owner Contact data of the poster
1932 * @param bool $complete default true
1935 private static function entryFooter($doc, $entry, $item, $owner, $complete = true)
1939 if (($item['parent'] != $item['id']) || ($item['parent-uri'] !== $item['uri']) || (($item['thr-parent'] !== '') && ($item['thr-parent'] !== $item['uri']))) {
1940 $parent = q("SELECT `guid`, `author-link`, `owner-link` FROM `item` WHERE `id` = %d", intval($item["parent"]));
1941 $parent_item = (($item['thr-parent']) ? $item['thr-parent'] : $item['parent-uri']);
1944 "SELECT `guid`, `author-link`, `owner-link`, `plink` FROM `item` WHERE `uid` = %d AND `uri` = '%s'",
1945 intval($owner["uid"]),
1949 $mentioned[$thrparent[0]["author-link"]] = $thrparent[0]["author-link"];
1950 $mentioned[$thrparent[0]["owner-link"]] = $thrparent[0]["owner-link"];
1951 $parent_plink = $thrparent[0]["plink"];
1953 $mentioned[$parent[0]["author-link"]] = $parent[0]["author-link"];
1954 $mentioned[$parent[0]["owner-link"]] = $parent[0]["owner-link"];
1955 $parent_plink = System::baseUrl()."/display/".$parent[0]["guid"];
1959 "ref" => $parent_item,
1960 "href" => $parent_plink];
1961 XML::addElement($doc, $entry, "thr:in-reply-to", "", $attributes);
1965 "href" => $parent_plink];
1966 XML::addElement($doc, $entry, "link", "", $attributes);
1969 if (intval($item["parent"]) > 0) {
1970 $conversation_href = System::baseUrl()."/display/".$owner["nick"]."/".$item["parent"];
1971 $conversation_uri = $conversation_href;
1973 if (isset($parent_item)) {
1974 $r = dba::fetch_first("SELECT `conversation-uri`, `conversation-href` FROM `conversation` WHERE `item-uri` = ?", $parent_item);
1975 if (DBM::is_result($r)) {
1976 if ($r['conversation-uri'] != '') {
1977 $conversation_uri = $r['conversation-uri'];
1979 if ($r['conversation-href'] != '') {
1980 $conversation_href = $r['conversation-href'];
1985 XML::addElement($doc, $entry, "link", "", ["rel" => "ostatus:conversation", "href" => $conversation_href]);
1988 "href" => $conversation_href,
1989 "local_id" => $item["parent"],
1990 "ref" => $conversation_uri];
1992 XML::addElement($doc, $entry, "ostatus:conversation", $conversation_uri, $attributes);
1995 $tags = item_getfeedtags($item);
1998 foreach ($tags as $t) {
2000 $mentioned[$t[1]] = $t[1];
2005 // Make sure that mentions are accepted (GNU Social has problems with mixing HTTP and HTTPS)
2007 foreach ($mentioned as $mention) {
2008 $newmentions[str_replace("http://", "https://", $mention)] = str_replace("http://", "https://", $mention);
2009 $newmentions[str_replace("https://", "http://", $mention)] = str_replace("https://", "http://", $mention);
2011 $mentioned = $newmentions;
2013 foreach ($mentioned as $mention) {
2015 "SELECT `forum`, `prv` FROM `contact` WHERE `uid` = %d AND `nurl` = '%s'",
2016 intval($owner["uid"]),
2017 dbesc(normalise_link($mention))
2019 if ($r[0]["forum"] || $r[0]["prv"]) {
2020 XML::addElement($doc, $entry, "link", "",
2022 "rel" => "mentioned",
2023 "ostatus:object-type" => ACTIVITY_OBJ_GROUP,
2027 XML::addElement($doc, $entry, "link", "",
2029 "rel" => "mentioned",
2030 "ostatus:object-type" => ACTIVITY_OBJ_PERSON,
2036 if (!$item["private"]) {
2037 XML::addElement($doc, $entry, "link", "", ["rel" => "ostatus:attention",
2038 "href" => "http://activityschema.org/collection/public"]);
2039 XML::addElement($doc, $entry, "link", "", ["rel" => "mentioned",
2040 "ostatus:object-type" => "http://activitystrea.ms/schema/1.0/collection",
2041 "href" => "http://activityschema.org/collection/public"]);
2042 XML::addElement($doc, $entry, "mastodon:scope", "public");
2046 foreach ($tags as $t) {
2048 XML::addElement($doc, $entry, "category", "", ["term" => $t[2]]);
2053 self::getAttachment($doc, $entry, $item);
2055 if ($complete && ($item["id"] > 0)) {
2056 $app = $item["app"];
2061 $attributes = ["local_id" => $item["id"], "source" => $app];
2063 if (isset($parent["id"])) {
2064 $attributes["repeat_of"] = $parent["id"];
2067 if ($item["coord"] != "") {
2068 XML::addElement($doc, $entry, "georss:point", $item["coord"]);
2071 XML::addElement($doc, $entry, "statusnet:notice_info", "", $attributes);
2076 * Creates the XML feed for a given nickname
2078 * Supported filters:
2079 * - activity (default): all the public posts
2080 * - posts: all the public top-level posts
2081 * - comments: all the public replies
2083 * Updates the provided last_update parameter if the result comes from the
2084 * cache or it is empty
2086 * @brief Creates the XML feed for a given nickname
2088 * @param string $owner_nick Nickname of the feed owner
2089 * @param string $last_update Date of the last update
2090 * @param integer $max_items Number of maximum items to fetch
2091 * @param string $filter Feed items filter (activity, posts or comments)
2092 * @param boolean $nocache Wether to bypass caching
2094 * @return string XML feed
2096 public static function feed($owner_nick, &$last_update, $max_items = 300, $filter = 'activity', $nocache = false)
2098 $stamp = microtime(true);
2100 $cachekey = "ostatus:feed:" . $owner_nick . ":" . $filter . ":" . $last_update;
2102 $previous_created = $last_update;
2104 $result = Cache::get($cachekey);
2105 if (!$nocache && !is_null($result)) {
2106 logger('Feed duration: ' . number_format(microtime(true) - $stamp, 3) . ' - ' . $owner_nick . ' - ' . $filter . ' - ' . $previous_created . ' (cached)', LOGGER_DEBUG);
2107 $last_update = $result['last_update'];
2108 return $result['feed'];
2111 $owner = dba::fetch_first(
2112 "SELECT `contact`.*, `user`.`nickname`, `user`.`timezone`, `user`.`page-flags`
2113 FROM `contact` INNER JOIN `user` ON `user`.`uid` = `contact`.`uid`
2114 WHERE `contact`.`self` AND `user`.`nickname` = ? LIMIT 1",
2117 if (!DBM::is_result($owner)) {
2121 if (!strlen($last_update)) {
2122 $last_update = 'now -30 days';
2125 $check_date = datetime_convert('UTC', 'UTC', $last_update, 'Y-m-d H:i:s');
2126 $authorid = Contact::getIdForURL($owner["url"], 0);
2129 if ($filter === 'posts') {
2130 $sql_extra .= ' AND `item`.`id` = `item`.`parent` ';
2133 if ($filter === 'comments') {
2134 $sql_extra .= sprintf(" AND `item`.`object-type` = '%s' ", dbesc(ACTIVITY_OBJ_COMMENT));
2138 "SELECT `item`.*, `item`.`id` AS `item_id` FROM `item` USE INDEX (`uid_contactid_created`)
2139 STRAIGHT_JOIN `thread` ON `thread`.`iid` = `item`.`parent`
2140 WHERE `item`.`uid` = %d
2141 AND `item`.`contact-id` = %d
2142 AND `item`.`author-id` = %d
2143 AND `item`.`created` > '%s'
2144 AND NOT `item`.`deleted`
2145 AND NOT `item`.`private`
2146 AND `thread`.`network` IN ('%s', '%s')
2148 ORDER BY `item`.`created` DESC LIMIT %d",
2149 intval($owner["uid"]),
2150 intval($owner["id"]),
2153 dbesc(NETWORK_OSTATUS),
2154 dbesc(NETWORK_DFRN),
2158 $doc = new DOMDocument('1.0', 'utf-8');
2159 $doc->formatOutput = true;
2161 $root = self::addHeader($doc, $owner, $filter);
2163 foreach ($items as $item) {
2164 if (Config::get('system', 'ostatus_debug')) {
2165 $item['body'] .= '🍼';
2167 $entry = self::entry($doc, $item, $owner);
2168 $root->appendChild($entry);
2170 if ($last_update < $item['created']) {
2171 $last_update = $item['created'];
2175 $feeddata = trim($doc->saveXML());
2177 $msg = ['feed' => $feeddata, 'last_update' => $last_update];
2178 Cache::set($cachekey, $msg, CACHE_QUARTER_HOUR);
2180 logger('Feed duration: ' . number_format(microtime(true) - $stamp, 3) . ' - ' . $owner_nick . ' - ' . $filter . ' - ' . $previous_created, LOGGER_DEBUG);
2186 * @brief Creates the XML for a salmon message
2188 * @param array $item Data of the item that is to be posted
2189 * @param array $owner Contact data of the poster
2191 * @return string XML for the salmon
2193 public static function salmon($item, $owner)
2195 $doc = new DOMDocument('1.0', 'utf-8');
2196 $doc->formatOutput = true;
2198 if (Config::get('system', 'ostatus_debug')) {
2199 $item['body'] .= '🐟';
2202 $entry = self::entry($doc, $item, $owner, true);
2204 $doc->appendChild($entry);
2206 return trim($doc->saveXML());