3 * @file src/Protocol/OStatus.php
5 namespace Friendica\Protocol;
8 use Friendica\Core\Cache;
9 use Friendica\Core\Config;
10 use Friendica\Core\L10n;
11 use Friendica\Core\System;
12 use Friendica\Database\DBM;
13 use Friendica\Model\Contact;
14 use Friendica\Model\GContact;
15 use Friendica\Model\Conversation;
16 use Friendica\Network\Probe;
17 use Friendica\Object\Image;
18 use Friendica\Util\Lock;
19 use Friendica\Util\XML;
24 require_once 'include/dba.php';
25 require_once 'include/threads.php';
26 require_once 'include/html2bbcode.php';
27 require_once 'include/bbcode.php';
28 require_once 'include/items.php';
29 require_once 'mod/share.php';
30 require_once 'include/enotify.php';
31 require_once 'include/api.php';
32 require_once 'mod/proxy.php';
35 * @brief This class contain functions for the OStatus protocol
39 private static $itemlist;
40 private static $conv_list = [];
43 * @brief Fetches author data
45 * @param object $xpath The xpath object
46 * @param object $context The xml context of the author details
47 * @param array $importer user record of the importing user
48 * @param array $contact Called by reference, will contain the fetched contact
49 * @param bool $onlyfetch Only fetch the header without updating the contact entries
51 * @return array Array of author related entries for the item
53 private static function fetchAuthor($xpath, $context, $importer, &$contact, $onlyfetch)
56 $author["author-link"] = $xpath->evaluate('atom:author/atom:uri/text()', $context)->item(0)->nodeValue;
57 $author["author-name"] = $xpath->evaluate('atom:author/atom:name/text()', $context)->item(0)->nodeValue;
58 $addr = $xpath->evaluate('atom:author/atom:email/text()', $context)->item(0)->nodeValue;
60 $aliaslink = $author["author-link"];
62 $alternate = $xpath->query("atom:author/atom:link[@rel='alternate']", $context)->item(0)->attributes;
63 if (is_object($alternate)) {
64 foreach ($alternate as $attributes) {
65 if (($attributes->name == "href") && ($attributes->textContent != "")) {
66 $author["author-link"] = $attributes->textContent;
70 $author["contact-id"] = $contact["id"];
74 if ($aliaslink != '') {
75 $condition = ["`uid` = ? AND `alias` = ? AND `network` != ?",
76 $importer["uid"], $aliaslink, NETWORK_STATUSNET];
77 $r = dba::selectFirst('contact', [], $condition);
79 if (DBM::is_result($r)) {
85 $author["contact-id"] = $r["id"];
89 if (!$found && ($author["author-link"] != "")) {
90 if ($aliaslink == "") {
91 $aliaslink = $author["author-link"];
94 $condition = ["`uid` = ? AND `nurl` IN (?, ?) AND `network` != ?", $importer["uid"],
95 normalise_link($author["author-link"]), normalise_link($aliaslink), NETWORK_STATUSNET];
96 $r = dba::selectFirst('contact', [], $condition);
98 if (DBM::is_result($r)) {
104 $author["contact-id"] = $r["id"];
108 if (!$found && ($addr != "")) {
109 $condition = ["`uid` = ? AND `addr` = ? AND `network` != ?",
110 $importer["uid"], $addr, NETWORK_STATUSNET];
111 $r = dba::selectFirst('contact', [], $condition);
113 if (DBM::is_result($r)) {
119 $author["contact-id"] = $r["id"];
124 $avatars = $xpath->query("atom:author/atom:link[@rel='avatar']", $context);
125 foreach ($avatars as $avatar) {
128 foreach ($avatar->attributes as $attributes) {
129 if ($attributes->name == "href") {
130 $href = $attributes->textContent;
132 if ($attributes->name == "width") {
133 $width = $attributes->textContent;
137 $avatarlist[$width] = $href;
140 if (count($avatarlist) > 0) {
142 $author["author-avatar"] = Probe::fixAvatar(current($avatarlist), $author["author-link"]);
145 $displayname = $xpath->evaluate('atom:author/poco:displayName/text()', $context)->item(0)->nodeValue;
146 if ($displayname != "") {
147 $author["author-name"] = $displayname;
150 $author["owner-name"] = $author["author-name"];
151 $author["owner-link"] = $author["author-link"];
152 $author["owner-avatar"] = $author["author-avatar"];
154 // Only update the contacts if it is an OStatus contact
155 if ($r && ($r['id'] > 0) && !$onlyfetch && ($contact["network"] == NETWORK_OSTATUS)) {
157 // Update contact data
159 unset($current['name-date']);
161 // This query doesn't seem to work
162 // $value = $xpath->query("atom:link[@rel='salmon']", $context)->item(0)->nodeValue;
164 // $contact["notify"] = $value;
166 // This query doesn't seem to work as well - I hate these queries
167 // $value = $xpath->query("atom:link[@rel='self' and @type='application/atom+xml']", $context)->item(0)->nodeValue;
169 // $contact["poll"] = $value;
171 $contact['url'] = $author["author-link"];
172 $contact['nurl'] = normalise_link($contact['url']);
174 $value = $xpath->evaluate('atom:author/atom:uri/text()', $context)->item(0)->nodeValue;
176 $contact["alias"] = $value;
179 $value = $xpath->evaluate('atom:author/poco:displayName/text()', $context)->item(0)->nodeValue;
181 $contact["name"] = $value;
184 $value = $xpath->evaluate('atom:author/poco:preferredUsername/text()', $context)->item(0)->nodeValue;
186 $contact["nick"] = $value;
189 $value = $xpath->evaluate('atom:author/poco:note/text()', $context)->item(0)->nodeValue;
191 $contact["about"] = html2bbcode($value);
194 $value = $xpath->evaluate('atom:author/poco:address/poco:formatted/text()', $context)->item(0)->nodeValue;
196 $contact["location"] = $value;
199 $contact['name-date'] = datetime_convert();
201 dba::update('contact', $contact, ['id' => $contact["id"]], $current);
203 if (!empty($author["author-avatar"]) && ($author["author-avatar"] != $current['avatar'])) {
204 logger("Update profile picture for contact ".$contact["id"], LOGGER_DEBUG);
205 Contact::updateAvatar($author["author-avatar"], $importer["uid"], $contact["id"]);
208 // Ensure that we are having this contact (with uid=0)
209 $cid = Contact::getIdForURL($aliaslink, 0);
212 $fields = ['url', 'nurl', 'name', 'nick', 'alias', 'about', 'location'];
213 $old_contact = dba::selectFirst('contact', $fields, ['id' => $cid]);
215 // Update it with the current values
216 $fields = ['url' => $author["author-link"], 'name' => $contact["name"],
217 'nurl' => normalise_link($author["author-link"]),
218 'nick' => $contact["nick"], 'alias' => $contact["alias"],
219 'about' => $contact["about"], 'location' => $contact["location"],
220 'success_update' => datetime_convert(), 'last-update' => datetime_convert()];
222 dba::update('contact', $fields, ['id' => $cid], $old_contact);
225 Contact::updateAvatar($author["author-avatar"], 0, $cid);
228 $contact["generation"] = 2;
229 $contact["hide"] = false; // OStatus contacts are never hidden
230 $contact["photo"] = $author["author-avatar"];
231 $gcid = GContact::update($contact);
233 GContact::link($gcid, $contact["uid"], $contact["id"]);
240 * @brief Fetches author data from a given XML string
242 * @param string $xml The XML
243 * @param array $importer user record of the importing user
245 * @return array Array of author related entries for the item
247 public static function salmonAuthor($xml, $importer)
253 $doc = new DOMDocument();
254 @$doc->loadXML($xml);
256 $xpath = new DOMXPath($doc);
257 $xpath->registerNamespace('atom', NAMESPACE_ATOM1);
258 $xpath->registerNamespace('thr', NAMESPACE_THREAD);
259 $xpath->registerNamespace('georss', NAMESPACE_GEORSS);
260 $xpath->registerNamespace('activity', NAMESPACE_ACTIVITY);
261 $xpath->registerNamespace('media', NAMESPACE_MEDIA);
262 $xpath->registerNamespace('poco', NAMESPACE_POCO);
263 $xpath->registerNamespace('ostatus', NAMESPACE_OSTATUS);
264 $xpath->registerNamespace('statusnet', NAMESPACE_STATUSNET);
266 $entries = $xpath->query('/atom:entry');
268 foreach ($entries as $entry) {
270 $author = self::fetchAuthor($xpath, $entry, $importer, $contact, true);
276 * @brief Read attributes from element
278 * @param object $element Element object
280 * @return array attributes
282 private static function readAttributes($element)
286 foreach ($element->attributes as $attributes) {
287 $attribute[$attributes->name] = $attributes->textContent;
294 * @brief Imports an XML string containing OStatus elements
296 * @param string $xml The XML
297 * @param array $importer user record of the importing user
298 * @param array $contact contact
299 * @param string $hub Called by reference, returns the fetched hub data
302 public static function import($xml, $importer, &$contact, &$hub)
304 self::process($xml, $importer, $contact, $hub);
308 * @brief Internal feed processing
310 * @param string $xml The XML
311 * @param array $importer user record of the importing user
312 * @param array $contact contact
313 * @param string $hub Called by reference, returns the fetched hub data
314 * @param boolean $stored Is the post fresh imported or from the database?
315 * @param boolean $initialize Is it the leading post so that data has to be initialized?
317 * @return boolean Could the XML be processed?
319 private static function process($xml, $importer, &$contact, &$hub, $stored = false, $initialize = true)
322 self::$itemlist = [];
323 self::$conv_list = [];
326 logger("Import OStatus message", LOGGER_DEBUG);
331 $doc = new DOMDocument();
332 @$doc->loadXML($xml);
334 $xpath = new DOMXPath($doc);
335 $xpath->registerNamespace('atom', NAMESPACE_ATOM1);
336 $xpath->registerNamespace('thr', NAMESPACE_THREAD);
337 $xpath->registerNamespace('georss', NAMESPACE_GEORSS);
338 $xpath->registerNamespace('activity', NAMESPACE_ACTIVITY);
339 $xpath->registerNamespace('media', NAMESPACE_MEDIA);
340 $xpath->registerNamespace('poco', NAMESPACE_POCO);
341 $xpath->registerNamespace('ostatus', NAMESPACE_OSTATUS);
342 $xpath->registerNamespace('statusnet', NAMESPACE_STATUSNET);
345 $hub_attributes = $xpath->query("/atom:feed/atom:link[@rel='hub']")->item(0)->attributes;
346 if (is_object($hub_attributes)) {
347 foreach ($hub_attributes as $hub_attribute) {
348 if ($hub_attribute->name == "href") {
349 $hub = $hub_attribute->textContent;
350 logger("Found hub ".$hub, LOGGER_DEBUG);
356 $header["uid"] = $importer["uid"];
357 $header["network"] = NETWORK_OSTATUS;
358 $header["type"] = "remote";
360 $header["origin"] = 0;
361 $header["gravity"] = GRAVITY_PARENT;
363 $first_child = $doc->firstChild->tagName;
365 if ($first_child == "feed") {
366 $entries = $xpath->query('/atom:feed/atom:entry');
368 $entries = $xpath->query('/atom:entry');
371 if ($entries->length == 1) {
372 // We reformat the XML to make it better readable
373 $doc2 = new DOMDocument();
374 $doc2->loadXML($xml);
375 $doc2->preserveWhiteSpace = false;
376 $doc2->formatOutput = true;
377 $xml2 = $doc2->saveXML();
379 $header["protocol"] = PROTOCOL_OSTATUS_SALMON;
380 $header["source"] = $xml2;
381 } elseif (!$initialize) {
385 // Fetch the first author
386 $authordata = $xpath->query('//author')->item(0);
387 $author = self::fetchAuthor($xpath, $authordata, $importer, $contact, $stored);
389 $entry = $xpath->query('/atom:entry');
391 // Reverse the order of the entries
394 foreach ($entries as $entry) {
395 $entrylist[] = $entry;
398 foreach (array_reverse($entrylist) as $entry) {
400 $authorelement = $xpath->query('/atom:entry/atom:author', $entry);
402 if ($authorelement->length == 0) {
403 $authorelement = $xpath->query('atom:author', $entry);
406 if ($authorelement->length > 0) {
407 $author = self::fetchAuthor($xpath, $entry, $importer, $contact, $stored);
410 $value = $xpath->evaluate('atom:author/poco:preferredUsername/text()', $entry)->item(0)->nodeValue;
414 $nickname = $author["author-name"];
417 $item = array_merge($header, $author);
419 $item["uri"] = $xpath->query('atom:id/text()', $entry)->item(0)->nodeValue;
421 $item["verb"] = $xpath->query('activity:verb/text()', $entry)->item(0)->nodeValue;
424 if (in_array($item["verb"], ['qvitter-delete-notice', ACTIVITY_DELETE, 'delete'])) {
425 self::deleteNotice($item);
429 if (in_array($item["verb"], [NAMESPACE_OSTATUS."/unfavorite", ACTIVITY_UNFAVORITE])) {
430 // Ignore "Unfavorite" message
431 logger("Ignore unfavorite message ".print_r($item, true), LOGGER_DEBUG);
435 // Deletions come with the same uri, so we check for duplicates after processing deletions
436 if (dba::exists('item', ['uid' => $importer["uid"], 'uri' => $item["uri"]])) {
437 logger('Post with URI '.$item["uri"].' already existed for user '.$importer["uid"].'.', LOGGER_DEBUG);
440 logger('Processing post with URI '.$item["uri"].' for user '.$importer["uid"].'.', LOGGER_DEBUG);
443 if ($item["verb"] == ACTIVITY_JOIN) {
444 // ignore "Join" messages
445 logger("Ignore join message ".print_r($item, true), LOGGER_DEBUG);
449 if ($item["verb"] == "http://mastodon.social/schema/1.0/block") {
450 // ignore mastodon "block" messages
451 logger("Ignore block message ".print_r($item, true), LOGGER_DEBUG);
455 if ($item["verb"] == ACTIVITY_FOLLOW) {
456 new_follower($importer, $contact, $item, $nickname);
460 if ($item["verb"] == NAMESPACE_OSTATUS."/unfollow") {
461 lose_follower($importer, $contact, $item, $dummy);
465 if ($item["verb"] == ACTIVITY_FAVORITE) {
466 $orig_uri = $xpath->query("activity:object/atom:id", $entry)->item(0)->nodeValue;
467 logger("Favorite ".$orig_uri." ".print_r($item, true));
469 $item["verb"] = ACTIVITY_LIKE;
470 $item["parent-uri"] = $orig_uri;
471 $item["gravity"] = GRAVITY_LIKE;
474 // http://activitystrea.ms/schema/1.0/rsvp-yes
475 if (!in_array($item["verb"], [ACTIVITY_POST, ACTIVITY_LIKE, ACTIVITY_SHARE])) {
476 logger("Unhandled verb ".$item["verb"]." ".print_r($item, true), LOGGER_DEBUG);
479 self::processPost($xpath, $entry, $item, $importer);
481 if ($initialize && (count(self::$itemlist) > 0)) {
482 if (self::$itemlist[0]['uri'] == self::$itemlist[0]['parent-uri']) {
483 // We will import it everytime, when it is started by our contacts
484 $valid = !empty(self::$itemlist[0]['contact-id']);
486 // If not, then it depends on this setting
487 $valid = !Config::get('system', 'ostatus_full_threads');
490 // Never post a thread when the only interaction by our contact was a like
492 $verbs = [ACTIVITY_POST, ACTIVITY_SHARE];
493 foreach (self::$itemlist as $item) {
494 if (!empty($item['contact-id']) && in_array($item['verb'], $verbs)) {
500 // But we will only import complete threads
501 $valid = dba::exists('item', ['uid' => $importer["uid"], 'uri' => self::$itemlist[0]['parent-uri']]);
505 $default_contact = 0;
506 $key = count(self::$itemlist);
507 for ($key = count(self::$itemlist) - 1; $key >= 0; $key--) {
508 if (empty(self::$itemlist[$key]['contact-id'])) {
509 self::$itemlist[$key]['contact-id'] = $default_contact;
511 $default_contact = $item['contact-id'];
514 foreach (self::$itemlist as $item) {
515 $found = dba::exists('item', ['uid' => $importer["uid"], 'uri' => $item["uri"]]);
517 logger("Item with uri ".$item["uri"]." for user ".$importer["uid"]." already exists.", LOGGER_DEBUG);
518 } elseif ($item['contact-id'] < 0) {
519 logger("Item with uri ".$item["uri"]." is from a blocked contact.", LOGGER_DEBUG);
521 // We are having duplicated entries. Hopefully this solves it.
522 if (Lock::set('ostatus_process_item_store')) {
523 $ret = item_store($item);
524 Lock::remove('ostatus_process_item_store');
525 logger("Item with uri ".$item["uri"]." for user ".$importer["uid"].' stored. Return value: '.$ret);
527 $ret = item_store($item);
528 logger("We couldn't lock - but tried to store the item anyway. Return value is ".$ret);
533 self::$itemlist = [];
535 logger('Processing done for post with URI '.$item["uri"].' for user '.$importer["uid"].'.', LOGGER_DEBUG);
541 * @param object $item item
544 private static function deleteNotice($item)
546 $condition = ['uid' => $item['uid'], 'author-link' => $item['author-link'], 'uri' => $item['uri']];
547 $deleted = dba::selectFirst('item', ['id', 'parent-uri'], $condition);
548 if (!DBM::is_result($deleted)) {
549 logger('Item from '.$item['author-link'].' with uri '.$item['uri'].' for user '.$item['uid']." wasn't found. We don't delete it. ");
553 // Currently we don't have a central deletion function that we could use in this case
554 // The function "item_drop" doesn't work for that case
557 ['deleted' => true, 'title' => '', 'body' => '',
558 'edited' => datetime_convert(), 'changed' => datetime_convert()],
559 ['id' => $deleted["id"]]
562 delete_thread($deleted["id"], $deleted["parent-uri"]);
564 logger('Deleted item with uri '.$item['uri'].' for user '.$item['uid']);
568 * @brief Processes the XML for a post
570 * @param object $xpath The xpath object
571 * @param object $entry The xml entry that is processed
572 * @param array $item The item array
573 * @param array $importer user record of the importing user
576 private static function processPost($xpath, $entry, &$item, $importer)
578 $item["body"] = html2bbcode($xpath->query('atom:content/text()', $entry)->item(0)->nodeValue);
579 $item["object-type"] = $xpath->query('activity:object-type/text()', $entry)->item(0)->nodeValue;
580 if (($item["object-type"] == ACTIVITY_OBJ_BOOKMARK) || ($item["object-type"] == ACTIVITY_OBJ_EVENT)) {
581 $item["title"] = $xpath->query('atom:title/text()', $entry)->item(0)->nodeValue;
582 $item["body"] = $xpath->query('atom:summary/text()', $entry)->item(0)->nodeValue;
583 } elseif ($item["object-type"] == ACTIVITY_OBJ_QUESTION) {
584 $item["title"] = $xpath->query('atom:title/text()', $entry)->item(0)->nodeValue;
587 $item["created"] = $xpath->query('atom:published/text()', $entry)->item(0)->nodeValue;
588 $item["edited"] = $xpath->query('atom:updated/text()', $entry)->item(0)->nodeValue;
589 $conversation = $xpath->query('ostatus:conversation/text()', $entry)->item(0)->nodeValue;
590 $item['conversation-uri'] = $conversation;
592 $conv = $xpath->query('ostatus:conversation', $entry);
593 if (is_object($conv->item(0))) {
594 foreach ($conv->item(0)->attributes as $attributes) {
595 if ($attributes->name == "ref") {
596 $item['conversation-uri'] = $attributes->textContent;
598 if ($attributes->name == "href") {
599 $item['conversation-href'] = $attributes->textContent;
606 $inreplyto = $xpath->query('thr:in-reply-to', $entry);
607 if (is_object($inreplyto->item(0))) {
608 foreach ($inreplyto->item(0)->attributes as $attributes) {
609 if ($attributes->name == "ref") {
610 $item["parent-uri"] = $attributes->textContent;
612 if ($attributes->name == "href") {
613 $related = $attributes->textContent;
618 $georsspoint = $xpath->query('georss:point', $entry);
619 if (!empty($georsspoint) && ($georsspoint->length > 0)) {
620 $item["coord"] = $georsspoint->item(0)->nodeValue;
623 $categories = $xpath->query('atom:category', $entry);
625 foreach ($categories as $category) {
626 foreach ($category->attributes as $attributes) {
627 if ($attributes->name == "term") {
628 $term = $attributes->textContent;
629 if (strlen($item["tag"])) {
632 $item["tag"] .= "#[url=".System::baseUrl()."/search?tag=".$term."]".$term."[/url]";
641 $links = $xpath->query('atom:link', $entry);
643 $link_data = self::processLinks($links, $item);
644 $self = $link_data['self'];
645 $add_body = $link_data['add_body'];
650 $notice_info = $xpath->query('statusnet:notice_info', $entry);
651 if ($notice_info && ($notice_info->length > 0)) {
652 foreach ($notice_info->item(0)->attributes as $attributes) {
653 if ($attributes->name == "source") {
654 $item["app"] = strip_tags($attributes->textContent);
656 if ($attributes->name == "repeat_of") {
657 $repeat_of = $attributes->textContent;
661 // Is it a repeated post?
662 if (($repeat_of != "") || ($item["verb"] == ACTIVITY_SHARE)) {
663 $link_data = self::processRepeatedItem($xpath, $entry, $item, $importer);
664 if (!empty($link_data['add_body'])) {
665 $add_body .= $link_data['add_body'];
669 $item["body"] .= $add_body;
671 // Only add additional data when there is no picture in the post
672 if (!strstr($item["body"], '[/img]')) {
673 $item["body"] = add_page_info_to_body($item["body"]);
676 // Mastodon Content Warning
677 if (($item["verb"] == ACTIVITY_POST) && $xpath->evaluate('boolean(atom:summary)', $entry)) {
678 $clear_text = $xpath->query('atom:summary/text()', $entry)->item(0)->nodeValue;
680 $item["body"] = html2bbcode($clear_text) . '[spoiler]' . $item["body"] . '[/spoiler]';
683 if (($self != '') && empty($item['protocol'])) {
684 self::fetchSelf($self, $item);
687 if (!empty($item["conversation-href"])) {
688 self::fetchConversation($item['conversation-href'], $item['conversation-uri']);
691 if (isset($item["parent-uri"]) && ($related != '')) {
692 if (!dba::exists('item', ['uid' => $importer["uid"], 'uri' => $item['parent-uri']])) {
693 self::fetchRelated($related, $item["parent-uri"], $importer);
695 logger('Reply with URI '.$item["uri"].' already existed for user '.$importer["uid"].'.', LOGGER_DEBUG);
698 $item["type"] = 'remote-comment';
699 $item["gravity"] = GRAVITY_COMMENT;
701 $item["parent-uri"] = $item["uri"];
704 if (($item['author-link'] != '') && !empty($item['protocol'])) {
705 $item = Conversation::insert($item);
708 self::$itemlist[] = $item;
712 * @brief Fetch the conversation for posts
714 * @param string $conversation The link to the conversation
715 * @param string $conversation_uri The conversation in "uri" format
718 private static function fetchConversation($conversation, $conversation_uri)
720 // Ensure that we only store a conversation once in a process
721 if (isset(self::$conv_list[$conversation])) {
725 self::$conv_list[$conversation] = true;
727 $conversation_data = z_fetch_url($conversation, false, $redirects, ['accept_content' => 'application/atom+xml, text/html']);
729 if (!$conversation_data['success']) {
735 if (stristr($conversation_data['header'], 'Content-Type: application/atom+xml')) {
736 $xml = $conversation_data['body'];
740 $doc = new DOMDocument();
741 if (!@$doc->loadHTML($conversation_data['body'])) {
744 $xpath = new DOMXPath($doc);
746 $links = $xpath->query('//link');
748 foreach ($links as $link) {
749 $attribute = self::readAttributes($link);
750 if (($attribute['rel'] == 'alternate') && ($attribute['type'] == 'application/atom+xml')) {
751 $file = $attribute['href'];
755 $conversation_atom = z_fetch_url($attribute['href']);
757 if ($conversation_atom['success']) {
758 $xml = $conversation_atom['body'];
768 self::storeConversation($xml, $conversation, $conversation_uri);
772 * @brief Store a feed in several conversation entries
774 * @param string $xml The feed
775 * @param string $conversation conversation
776 * @param string $conversation_uri conversation uri
779 private static function storeConversation($xml, $conversation = '', $conversation_uri = '')
781 $doc = new DOMDocument();
782 @$doc->loadXML($xml);
784 $xpath = new DOMXPath($doc);
785 $xpath->registerNamespace('atom', NAMESPACE_ATOM1);
786 $xpath->registerNamespace('thr', NAMESPACE_THREAD);
787 $xpath->registerNamespace('ostatus', NAMESPACE_OSTATUS);
789 $entries = $xpath->query('/atom:feed/atom:entry');
791 // Now store the entries
792 foreach ($entries as $entry) {
793 $doc2 = new DOMDocument();
794 $doc2->preserveWhiteSpace = false;
795 $doc2->formatOutput = true;
799 $conv_data['protocol'] = PROTOCOL_SPLITTED_CONV;
800 $conv_data['network'] = NETWORK_OSTATUS;
801 $conv_data['uri'] = $xpath->query('atom:id/text()', $entry)->item(0)->nodeValue;
803 $inreplyto = $xpath->query('thr:in-reply-to', $entry);
804 if (is_object($inreplyto->item(0))) {
805 foreach ($inreplyto->item(0)->attributes as $attributes) {
806 if ($attributes->name == "ref") {
807 $conv_data['reply-to-uri'] = $attributes->textContent;
812 $conv = $xpath->query('ostatus:conversation/text()', $entry)->item(0)->nodeValue;
813 $conv_data['conversation-uri'] = $conv;
815 $conv = $xpath->query('ostatus:conversation', $entry);
816 if (is_object($conv->item(0))) {
817 foreach ($conv->item(0)->attributes as $attributes) {
818 if ($attributes->name == "ref") {
819 $conv_data['conversation-uri'] = $attributes->textContent;
821 if ($attributes->name == "href") {
822 $conv_data['conversation-href'] = $attributes->textContent;
827 if ($conversation != '') {
828 $conv_data['conversation-uri'] = $conversation;
831 if ($conversation_uri != '') {
832 $conv_data['conversation-uri'] = $conversation_uri;
835 $entry = $doc2->importNode($entry, true);
837 $doc2->appendChild($entry);
839 $conv_data['source'] = $doc2->saveXML();
841 $condition = ['item-uri' => $conv_data['uri'],'protocol' => PROTOCOL_OSTATUS_FEED];
842 if (dba::exists('conversation', $condition)) {
843 logger('Delete deprecated entry for URI '.$conv_data['uri'], LOGGER_DEBUG);
844 dba::delete('conversation', ['item-uri' => $conv_data['uri']]);
847 logger('Store conversation data for uri '.$conv_data['uri'], LOGGER_DEBUG);
848 Conversation::insert($conv_data);
853 * @brief Fetch the own post so that it can be stored later
855 * We want to store the original data for later processing.
856 * This function is meant for cases where we process a feed with multiple entries.
857 * In that case we need to fetch the single posts here.
859 * @param string $self The link to the self item
860 * @param array $item The item array
863 private static function fetchSelf($self, &$item)
865 $condition = ['`item-uri` = ? AND `protocol` IN (?, ?)', $self, PROTOCOL_DFRN, PROTOCOL_OSTATUS_SALMON];
866 if (dba::exists('conversation', $condition)) {
867 logger('Conversation '.$item['uri'].' is already stored.', LOGGER_DEBUG);
871 $self_data = z_fetch_url($self);
873 if (!$self_data['success']) {
877 // We reformat the XML to make it better readable
878 $doc = new DOMDocument();
879 $doc->loadXML($self_data['body']);
880 $doc->preserveWhiteSpace = false;
881 $doc->formatOutput = true;
882 $xml = $doc->saveXML();
884 $item["protocol"] = PROTOCOL_OSTATUS_SALMON;
885 $item["source"] = $xml;
887 logger('Conversation '.$item['uri'].' is now fetched.', LOGGER_DEBUG);
891 * @brief Fetch related posts and processes them
893 * @param string $related The link to the related item
894 * @param string $related_uri The related item in "uri" format
895 * @param array $importer user record of the importing user
898 private static function fetchRelated($related, $related_uri, $importer)
900 $condition = ['`item-uri` = ? AND `protocol` IN (?, ?)', $related_uri, PROTOCOL_DFRN, PROTOCOL_OSTATUS_SALMON];
901 $conversation = dba::selectFirst('conversation', ['source', 'protocol'], $condition);
902 if (DBM::is_result($conversation)) {
904 $xml = $conversation['source'];
905 if (self::process($xml, $importer, $contact, $hub, $stored, false)) {
906 logger('Got valid cached XML for URI '.$related_uri, LOGGER_DEBUG);
909 if ($conversation['protocol'] == PROTOCOL_OSTATUS_SALMON) {
910 logger('Delete invalid cached XML for URI '.$related_uri, LOGGER_DEBUG);
911 dba::delete('conversation', ['item-uri' => $related_uri]);
916 $related_data = z_fetch_url($related, false, $redirects, ['accept_content' => 'application/atom+xml, text/html']);
918 if (!$related_data['success']) {
924 if (stristr($related_data['header'], 'Content-Type: application/atom+xml')) {
925 logger('Directly fetched XML for URI '.$related_uri, LOGGER_DEBUG);
926 $xml = $related_data['body'];
930 $doc = new DOMDocument();
931 if (!@$doc->loadHTML($related_data['body'])) {
934 $xpath = new DOMXPath($doc);
938 $links = $xpath->query('//link');
940 foreach ($links as $link) {
941 $attribute = self::readAttributes($link);
942 if (($attribute['rel'] == 'alternate') && ($attribute['type'] == 'application/atom+xml')) {
943 $atom_file = $attribute['href'];
946 if ($atom_file != '') {
947 $related_atom = z_fetch_url($atom_file);
949 if ($related_atom['success']) {
950 logger('Fetched XML for URI '.$related_uri, LOGGER_DEBUG);
951 $xml = $related_atom['body'];
957 // Workaround for older GNU Social servers
958 if (($xml == '') && strstr($related, '/notice/')) {
959 $related_atom = z_fetch_url(str_replace('/notice/', '/api/statuses/show/', $related).'.atom');
961 if ($related_atom['success']) {
962 logger('GNU Social workaround to fetch XML for URI '.$related_uri, LOGGER_DEBUG);
963 $xml = $related_atom['body'];
967 // Even more worse workaround for GNU Social ;-)
969 $related_guess = OStatus::convertHref($related_uri);
970 $related_atom = z_fetch_url(str_replace('/notice/', '/api/statuses/show/', $related_guess).'.atom');
972 if ($related_atom['success']) {
973 logger('GNU Social workaround 2 to fetch XML for URI '.$related_uri, LOGGER_DEBUG);
974 $xml = $related_atom['body'];
978 // Finally we take the data that we fetched from "ostatus:conversation"
980 $condition = ['item-uri' => $related_uri, 'protocol' => PROTOCOL_SPLITTED_CONV];
981 $conversation = dba::selectFirst('conversation', ['source'], $condition);
982 if (DBM::is_result($conversation)) {
984 logger('Got cached XML from conversation for URI '.$related_uri, LOGGER_DEBUG);
985 $xml = $conversation['source'];
990 self::process($xml, $importer, $contact, $hub, $stored, false);
992 logger("XML couldn't be fetched for URI: ".$related_uri." - href: ".$related, LOGGER_DEBUG);
998 * @brief Processes the XML for a repeated post
1000 * @param object $xpath The xpath object
1001 * @param object $entry The xml entry that is processed
1002 * @param array $item The item array
1003 * @param array $importer user record of the importing user
1005 * @return array with data from links
1007 private static function processRepeatedItem($xpath, $entry, &$item, $importer)
1009 $activityobjects = $xpath->query('activity:object', $entry)->item(0);
1011 if (!is_object($activityobjects)) {
1017 $orig_uri = $xpath->query('atom:id/text()', $activityobjects)->item(0)->nodeValue;
1019 $links = $xpath->query("atom:link", $activityobjects);
1021 $link_data = self::processLinks($links, $item);
1024 $orig_body = $xpath->query('atom:content/text()', $activityobjects)->item(0)->nodeValue;
1025 $orig_created = $xpath->query('atom:published/text()', $activityobjects)->item(0)->nodeValue;
1026 $orig_edited = $xpath->query('atom:updated/text()', $activityobjects)->item(0)->nodeValue;
1028 $orig_author = self::fetchAuthor($xpath, $activityobjects, $importer, $dummy, false);
1030 $item["author-name"] = $orig_author["author-name"];
1031 $item["author-link"] = $orig_author["author-link"];
1032 $item["author-avatar"] = $orig_author["author-avatar"];
1034 $item["body"] = html2bbcode($orig_body);
1035 $item["created"] = $orig_created;
1036 $item["edited"] = $orig_edited;
1038 $item["uri"] = $orig_uri;
1040 $item["verb"] = $xpath->query('activity:verb/text()', $activityobjects)->item(0)->nodeValue;
1042 $item["object-type"] = $xpath->query('activity:object-type/text()', $activityobjects)->item(0)->nodeValue;
1044 $inreplyto = $xpath->query('thr:in-reply-to', $activityobjects);
1045 if (is_object($inreplyto->item(0))) {
1046 foreach ($inreplyto->item(0)->attributes as $attributes) {
1047 if ($attributes->name == "ref") {
1048 $item["parent-uri"] = $attributes->textContent;
1057 * @brief Processes links in the XML
1059 * @param object $links The xml data that contain links
1060 * @param array $item The item array
1062 * @return array with data from the links
1064 private static function processLinks($links, &$item)
1066 $link_data = ['add_body' => '', 'self' => ''];
1068 foreach ($links as $link) {
1069 $attribute = self::readAttributes($link);
1071 if (($attribute['rel'] != "") && ($attribute['href'] != "")) {
1072 switch ($attribute['rel']) {
1074 $item["plink"] = $attribute['href'];
1075 if (($item["object-type"] == ACTIVITY_OBJ_QUESTION)
1076 || ($item["object-type"] == ACTIVITY_OBJ_EVENT)
1078 $item["body"] .= add_page_info($attribute['href']);
1081 case "ostatus:conversation":
1082 $link_data['conversation'] = $attribute['href'];
1083 $item['conversation-href'] = $link_data['conversation'];
1084 if (!isset($item['conversation-uri'])) {
1085 $item['conversation-uri'] = $item['conversation-href'];
1089 $filetype = strtolower(substr($attribute['type'], 0, strpos($attribute['type'], '/')));
1090 if ($filetype == 'image') {
1091 $link_data['add_body'] .= "\n[img]".$attribute['href'].'[/img]';
1093 if (strlen($item["attach"])) {
1094 $item["attach"] .= ',';
1096 if (!isset($attribute['length'])) {
1097 $attribute['length'] = "0";
1099 $item["attach"] .= '[attach]href="'.$attribute['href'].'" length="'.$attribute['length'].'" type="'.$attribute['type'].'" title="'.$attribute['title'].'"[/attach]';
1103 if ($item["object-type"] != ACTIVITY_OBJ_BOOKMARK) {
1104 if (!isset($item["parent-uri"])) {
1105 $item["parent-uri"] = $attribute['href'];
1107 $link_data['related'] = $attribute['href'];
1109 $item["body"] .= add_page_info($attribute['href']);
1113 if ($item["plink"] == '') {
1114 $item["plink"] = $attribute['href'];
1116 $link_data['self'] = $attribute['href'];
1125 * @brief Create an url out of an uri
1127 * @param string $href URI in the format "parameter1:parameter1:..."
1129 * @return string URL in the format http(s)://....
1131 public static function convertHref($href)
1133 $elements = explode(":", $href);
1135 if ((count($elements) <= 2) || ($elements[0] != "tag")) {
1139 $server = explode(",", $elements[1]);
1140 $conversation = explode("=", $elements[2]);
1142 if ((count($elements) == 4) && ($elements[2] == "post")) {
1143 return "http://".$server[0]."/notice/".$elements[3];
1146 if ((count($conversation) != 2) || ($conversation[1] =="")) {
1149 if ($elements[3] == "objectType=thread") {
1150 return "http://".$server[0]."/conversation/".$conversation[1];
1152 return "http://".$server[0]."/notice/".$conversation[1];
1158 * @brief Checks if the current post is a reshare
1160 * @param array $item The item array of thw post
1162 * @return string The guid if the post is a reshare
1164 private static function getResharedGuid($item)
1166 $body = trim($item["body"]);
1168 // Skip if it isn't a pure repeated messages
1169 // Does it start with a share?
1170 if (strpos($body, "[share") > 0) {
1174 // Does it end with a share?
1175 if (strlen($body) > (strrpos($body, "[/share]") + 8)) {
1179 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "$1", $body);
1180 // Skip if there is no shared message in there
1181 if ($body == $attributes) {
1186 preg_match("/guid='(.*?)'/ism", $attributes, $matches);
1187 if ($matches[1] != "") {
1188 $guid = $matches[1];
1191 preg_match('/guid="(.*?)"/ism', $attributes, $matches);
1192 if ($matches[1] != "") {
1193 $guid = $matches[1];
1200 * @brief Cleans the body of a post if it contains picture links
1202 * @param string $body The body
1204 * @return string The cleaned body
1206 private static function formatPicturePost($body)
1208 $siteinfo = get_attached_data($body);
1210 if (($siteinfo["type"] == "photo")) {
1211 if (isset($siteinfo["preview"])) {
1212 $preview = $siteinfo["preview"];
1214 $preview = $siteinfo["image"];
1217 // Is it a remote picture? Then make a smaller preview here
1218 $preview = proxy_url($preview, false, PROXY_SIZE_SMALL);
1220 // Is it a local picture? Then make it smaller here
1221 $preview = str_replace(["-0.jpg", "-0.png"], ["-2.jpg", "-2.png"], $preview);
1222 $preview = str_replace(["-1.jpg", "-1.png"], ["-2.jpg", "-2.png"], $preview);
1224 if (isset($siteinfo["url"])) {
1225 $url = $siteinfo["url"];
1227 $url = $siteinfo["image"];
1230 $body = trim($siteinfo["text"])." [url]".$url."[/url]\n[img]".$preview."[/img]";
1237 * @brief Adds the header elements to the XML document
1239 * @param object $doc XML document
1240 * @param array $owner Contact data of the poster
1241 * @param string $filter The related feed filter (activity, posts or comments)
1243 * @return object header root element
1245 private static function addHeader($doc, $owner, $filter)
1249 $root = $doc->createElementNS(NAMESPACE_ATOM1, 'feed');
1250 $doc->appendChild($root);
1252 $root->setAttribute("xmlns:thr", NAMESPACE_THREAD);
1253 $root->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
1254 $root->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
1255 $root->setAttribute("xmlns:media", NAMESPACE_MEDIA);
1256 $root->setAttribute("xmlns:poco", NAMESPACE_POCO);
1257 $root->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
1258 $root->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
1259 $root->setAttribute("xmlns:mastodon", NAMESPACE_MASTODON);
1262 case 'activity': $title = L10n::t('%s\'s timeline', $owner['name']); break;
1263 case 'posts' : $title = L10n::t('%s\'s posts' , $owner['name']); break;
1264 case 'comments': $title = L10n::t('%s\'s comments', $owner['name']); break;
1267 $attributes = ["uri" => "https://friendi.ca", "version" => FRIENDICA_VERSION . "-" . DB_UPDATE_VERSION];
1268 XML::addElement($doc, $root, "generator", FRIENDICA_PLATFORM, $attributes);
1269 XML::addElement($doc, $root, "id", System::baseUrl() . "/profile/" . $owner["nick"]);
1270 XML::addElement($doc, $root, "title", $title);
1271 XML::addElement($doc, $root, "subtitle", sprintf("Updates from %s on %s", $owner["name"], $a->config["sitename"]));
1272 XML::addElement($doc, $root, "logo", $owner["photo"]);
1273 XML::addElement($doc, $root, "updated", datetime_convert("UTC", "UTC", "now", ATOM_TIME));
1275 $author = self::addAuthor($doc, $owner);
1276 $root->appendChild($author);
1278 $attributes = ["href" => $owner["url"], "rel" => "alternate", "type" => "text/html"];
1279 XML::addElement($doc, $root, "link", "", $attributes);
1281 /// @TODO We have to find out what this is
1282 /// $attributes = array("href" => System::baseUrl()."/sup",
1283 /// "rel" => "http://api.friendfeed.com/2008/03#sup",
1284 /// "type" => "application/json");
1285 /// XML::addElement($doc, $root, "link", "", $attributes);
1287 self::hublinks($doc, $root, $owner["nick"]);
1289 $attributes = ["href" => System::baseUrl() . "/salmon/" . $owner["nick"], "rel" => "salmon"];
1290 XML::addElement($doc, $root, "link", "", $attributes);
1292 $attributes = ["href" => System::baseUrl() . "/salmon/" . $owner["nick"], "rel" => "http://salmon-protocol.org/ns/salmon-replies"];
1293 XML::addElement($doc, $root, "link", "", $attributes);
1295 $attributes = ["href" => System::baseUrl() . "/salmon/" . $owner["nick"], "rel" => "http://salmon-protocol.org/ns/salmon-mention"];
1296 XML::addElement($doc, $root, "link", "", $attributes);
1298 $attributes = ["href" => System::baseUrl() . "/api/statuses/user_timeline/" . $owner["nick"] . ".atom",
1299 "rel" => "self", "type" => "application/atom+xml"];
1300 XML::addElement($doc, $root, "link", "", $attributes);
1306 * @brief Add the link to the push hubs to the XML document
1308 * @param object $doc XML document
1309 * @param object $root XML root element where the hub links are added
1310 * @param object $nick nick
1313 public static function hublinks($doc, $root, $nick)
1315 $h = System::baseUrl() . '/pubsubhubbub/'.$nick;
1316 XML::addElement($doc, $root, "link", "", ["href" => $h, "rel" => "hub"]);
1320 * @brief Adds attachement data to the XML document
1322 * @param object $doc XML document
1323 * @param object $root XML root element where the hub links are added
1324 * @param array $item Data of the item that is to be posted
1327 private static function getAttachment($doc, $root, $item)
1330 $siteinfo = get_attached_data($item["body"]);
1332 switch ($siteinfo["type"]) {
1334 $imgdata = Image::getInfoFromURL($siteinfo["image"]);
1335 $attributes = ["rel" => "enclosure",
1336 "href" => $siteinfo["image"],
1337 "type" => $imgdata["mime"],
1338 "length" => intval($imgdata["size"])];
1339 XML::addElement($doc, $root, "link", "", $attributes);
1342 $attributes = ["rel" => "enclosure",
1343 "href" => $siteinfo["url"],
1344 "type" => "text/html; charset=UTF-8",
1346 "title" => $siteinfo["title"]];
1347 XML::addElement($doc, $root, "link", "", $attributes);
1353 if (!Config::get('system', 'ostatus_not_attach_preview') && ($siteinfo["type"] != "photo") && isset($siteinfo["image"])) {
1354 $imgdata = Image::getInfoFromURL($siteinfo["image"]);
1355 $attributes = ["rel" => "enclosure",
1356 "href" => $siteinfo["image"],
1357 "type" => $imgdata["mime"],
1358 "length" => intval($imgdata["size"])];
1360 XML::addElement($doc, $root, "link", "", $attributes);
1363 $arr = explode('[/attach],', $item['attach']);
1365 foreach ($arr as $r) {
1367 $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"|', $r, $matches);
1369 $attributes = ["rel" => "enclosure",
1370 "href" => $matches[1],
1371 "type" => $matches[3]];
1373 if (intval($matches[2])) {
1374 $attributes["length"] = intval($matches[2]);
1376 if (trim($matches[4]) != "") {
1377 $attributes["title"] = trim($matches[4]);
1379 XML::addElement($doc, $root, "link", "", $attributes);
1386 * @brief Adds the author element to the XML document
1388 * @param object $doc XML document
1389 * @param array $owner Contact data of the poster
1391 * @return object author element
1393 private static function addAuthor($doc, $owner)
1395 $r = q("SELECT `homepage`, `publish` FROM `profile` WHERE `uid` = %d AND `is-default` LIMIT 1", intval($owner["uid"]));
1396 if (DBM::is_result($r)) {
1399 $author = $doc->createElement("author");
1400 XML::addElement($doc, $author, "id", $owner["url"]);
1401 XML::addElement($doc, $author, "activity:object-type", ACTIVITY_OBJ_PERSON);
1402 XML::addElement($doc, $author, "uri", $owner["url"]);
1403 XML::addElement($doc, $author, "name", $owner["nick"]);
1404 XML::addElement($doc, $author, "email", $owner["addr"]);
1405 XML::addElement($doc, $author, "summary", bbcode($owner["about"], false, false, 7));
1407 $attributes = ["rel" => "alternate", "type" => "text/html", "href" => $owner["url"]];
1408 XML::addElement($doc, $author, "link", "", $attributes);
1412 "type" => "image/jpeg", // To-Do?
1413 "media:width" => 175,
1414 "media:height" => 175,
1415 "href" => $owner["photo"]];
1416 XML::addElement($doc, $author, "link", "", $attributes);
1418 if (isset($owner["thumb"])) {
1421 "type" => "image/jpeg", // To-Do?
1422 "media:width" => 80,
1423 "media:height" => 80,
1424 "href" => $owner["thumb"]];
1425 XML::addElement($doc, $author, "link", "", $attributes);
1428 XML::addElement($doc, $author, "poco:preferredUsername", $owner["nick"]);
1429 XML::addElement($doc, $author, "poco:displayName", $owner["name"]);
1430 XML::addElement($doc, $author, "poco:note", bbcode($owner["about"], false, false, 7));
1432 if (trim($owner["location"]) != "") {
1433 $element = $doc->createElement("poco:address");
1434 XML::addElement($doc, $element, "poco:formatted", $owner["location"]);
1435 $author->appendChild($element);
1438 if (trim($profile["homepage"]) != "") {
1439 $urls = $doc->createElement("poco:urls");
1440 XML::addElement($doc, $urls, "poco:type", "homepage");
1441 XML::addElement($doc, $urls, "poco:value", $profile["homepage"]);
1442 XML::addElement($doc, $urls, "poco:primary", "true");
1443 $author->appendChild($urls);
1446 if (count($profile)) {
1447 XML::addElement($doc, $author, "followers", "", ["url" => System::baseUrl()."/viewcontacts/".$owner["nick"]]);
1448 XML::addElement($doc, $author, "statusnet:profile_info", "", ["local_id" => $owner["uid"]]);
1451 if ($profile["publish"]) {
1452 XML::addElement($doc, $author, "mastodon:scope", "public");
1458 * @TODO Picture attachments should look like this:
1459 * <a href="https://status.pirati.ca/attachment/572819" title="https://status.pirati.ca/file/heluecht-20151202T222602-rd3u49p.gif"
1460 * class="attachment thumbnail" id="attachment-572819" rel="nofollow external">https://status.pirati.ca/attachment/572819</a>
1464 * @brief Returns the given activity if present - otherwise returns the "post" activity
1466 * @param array $item Data of the item that is to be posted
1468 * @return string activity
1470 private static function constructVerb($item)
1472 if ($item['verb']) {
1473 return $item['verb'];
1476 return ACTIVITY_POST;
1480 * @brief Returns the given object type if present - otherwise returns the "note" object type
1482 * @param array $item Data of the item that is to be posted
1484 * @return string Object type
1486 private static function constructObjecttype($item)
1488 if (in_array($item['object-type'], [ACTIVITY_OBJ_NOTE, ACTIVITY_OBJ_COMMENT]))
1489 return $item['object-type'];
1490 return ACTIVITY_OBJ_NOTE;
1494 * @brief Adds an entry element to the XML document
1496 * @param object $doc XML document
1497 * @param array $item Data of the item that is to be posted
1498 * @param array $owner Contact data of the poster
1499 * @param bool $toplevel optional default false
1501 * @return object Entry element
1503 private static function entry($doc, $item, $owner, $toplevel = false)
1505 $repeated_guid = self::getResharedGuid($item);
1506 if ($repeated_guid != "") {
1507 $xml = self::reshareEntry($doc, $item, $owner, $repeated_guid, $toplevel);
1514 if ($item["verb"] == ACTIVITY_LIKE) {
1515 return self::likeEntry($doc, $item, $owner, $toplevel);
1516 } elseif (in_array($item["verb"], [ACTIVITY_FOLLOW, NAMESPACE_OSTATUS."/unfollow"])) {
1517 return self::followEntry($doc, $item, $owner, $toplevel);
1519 return self::noteEntry($doc, $item, $owner, $toplevel);
1524 * @brief Adds a source entry to the XML document
1526 * @param object $doc XML document
1527 * @param array $contact Array of the contact that is added
1529 * @return object Source element
1531 private static function sourceEntry($doc, $contact)
1533 $source = $doc->createElement("source");
1534 XML::addElement($doc, $source, "id", $contact["poll"]);
1535 XML::addElement($doc, $source, "title", $contact["name"]);
1536 XML::addElement($doc, $source, "link", "", ["rel" => "alternate", "type" => "text/html", "href" => $contact["alias"]]);
1537 XML::addElement($doc, $source, "link", "", ["rel" => "self", "type" => "application/atom+xml", "href" => $contact["poll"]]);
1538 XML::addElement($doc, $source, "icon", $contact["photo"]);
1539 XML::addElement($doc, $source, "updated", datetime_convert("UTC", "UTC", $contact["success_update"]."+00:00", ATOM_TIME));
1545 * @brief Fetches contact data from the contact or the gcontact table
1547 * @param string $url URL of the contact
1548 * @param array $owner Contact data of the poster
1550 * @return array Contact array
1552 private static function contactEntry($url, $owner)
1555 "SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` IN (0, %d) ORDER BY `uid` DESC LIMIT 1",
1556 dbesc(normalise_link($url)),
1557 intval($owner["uid"])
1559 if (DBM::is_result($r)) {
1561 $contact["uid"] = -1;
1564 if (!DBM::is_result($r)) {
1566 "SELECT * FROM `gcontact` WHERE `nurl` = '%s' LIMIT 1",
1567 dbesc(normalise_link($url))
1569 if (DBM::is_result($r)) {
1571 $contact["uid"] = -1;
1572 $contact["success_update"] = $contact["updated"];
1576 if (!DBM::is_result($r)) {
1580 if (!isset($contact["poll"])) {
1581 $data = Probe::uri($url);
1582 $contact["poll"] = $data["poll"];
1584 if (!$contact["alias"]) {
1585 $contact["alias"] = $data["alias"];
1589 if (!isset($contact["alias"])) {
1590 $contact["alias"] = $contact["url"];
1597 * @brief Adds an entry element with reshared content
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 string $repeated_guid guid
1603 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1605 * @return object Entry element
1607 private static function reshareEntry($doc, $item, $owner, $repeated_guid, $toplevel)
1609 if (($item["id"] != $item["parent"]) && (normalise_link($item["author-link"]) != normalise_link($owner["url"]))) {
1610 logger("OStatus entry is from author ".$owner["url"]." - not from ".$item["author-link"].". Quitting.", LOGGER_DEBUG);
1613 $title = self::entryHeader($doc, $entry, $owner, $toplevel);
1616 "SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' AND NOT `private` AND `network` IN ('%s', '%s', '%s') LIMIT 1",
1617 intval($owner["uid"]),
1618 dbesc($repeated_guid),
1619 dbesc(NETWORK_DFRN),
1620 dbesc(NETWORK_DIASPORA),
1621 dbesc(NETWORK_OSTATUS)
1623 if (DBM::is_result($r)) {
1624 $repeated_item = $r[0];
1628 $contact = self::contactEntry($repeated_item['author-link'], $owner);
1630 $parent_item = (($item['thr-parent']) ? $item['thr-parent'] : $item['parent-uri']);
1632 $title = $owner["nick"]." repeated a notice by ".$contact["nick"];
1634 self::entryContent($doc, $entry, $item, $owner, $title, ACTIVITY_SHARE, false);
1636 $as_object = $doc->createElement("activity:object");
1638 XML::addElement($doc, $as_object, "activity:object-type", NAMESPACE_ACTIVITY_SCHEMA."activity");
1640 self::entryContent($doc, $as_object, $repeated_item, $owner, "", "", false);
1642 $author = self::addAuthor($doc, $contact);
1643 $as_object->appendChild($author);
1645 $as_object2 = $doc->createElement("activity:object");
1647 XML::addElement($doc, $as_object2, "activity:object-type", self::constructObjecttype($repeated_item));
1649 $title = sprintf("New comment by %s", $contact["nick"]);
1651 self::entryContent($doc, $as_object2, $repeated_item, $owner, $title);
1653 $as_object->appendChild($as_object2);
1655 self::entryFooter($doc, $as_object, $item, $owner, false);
1657 $source = self::sourceEntry($doc, $contact);
1659 $as_object->appendChild($source);
1661 $entry->appendChild($as_object);
1663 self::entryFooter($doc, $entry, $item, $owner);
1669 * @brief Adds an entry element with a "like"
1671 * @param object $doc XML document
1672 * @param array $item Data of the item that is to be posted
1673 * @param array $owner Contact data of the poster
1674 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1676 * @return object Entry element with "like"
1678 private static function likeEntry($doc, $item, $owner, $toplevel)
1680 if (($item["id"] != $item["parent"]) && (normalise_link($item["author-link"]) != normalise_link($owner["url"]))) {
1681 logger("OStatus entry is from author ".$owner["url"]." - not from ".$item["author-link"].". Quitting.", LOGGER_DEBUG);
1684 $title = self::entryHeader($doc, $entry, $owner, $toplevel);
1686 $verb = NAMESPACE_ACTIVITY_SCHEMA."favorite";
1687 self::entryContent($doc, $entry, $item, $owner, "Favorite", $verb, false);
1689 $as_object = $doc->createElement("activity:object");
1692 "SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d",
1693 dbesc($item["thr-parent"]),
1694 intval($item["uid"])
1696 $parent_item = (($item['thr-parent']) ? $item['thr-parent'] : $item['parent-uri']);
1698 XML::addElement($doc, $as_object, "activity:object-type", self::constructObjecttype($parent[0]));
1700 self::entryContent($doc, $as_object, $parent[0], $owner, "New entry");
1702 $entry->appendChild($as_object);
1704 self::entryFooter($doc, $entry, $item, $owner);
1710 * @brief Adds the person object element to the XML document
1712 * @param object $doc XML document
1713 * @param array $owner Contact data of the poster
1714 * @param array $contact Contact data of the target
1716 * @return object author element
1718 private static function addPersonObject($doc, $owner, $contact)
1720 $object = $doc->createElement("activity:object");
1721 XML::addElement($doc, $object, "activity:object-type", ACTIVITY_OBJ_PERSON);
1723 if ($contact['network'] == NETWORK_PHANTOM) {
1724 XML::addElement($doc, $object, "id", $contact['url']);
1728 XML::addElement($doc, $object, "id", $contact["alias"]);
1729 XML::addElement($doc, $object, "title", $contact["nick"]);
1731 $attributes = ["rel" => "alternate", "type" => "text/html", "href" => $contact["url"]];
1732 XML::addElement($doc, $object, "link", "", $attributes);
1736 "type" => "image/jpeg", // To-Do?
1737 "media:width" => 175,
1738 "media:height" => 175,
1739 "href" => $contact["photo"]];
1740 XML::addElement($doc, $object, "link", "", $attributes);
1742 XML::addElement($doc, $object, "poco:preferredUsername", $contact["nick"]);
1743 XML::addElement($doc, $object, "poco:displayName", $contact["name"]);
1745 if (trim($contact["location"]) != "") {
1746 $element = $doc->createElement("poco:address");
1747 XML::addElement($doc, $element, "poco:formatted", $contact["location"]);
1748 $object->appendChild($element);
1755 * @brief Adds a follow/unfollow entry element
1757 * @param object $doc XML document
1758 * @param array $item Data of the follow/unfollow message
1759 * @param array $owner Contact data of the poster
1760 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1762 * @return object Entry element
1764 private static function followEntry($doc, $item, $owner, $toplevel)
1766 $item["id"] = $item["parent"] = 0;
1767 $item["created"] = $item["edited"] = date("c");
1768 $item["private"] = true;
1770 $contact = Probe::uri($item['follow']);
1772 if ($contact['alias'] == '') {
1773 $contact['alias'] = $contact["url"];
1775 $item['follow'] = $contact['alias'];
1779 "SELECT `id` FROM `contact` WHERE `uid` = %d AND `nurl` = '%s'",
1780 intval($owner['uid']),
1781 dbesc(normalise_link($contact["url"]))
1784 if (DBM::is_result($r)) {
1785 $connect_id = $r[0]['id'];
1790 if ($item['verb'] == ACTIVITY_FOLLOW) {
1791 $message = L10n::t('%s is now following %s.');
1792 $title = L10n::t('following');
1793 $action = "subscription";
1795 $message = L10n::t('%s stopped following %s.');
1796 $title = L10n::t('stopped following');
1797 $action = "unfollow";
1800 $item["uri"] = $item['parent-uri'] = $item['thr-parent']
1801 = 'tag:'.get_app()->get_hostname().
1802 ','.date('Y-m-d').':'.$action.':'.$owner['uid'].
1803 ':person:'.$connect_id.':'.$item['created'];
1805 $item["body"] = sprintf($message, $owner["nick"], $contact["nick"]);
1807 self::entryHeader($doc, $entry, $owner, $toplevel);
1809 self::entryContent($doc, $entry, $item, $owner, $title);
1811 $object = self::addPersonObject($doc, $owner, $contact);
1812 $entry->appendChild($object);
1814 self::entryFooter($doc, $entry, $item, $owner);
1820 * @brief Adds a regular entry element
1822 * @param object $doc XML document
1823 * @param array $item Data of the item that is to be posted
1824 * @param array $owner Contact data of the poster
1825 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1827 * @return object Entry element
1829 private static function noteEntry($doc, $item, $owner, $toplevel)
1831 if (($item["id"] != $item["parent"]) && (normalise_link($item["author-link"]) != normalise_link($owner["url"]))) {
1832 logger("OStatus entry is from author ".$owner["url"]." - not from ".$item["author-link"].". Quitting.", LOGGER_DEBUG);
1835 $title = self::entryHeader($doc, $entry, $owner, $toplevel);
1837 XML::addElement($doc, $entry, "activity:object-type", ACTIVITY_OBJ_NOTE);
1839 self::entryContent($doc, $entry, $item, $owner, $title);
1841 self::entryFooter($doc, $entry, $item, $owner);
1847 * @brief Adds a header element to the XML document
1849 * @param object $doc XML document
1850 * @param object $entry The entry element where the elements are added
1851 * @param array $owner Contact data of the poster
1852 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1854 * @return string The title for the element
1856 private static function entryHeader($doc, &$entry, $owner, $toplevel)
1858 /// @todo Check if this title stuff is really needed (I guess not)
1860 $entry = $doc->createElement("entry");
1861 $title = sprintf("New note by %s", $owner["nick"]);
1863 $entry = $doc->createElementNS(NAMESPACE_ATOM1, "entry");
1865 $entry->setAttribute("xmlns:thr", NAMESPACE_THREAD);
1866 $entry->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
1867 $entry->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
1868 $entry->setAttribute("xmlns:media", NAMESPACE_MEDIA);
1869 $entry->setAttribute("xmlns:poco", NAMESPACE_POCO);
1870 $entry->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
1871 $entry->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
1872 $entry->setAttribute("xmlns:mastodon", NAMESPACE_MASTODON);
1874 $author = self::addAuthor($doc, $owner);
1875 $entry->appendChild($author);
1877 $title = sprintf("New comment by %s", $owner["nick"]);
1883 * @brief Adds elements to the XML document
1885 * @param object $doc XML document
1886 * @param object $entry Entry element where the content is added
1887 * @param array $item Data of the item that is to be posted
1888 * @param array $owner Contact data of the poster
1889 * @param string $title Title for the post
1890 * @param string $verb The activity verb
1891 * @param bool $complete Add the "status_net" element?
1894 private static function entryContent($doc, $entry, $item, $owner, $title, $verb = "", $complete = true)
1897 $verb = self::constructVerb($item);
1900 XML::addElement($doc, $entry, "id", $item["uri"]);
1901 XML::addElement($doc, $entry, "title", $title);
1903 $body = self::formatPicturePost($item['body']);
1905 if ($item['title'] != "") {
1906 $body = "[b]".$item['title']."[/b]\n\n".$body;
1909 $body = bbcode($body, false, false, 7);
1911 XML::addElement($doc, $entry, "content", $body, ["type" => "html"]);
1913 XML::addElement($doc, $entry, "link", "", ["rel" => "alternate", "type" => "text/html",
1914 "href" => System::baseUrl()."/display/".$item["guid"]]
1917 if ($complete && ($item["id"] > 0)) {
1918 XML::addElement($doc, $entry, "status_net", "", ["notice_id" => $item["id"]]);
1921 XML::addElement($doc, $entry, "activity:verb", $verb);
1923 XML::addElement($doc, $entry, "published", datetime_convert("UTC", "UTC", $item["created"]."+00:00", ATOM_TIME));
1924 XML::addElement($doc, $entry, "updated", datetime_convert("UTC", "UTC", $item["edited"]."+00:00", ATOM_TIME));
1928 * @brief Adds the elements at the foot of an entry to the XML document
1930 * @param object $doc XML document
1931 * @param object $entry The entry element where the elements are added
1932 * @param array $item Data of the item that is to be posted
1933 * @param array $owner Contact data of the poster
1934 * @param bool $complete default true
1937 private static function entryFooter($doc, $entry, $item, $owner, $complete = true)
1941 if (($item['parent'] != $item['id']) || ($item['parent-uri'] !== $item['uri']) || (($item['thr-parent'] !== '') && ($item['thr-parent'] !== $item['uri']))) {
1942 $parent = q("SELECT `guid`, `author-link`, `owner-link` FROM `item` WHERE `id` = %d", intval($item["parent"]));
1943 $parent_item = (($item['thr-parent']) ? $item['thr-parent'] : $item['parent-uri']);
1946 "SELECT `guid`, `author-link`, `owner-link`, `plink` FROM `item` WHERE `uid` = %d AND `uri` = '%s'",
1947 intval($owner["uid"]),
1951 $mentioned[$thrparent[0]["author-link"]] = $thrparent[0]["author-link"];
1952 $mentioned[$thrparent[0]["owner-link"]] = $thrparent[0]["owner-link"];
1953 $parent_plink = $thrparent[0]["plink"];
1955 $mentioned[$parent[0]["author-link"]] = $parent[0]["author-link"];
1956 $mentioned[$parent[0]["owner-link"]] = $parent[0]["owner-link"];
1957 $parent_plink = System::baseUrl()."/display/".$parent[0]["guid"];
1961 "ref" => $parent_item,
1962 "href" => $parent_plink];
1963 XML::addElement($doc, $entry, "thr:in-reply-to", "", $attributes);
1967 "href" => $parent_plink];
1968 XML::addElement($doc, $entry, "link", "", $attributes);
1971 if (intval($item["parent"]) > 0) {
1972 $conversation_href = System::baseUrl()."/display/".$owner["nick"]."/".$item["parent"];
1973 $conversation_uri = $conversation_href;
1975 if (isset($parent_item)) {
1976 $r = dba::fetch_first("SELECT `conversation-uri`, `conversation-href` FROM `conversation` WHERE `item-uri` = ?", $parent_item);
1977 if (DBM::is_result($r)) {
1978 if ($r['conversation-uri'] != '') {
1979 $conversation_uri = $r['conversation-uri'];
1981 if ($r['conversation-href'] != '') {
1982 $conversation_href = $r['conversation-href'];
1987 XML::addElement($doc, $entry, "link", "", ["rel" => "ostatus:conversation", "href" => $conversation_href]);
1990 "href" => $conversation_href,
1991 "local_id" => $item["parent"],
1992 "ref" => $conversation_uri];
1994 XML::addElement($doc, $entry, "ostatus:conversation", $conversation_uri, $attributes);
1997 $tags = item_getfeedtags($item);
2000 foreach ($tags as $t) {
2002 $mentioned[$t[1]] = $t[1];
2007 // Make sure that mentions are accepted (GNU Social has problems with mixing HTTP and HTTPS)
2009 foreach ($mentioned as $mention) {
2010 $newmentions[str_replace("http://", "https://", $mention)] = str_replace("http://", "https://", $mention);
2011 $newmentions[str_replace("https://", "http://", $mention)] = str_replace("https://", "http://", $mention);
2013 $mentioned = $newmentions;
2015 foreach ($mentioned as $mention) {
2017 "SELECT `forum`, `prv` FROM `contact` WHERE `uid` = %d AND `nurl` = '%s'",
2018 intval($owner["uid"]),
2019 dbesc(normalise_link($mention))
2021 if ($r[0]["forum"] || $r[0]["prv"]) {
2022 XML::addElement($doc, $entry, "link", "",
2024 "rel" => "mentioned",
2025 "ostatus:object-type" => ACTIVITY_OBJ_GROUP,
2029 XML::addElement($doc, $entry, "link", "",
2031 "rel" => "mentioned",
2032 "ostatus:object-type" => ACTIVITY_OBJ_PERSON,
2038 if (!$item["private"]) {
2039 XML::addElement($doc, $entry, "link", "", ["rel" => "ostatus:attention",
2040 "href" => "http://activityschema.org/collection/public"]);
2041 XML::addElement($doc, $entry, "link", "", ["rel" => "mentioned",
2042 "ostatus:object-type" => "http://activitystrea.ms/schema/1.0/collection",
2043 "href" => "http://activityschema.org/collection/public"]);
2044 XML::addElement($doc, $entry, "mastodon:scope", "public");
2048 foreach ($tags as $t) {
2050 XML::addElement($doc, $entry, "category", "", ["term" => $t[2]]);
2055 self::getAttachment($doc, $entry, $item);
2057 if ($complete && ($item["id"] > 0)) {
2058 $app = $item["app"];
2063 $attributes = ["local_id" => $item["id"], "source" => $app];
2065 if (isset($parent["id"])) {
2066 $attributes["repeat_of"] = $parent["id"];
2069 if ($item["coord"] != "") {
2070 XML::addElement($doc, $entry, "georss:point", $item["coord"]);
2073 XML::addElement($doc, $entry, "statusnet:notice_info", "", $attributes);
2078 * Creates the XML feed for a given nickname
2080 * Supported filters:
2081 * - activity (default): all the public posts
2082 * - posts: all the public top-level posts
2083 * - comments: all the public replies
2085 * Updates the provided last_update parameter if the result comes from the
2086 * cache or it is empty
2088 * @brief Creates the XML feed for a given nickname
2090 * @param string $owner_nick Nickname of the feed owner
2091 * @param string $last_update Date of the last update
2092 * @param integer $max_items Number of maximum items to fetch
2093 * @param string $filter Feed items filter (activity, posts or comments)
2094 * @param boolean $nocache Wether to bypass caching
2096 * @return string XML feed
2098 public static function feed($owner_nick, &$last_update, $max_items = 300, $filter = 'activity', $nocache = false)
2100 $stamp = microtime(true);
2102 $cachekey = "ostatus:feed:" . $owner_nick . ":" . $filter . ":" . $last_update;
2104 $previous_created = $last_update;
2106 $result = Cache::get($cachekey);
2107 if (!$nocache && !is_null($result)) {
2108 logger('Feed duration: ' . number_format(microtime(true) - $stamp, 3) . ' - ' . $owner_nick . ' - ' . $filter . ' - ' . $previous_created . ' (cached)', LOGGER_DEBUG);
2109 $last_update = $result['last_update'];
2110 return $result['feed'];
2113 $owner = dba::fetch_first(
2114 "SELECT `contact`.*, `user`.`nickname`, `user`.`timezone`, `user`.`page-flags`
2115 FROM `contact` INNER JOIN `user` ON `user`.`uid` = `contact`.`uid`
2116 WHERE `contact`.`self` AND `user`.`nickname` = ? LIMIT 1",
2119 if (!DBM::is_result($owner)) {
2123 if (!strlen($last_update)) {
2124 $last_update = 'now -30 days';
2127 $check_date = datetime_convert('UTC', 'UTC', $last_update, 'Y-m-d H:i:s');
2128 $authorid = Contact::getIdForURL($owner["url"], 0);
2131 if ($filter === 'posts') {
2132 $sql_extra .= ' AND `item`.`id` = `item`.`parent` ';
2135 if ($filter === 'comments') {
2136 $sql_extra .= sprintf(" AND `item`.`object-type` = '%s' ", dbesc(ACTIVITY_OBJ_COMMENT));
2140 "SELECT `item`.*, `item`.`id` AS `item_id` FROM `item` USE INDEX (`uid_contactid_created`)
2141 STRAIGHT_JOIN `thread` ON `thread`.`iid` = `item`.`parent`
2142 WHERE `item`.`uid` = %d
2143 AND `item`.`contact-id` = %d
2144 AND `item`.`author-id` = %d
2145 AND `item`.`created` > '%s'
2146 AND NOT `item`.`deleted`
2147 AND NOT `item`.`private`
2148 AND `thread`.`network` IN ('%s', '%s')
2150 ORDER BY `item`.`created` DESC LIMIT %d",
2151 intval($owner["uid"]),
2152 intval($owner["id"]),
2155 dbesc(NETWORK_OSTATUS),
2156 dbesc(NETWORK_DFRN),
2160 $doc = new DOMDocument('1.0', 'utf-8');
2161 $doc->formatOutput = true;
2163 $root = self::addHeader($doc, $owner, $filter);
2165 foreach ($items as $item) {
2166 if (Config::get('system', 'ostatus_debug')) {
2167 $item['body'] .= '🍼';
2169 $entry = self::entry($doc, $item, $owner);
2170 $root->appendChild($entry);
2172 if ($last_update < $item['created']) {
2173 $last_update = $item['created'];
2177 $feeddata = trim($doc->saveXML());
2179 $msg = ['feed' => $feeddata, 'last_update' => $last_update];
2180 Cache::set($cachekey, $msg, CACHE_QUARTER_HOUR);
2182 logger('Feed duration: ' . number_format(microtime(true) - $stamp, 3) . ' - ' . $owner_nick . ' - ' . $filter . ' - ' . $previous_created, LOGGER_DEBUG);
2188 * @brief Creates the XML for a salmon message
2190 * @param array $item Data of the item that is to be posted
2191 * @param array $owner Contact data of the poster
2193 * @return string XML for the salmon
2195 public static function salmon($item, $owner)
2197 $doc = new DOMDocument('1.0', 'utf-8');
2198 $doc->formatOutput = true;
2200 if (Config::get('system', 'ostatus_debug')) {
2201 $item['body'] .= '🐟';
2204 $entry = self::entry($doc, $item, $owner, true);
2206 $doc->appendChild($entry);
2208 return trim($doc->saveXML());