3 * @file src/Protocol/OStatus.php
5 namespace Friendica\Protocol;
7 use Friendica\Content\Text\BBCode;
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\Conversation;
15 use Friendica\Model\GContact;
16 use Friendica\Model\Item;
17 use Friendica\Network\Probe;
18 use Friendica\Object\Image;
19 use Friendica\Util\DateTimeFormat;
20 use Friendica\Util\Lock;
21 use Friendica\Util\Network;
22 use Friendica\Util\XML;
27 require_once 'include/dba.php';
28 require_once 'include/html2bbcode.php';
29 require_once 'include/items.php';
30 require_once 'mod/share.php';
31 require_once 'include/enotify.php';
32 require_once 'include/api.php';
33 require_once 'mod/proxy.php';
36 * @brief This class contain functions for the OStatus protocol
40 private static $itemlist;
41 private static $conv_list = [];
44 * @brief Fetches author data
46 * @param object $xpath The xpath object
47 * @param object $context The xml context of the author details
48 * @param array $importer user record of the importing user
49 * @param array $contact Called by reference, will contain the fetched contact
50 * @param bool $onlyfetch Only fetch the header without updating the contact entries
52 * @return array Array of author related entries for the item
54 private static function fetchAuthor($xpath, $context, $importer, &$contact, $onlyfetch)
57 $author["author-link"] = $xpath->evaluate('atom:author/atom:uri/text()', $context)->item(0)->nodeValue;
58 $author["author-name"] = $xpath->evaluate('atom:author/atom:name/text()', $context)->item(0)->nodeValue;
59 $addr = $xpath->evaluate('atom:author/atom:email/text()', $context)->item(0)->nodeValue;
61 $aliaslink = $author["author-link"];
63 $alternate = $xpath->query("atom:author/atom:link[@rel='alternate']", $context)->item(0)->attributes;
64 if (is_object($alternate)) {
65 foreach ($alternate as $attributes) {
66 if (($attributes->name == "href") && ($attributes->textContent != "")) {
67 $author["author-link"] = $attributes->textContent;
71 $author["contact-id"] = $contact["id"];
74 if ($aliaslink != '') {
75 $condition = ["`uid` = ? AND `alias` = ? AND `network` != ?",
76 $importer["uid"], $aliaslink, NETWORK_STATUSNET];
77 $contact = dba::selectFirst('contact', [], $condition);
80 if (!DBM::is_result($contact) && $author["author-link"] != '') {
81 if ($aliaslink == "") {
82 $aliaslink = $author["author-link"];
85 $condition = ["`uid` = ? AND `nurl` IN (?, ?) AND `network` != ?", $importer["uid"],
86 normalise_link($author["author-link"]), normalise_link($aliaslink), NETWORK_STATUSNET];
87 $contact = dba::selectFirst('contact', [], $condition);
90 if (!DBM::is_result($contact) && ($addr != '')) {
91 $condition = ["`uid` = ? AND `addr` = ? AND `network` != ?",
92 $importer["uid"], $addr, NETWORK_STATUSNET];
93 $contact = dba::selectFirst('contact', [], $condition);
96 if (DBM::is_result($contact)) {
97 if ($contact['blocked']) {
100 $author["contact-id"] = $contact["id"];
104 $avatars = $xpath->query("atom:author/atom:link[@rel='avatar']", $context);
105 foreach ($avatars as $avatar) {
108 foreach ($avatar->attributes as $attributes) {
109 if ($attributes->name == "href") {
110 $href = $attributes->textContent;
112 if ($attributes->name == "width") {
113 $width = $attributes->textContent;
117 $avatarlist[$width] = $href;
120 if (count($avatarlist) > 0) {
122 $author["author-avatar"] = Probe::fixAvatar(current($avatarlist), $author["author-link"]);
125 $displayname = $xpath->evaluate('atom:author/poco:displayName/text()', $context)->item(0)->nodeValue;
126 if ($displayname != "") {
127 $author["author-name"] = $displayname;
130 $author["owner-name"] = $author["author-name"];
131 $author["owner-link"] = $author["author-link"];
132 $author["owner-avatar"] = $author["author-avatar"];
134 // Only update the contacts if it is an OStatus contact
135 if (DBM::is_result($contact) && ($contact['id'] > 0) && !$onlyfetch && ($contact["network"] == NETWORK_OSTATUS)) {
137 // Update contact data
139 unset($current['name-date']);
141 // This query doesn't seem to work
142 // $value = $xpath->query("atom:link[@rel='salmon']", $context)->item(0)->nodeValue;
144 // $contact["notify"] = $value;
146 // This query doesn't seem to work as well - I hate these queries
147 // $value = $xpath->query("atom:link[@rel='self' and @type='application/atom+xml']", $context)->item(0)->nodeValue;
149 // $contact["poll"] = $value;
151 $contact['url'] = $author["author-link"];
152 $contact['nurl'] = normalise_link($contact['url']);
154 $value = $xpath->evaluate('atom:author/atom:uri/text()', $context)->item(0)->nodeValue;
156 $contact["alias"] = $value;
159 $value = $xpath->evaluate('atom:author/poco:displayName/text()', $context)->item(0)->nodeValue;
161 $contact["name"] = $value;
164 $value = $xpath->evaluate('atom:author/poco:preferredUsername/text()', $context)->item(0)->nodeValue;
166 $contact["nick"] = $value;
169 $value = $xpath->evaluate('atom:author/poco:note/text()', $context)->item(0)->nodeValue;
171 $contact["about"] = html2bbcode($value);
174 $value = $xpath->evaluate('atom:author/poco:address/poco:formatted/text()', $context)->item(0)->nodeValue;
176 $contact["location"] = $value;
179 $contact['name-date'] = DateTimeFormat::utcNow();
181 dba::update('contact', $contact, ['id' => $contact["id"]], $current);
183 if (!empty($author["author-avatar"]) && ($author["author-avatar"] != $current['avatar'])) {
184 logger("Update profile picture for contact ".$contact["id"], LOGGER_DEBUG);
185 Contact::updateAvatar($author["author-avatar"], $importer["uid"], $contact["id"]);
188 // Ensure that we are having this contact (with uid=0)
189 $cid = Contact::getIdForURL($aliaslink, 0, true);
192 $fields = ['url', 'nurl', 'name', 'nick', 'alias', 'about', 'location'];
193 $old_contact = dba::selectFirst('contact', $fields, ['id' => $cid]);
195 // Update it with the current values
196 $fields = ['url' => $author["author-link"], 'name' => $contact["name"],
197 'nurl' => normalise_link($author["author-link"]),
198 'nick' => $contact["nick"], 'alias' => $contact["alias"],
199 'about' => $contact["about"], 'location' => $contact["location"],
200 'success_update' => DateTimeFormat::utcNow(), 'last-update' => DateTimeFormat::utcNow()];
202 dba::update('contact', $fields, ['id' => $cid], $old_contact);
205 Contact::updateAvatar($author["author-avatar"], 0, $cid);
208 $contact["generation"] = 2;
209 $contact["hide"] = false; // OStatus contacts are never hidden
210 $contact["photo"] = $author["author-avatar"];
211 $gcid = GContact::update($contact);
213 GContact::link($gcid, $contact["uid"], $contact["id"]);
220 * @brief Fetches author data from a given XML string
222 * @param string $xml The XML
223 * @param array $importer user record of the importing user
225 * @return array Array of author related entries for the item
227 public static function salmonAuthor($xml, $importer)
233 $doc = new DOMDocument();
234 @$doc->loadXML($xml);
236 $xpath = new DOMXPath($doc);
237 $xpath->registerNamespace('atom', NAMESPACE_ATOM1);
238 $xpath->registerNamespace('thr', NAMESPACE_THREAD);
239 $xpath->registerNamespace('georss', NAMESPACE_GEORSS);
240 $xpath->registerNamespace('activity', NAMESPACE_ACTIVITY);
241 $xpath->registerNamespace('media', NAMESPACE_MEDIA);
242 $xpath->registerNamespace('poco', NAMESPACE_POCO);
243 $xpath->registerNamespace('ostatus', NAMESPACE_OSTATUS);
244 $xpath->registerNamespace('statusnet', NAMESPACE_STATUSNET);
246 $entries = $xpath->query('/atom:entry');
248 foreach ($entries as $entry) {
250 $author = self::fetchAuthor($xpath, $entry, $importer, $contact, true);
256 * @brief Read attributes from element
258 * @param object $element Element object
260 * @return array attributes
262 private static function readAttributes($element)
266 foreach ($element->attributes as $attributes) {
267 $attribute[$attributes->name] = $attributes->textContent;
274 * @brief Imports an XML string containing OStatus elements
276 * @param string $xml The XML
277 * @param array $importer user record of the importing user
278 * @param array $contact contact
279 * @param string $hub Called by reference, returns the fetched hub data
282 public static function import($xml, $importer, &$contact, &$hub)
284 self::process($xml, $importer, $contact, $hub);
288 * @brief Internal feed processing
290 * @param string $xml The XML
291 * @param array $importer user record of the importing user
292 * @param array $contact contact
293 * @param string $hub Called by reference, returns the fetched hub data
294 * @param boolean $stored Is the post fresh imported or from the database?
295 * @param boolean $initialize Is it the leading post so that data has to be initialized?
297 * @return boolean Could the XML be processed?
299 private static function process($xml, $importer, &$contact, &$hub, $stored = false, $initialize = true)
302 self::$itemlist = [];
303 self::$conv_list = [];
306 logger("Import OStatus message", LOGGER_DEBUG);
311 $doc = new DOMDocument();
312 @$doc->loadXML($xml);
314 $xpath = new DOMXPath($doc);
315 $xpath->registerNamespace('atom', NAMESPACE_ATOM1);
316 $xpath->registerNamespace('thr', NAMESPACE_THREAD);
317 $xpath->registerNamespace('georss', NAMESPACE_GEORSS);
318 $xpath->registerNamespace('activity', NAMESPACE_ACTIVITY);
319 $xpath->registerNamespace('media', NAMESPACE_MEDIA);
320 $xpath->registerNamespace('poco', NAMESPACE_POCO);
321 $xpath->registerNamespace('ostatus', NAMESPACE_OSTATUS);
322 $xpath->registerNamespace('statusnet', NAMESPACE_STATUSNET);
325 $hub_attributes = $xpath->query("/atom:feed/atom:link[@rel='hub']")->item(0)->attributes;
326 if (is_object($hub_attributes)) {
327 foreach ($hub_attributes as $hub_attribute) {
328 if ($hub_attribute->name == "href") {
329 $hub = $hub_attribute->textContent;
330 logger("Found hub ".$hub, LOGGER_DEBUG);
336 $header["uid"] = $importer["uid"];
337 $header["network"] = NETWORK_OSTATUS;
338 $header["type"] = "remote";
340 $header["origin"] = 0;
341 $header["gravity"] = GRAVITY_PARENT;
343 $first_child = $doc->firstChild->tagName;
345 if ($first_child == "feed") {
346 $entries = $xpath->query('/atom:feed/atom:entry');
348 $entries = $xpath->query('/atom:entry');
351 if ($entries->length == 1) {
352 // We reformat the XML to make it better readable
353 $doc2 = new DOMDocument();
354 $doc2->loadXML($xml);
355 $doc2->preserveWhiteSpace = false;
356 $doc2->formatOutput = true;
357 $xml2 = $doc2->saveXML();
359 $header["protocol"] = PROTOCOL_OSTATUS_SALMON;
360 $header["source"] = $xml2;
361 } elseif (!$initialize) {
365 // Fetch the first author
366 $authordata = $xpath->query('//author')->item(0);
367 $author = self::fetchAuthor($xpath, $authordata, $importer, $contact, $stored);
369 $entry = $xpath->query('/atom:entry');
371 // Reverse the order of the entries
374 foreach ($entries as $entry) {
375 $entrylist[] = $entry;
378 foreach (array_reverse($entrylist) as $entry) {
380 $authorelement = $xpath->query('/atom:entry/atom:author', $entry);
382 if ($authorelement->length == 0) {
383 $authorelement = $xpath->query('atom:author', $entry);
386 if ($authorelement->length > 0) {
387 $author = self::fetchAuthor($xpath, $entry, $importer, $contact, $stored);
390 $value = $xpath->evaluate('atom:author/poco:preferredUsername/text()', $entry)->item(0)->nodeValue;
394 $nickname = $author["author-name"];
397 $item = array_merge($header, $author);
399 $item["uri"] = $xpath->query('atom:id/text()', $entry)->item(0)->nodeValue;
401 $item["verb"] = $xpath->query('activity:verb/text()', $entry)->item(0)->nodeValue;
404 if (in_array($item["verb"], ['qvitter-delete-notice', ACTIVITY_DELETE, 'delete'])) {
405 self::deleteNotice($item);
409 if (in_array($item["verb"], [NAMESPACE_OSTATUS."/unfavorite", ACTIVITY_UNFAVORITE])) {
410 // Ignore "Unfavorite" message
411 logger("Ignore unfavorite message ".print_r($item, true), LOGGER_DEBUG);
415 // Deletions come with the same uri, so we check for duplicates after processing deletions
416 if (dba::exists('item', ['uid' => $importer["uid"], 'uri' => $item["uri"]])) {
417 logger('Post with URI '.$item["uri"].' already existed for user '.$importer["uid"].'.', LOGGER_DEBUG);
420 logger('Processing post with URI '.$item["uri"].' for user '.$importer["uid"].'.', LOGGER_DEBUG);
423 if ($item["verb"] == ACTIVITY_JOIN) {
424 // ignore "Join" messages
425 logger("Ignore join message ".print_r($item, true), LOGGER_DEBUG);
429 if ($item["verb"] == "http://mastodon.social/schema/1.0/block") {
430 // ignore mastodon "block" messages
431 logger("Ignore block message ".print_r($item, true), LOGGER_DEBUG);
435 if ($item["verb"] == ACTIVITY_FOLLOW) {
436 Contact::addRelationship($importer, $contact, $item, $nickname);
440 if ($item["verb"] == NAMESPACE_OSTATUS."/unfollow") {
441 Contact::removeFollower($importer, $contact, $item, $dummy);
445 if ($item["verb"] == ACTIVITY_FAVORITE) {
446 $orig_uri = $xpath->query("activity:object/atom:id", $entry)->item(0)->nodeValue;
447 logger("Favorite ".$orig_uri." ".print_r($item, true));
449 $item["verb"] = ACTIVITY_LIKE;
450 $item["parent-uri"] = $orig_uri;
451 $item["gravity"] = GRAVITY_LIKE;
454 // http://activitystrea.ms/schema/1.0/rsvp-yes
455 if (!in_array($item["verb"], [ACTIVITY_POST, ACTIVITY_LIKE, ACTIVITY_SHARE])) {
456 logger("Unhandled verb ".$item["verb"]." ".print_r($item, true), LOGGER_DEBUG);
459 self::processPost($xpath, $entry, $item, $importer);
461 if ($initialize && (count(self::$itemlist) > 0)) {
462 if (self::$itemlist[0]['uri'] == self::$itemlist[0]['parent-uri']) {
463 // We will import it everytime, when it is started by our contacts
464 $valid = !empty(self::$itemlist[0]['contact-id']);
466 // If not, then it depends on this setting
467 $valid = !Config::get('system', 'ostatus_full_threads');
469 logger("Item with uri ".self::$itemlist[0]['uri']." will be imported due to the system settings.", LOGGER_DEBUG);
472 logger("Item with uri ".self::$itemlist[0]['uri']." belongs to a contact (".self::$itemlist[0]['contact-id']."). It will be imported.", LOGGER_DEBUG);
475 // Never post a thread when the only interaction by our contact was a like
477 $verbs = [ACTIVITY_POST, ACTIVITY_SHARE];
478 foreach (self::$itemlist as $item) {
479 if (!empty($item['contact-id']) && in_array($item['verb'], $verbs)) {
484 logger("Item with uri ".self::$itemlist[0]['uri']." will be imported since the thread contains posts or shares.", LOGGER_DEBUG);
488 // But we will only import complete threads
489 $valid = dba::exists('item', ['uid' => $importer["uid"], 'uri' => self::$itemlist[0]['parent-uri']]);
491 logger("Item with uri ".self::$itemlist[0]["uri"]." belongs to parent ".self::$itemlist[0]['parent-uri']." of user ".$importer["uid"].". It will be imported.", LOGGER_DEBUG);
496 $default_contact = 0;
497 $key = count(self::$itemlist);
498 for ($key = count(self::$itemlist) - 1; $key >= 0; $key--) {
499 if (empty(self::$itemlist[$key]['contact-id'])) {
500 self::$itemlist[$key]['contact-id'] = $default_contact;
502 $default_contact = $item['contact-id'];
505 foreach (self::$itemlist as $item) {
506 $found = dba::exists('item', ['uid' => $importer["uid"], 'uri' => $item["uri"]]);
508 logger("Item with uri ".$item["uri"]." for user ".$importer["uid"]." already exists.", LOGGER_DEBUG);
509 } elseif ($item['contact-id'] < 0) {
510 logger("Item with uri ".$item["uri"]." is from a blocked contact.", LOGGER_DEBUG);
512 // We are having duplicated entries. Hopefully this solves it.
513 if (Lock::set('ostatus_process_item_insert')) {
514 $ret = Item::insert($item);
515 Lock::remove('ostatus_process_item_insert');
516 logger("Item with uri ".$item["uri"]." for user ".$importer["uid"].' stored. Return value: '.$ret);
518 $ret = Item::insert($item);
519 logger("We couldn't lock - but tried to store the item anyway. Return value is ".$ret);
524 self::$itemlist = [];
526 logger('Processing done for post with URI '.$item["uri"].' for user '.$importer["uid"].'.', LOGGER_DEBUG);
532 * @param object $item item
535 private static function deleteNotice($item)
537 $condition = ['uid' => $item['uid'], 'author-link' => $item['author-link'], 'uri' => $item['uri']];
538 $deleted = dba::selectFirst('item', ['id', 'parent-uri'], $condition);
539 if (!DBM::is_result($deleted)) {
540 logger('Item from '.$item['author-link'].' with uri '.$item['uri'].' for user '.$item['uid']." wasn't found. We don't delete it. ");
544 Item::deleteById($deleted["id"]);
546 logger('Deleted item with uri '.$item['uri'].' for user '.$item['uid']);
550 * @brief Processes the XML for a post
552 * @param object $xpath The xpath object
553 * @param object $entry The xml entry that is processed
554 * @param array $item The item array
555 * @param array $importer user record of the importing user
558 private static function processPost($xpath, $entry, &$item, $importer)
560 $item["body"] = html2bbcode($xpath->query('atom:content/text()', $entry)->item(0)->nodeValue);
561 $item["object-type"] = $xpath->query('activity:object-type/text()', $entry)->item(0)->nodeValue;
562 if (($item["object-type"] == ACTIVITY_OBJ_BOOKMARK) || ($item["object-type"] == ACTIVITY_OBJ_EVENT)) {
563 $item["title"] = $xpath->query('atom:title/text()', $entry)->item(0)->nodeValue;
564 $item["body"] = $xpath->query('atom:summary/text()', $entry)->item(0)->nodeValue;
565 } elseif ($item["object-type"] == ACTIVITY_OBJ_QUESTION) {
566 $item["title"] = $xpath->query('atom:title/text()', $entry)->item(0)->nodeValue;
569 $item["created"] = $xpath->query('atom:published/text()', $entry)->item(0)->nodeValue;
570 $item["edited"] = $xpath->query('atom:updated/text()', $entry)->item(0)->nodeValue;
571 $conversation = $xpath->query('ostatus:conversation/text()', $entry)->item(0)->nodeValue;
572 $item['conversation-uri'] = $conversation;
574 $conv = $xpath->query('ostatus:conversation', $entry);
575 if (is_object($conv->item(0))) {
576 foreach ($conv->item(0)->attributes as $attributes) {
577 if ($attributes->name == "ref") {
578 $item['conversation-uri'] = $attributes->textContent;
580 if ($attributes->name == "href") {
581 $item['conversation-href'] = $attributes->textContent;
588 $inreplyto = $xpath->query('thr:in-reply-to', $entry);
589 if (is_object($inreplyto->item(0))) {
590 foreach ($inreplyto->item(0)->attributes as $attributes) {
591 if ($attributes->name == "ref") {
592 $item["parent-uri"] = $attributes->textContent;
594 if ($attributes->name == "href") {
595 $related = $attributes->textContent;
600 $georsspoint = $xpath->query('georss:point', $entry);
601 if (!empty($georsspoint) && ($georsspoint->length > 0)) {
602 $item["coord"] = $georsspoint->item(0)->nodeValue;
605 $categories = $xpath->query('atom:category', $entry);
607 foreach ($categories as $category) {
608 foreach ($category->attributes as $attributes) {
609 if ($attributes->name == "term") {
610 $term = $attributes->textContent;
611 if (strlen($item["tag"])) {
614 $item["tag"] .= "#[url=".System::baseUrl()."/search?tag=".$term."]".$term."[/url]";
623 $links = $xpath->query('atom:link', $entry);
625 $link_data = self::processLinks($links, $item);
626 $self = $link_data['self'];
627 $add_body = $link_data['add_body'];
632 $notice_info = $xpath->query('statusnet:notice_info', $entry);
633 if ($notice_info && ($notice_info->length > 0)) {
634 foreach ($notice_info->item(0)->attributes as $attributes) {
635 if ($attributes->name == "source") {
636 $item["app"] = strip_tags($attributes->textContent);
638 if ($attributes->name == "repeat_of") {
639 $repeat_of = $attributes->textContent;
643 // Is it a repeated post?
644 if (($repeat_of != "") || ($item["verb"] == ACTIVITY_SHARE)) {
645 $link_data = self::processRepeatedItem($xpath, $entry, $item, $importer);
646 if (!empty($link_data['add_body'])) {
647 $add_body .= $link_data['add_body'];
651 $item["body"] .= $add_body;
653 // Only add additional data when there is no picture in the post
654 if (!strstr($item["body"], '[/img]')) {
655 $item["body"] = add_page_info_to_body($item["body"]);
658 // Mastodon Content Warning
659 if (($item["verb"] == ACTIVITY_POST) && $xpath->evaluate('boolean(atom:summary)', $entry)) {
660 $clear_text = $xpath->query('atom:summary/text()', $entry)->item(0)->nodeValue;
662 $item["body"] = html2bbcode($clear_text) . '[spoiler]' . $item["body"] . '[/spoiler]';
665 if (($self != '') && empty($item['protocol'])) {
666 self::fetchSelf($self, $item);
669 if (!empty($item["conversation-href"])) {
670 self::fetchConversation($item['conversation-href'], $item['conversation-uri']);
673 if (isset($item["parent-uri"]) && ($related != '')) {
674 if (!dba::exists('item', ['uid' => $importer["uid"], 'uri' => $item['parent-uri']])) {
675 self::fetchRelated($related, $item["parent-uri"], $importer);
677 logger('Reply with URI '.$item["uri"].' already existed for user '.$importer["uid"].'.', LOGGER_DEBUG);
680 $item["type"] = 'remote-comment';
681 $item["gravity"] = GRAVITY_COMMENT;
683 $item["parent-uri"] = $item["uri"];
686 if (($item['author-link'] != '') && !empty($item['protocol'])) {
687 $item = Conversation::insert($item);
690 self::$itemlist[] = $item;
694 * @brief Fetch the conversation for posts
696 * @param string $conversation The link to the conversation
697 * @param string $conversation_uri The conversation in "uri" format
700 private static function fetchConversation($conversation, $conversation_uri)
702 // Ensure that we only store a conversation once in a process
703 if (isset(self::$conv_list[$conversation])) {
707 self::$conv_list[$conversation] = true;
709 $conversation_data = Network::curl($conversation, false, $redirects, ['accept_content' => 'application/atom+xml, text/html']);
711 if (!$conversation_data['success']) {
717 if (stristr($conversation_data['header'], 'Content-Type: application/atom+xml')) {
718 $xml = $conversation_data['body'];
722 $doc = new DOMDocument();
723 if (!@$doc->loadHTML($conversation_data['body'])) {
726 $xpath = new DOMXPath($doc);
728 $links = $xpath->query('//link');
731 foreach ($links as $link) {
732 $attribute = self::readAttributes($link);
733 if (($attribute['rel'] == 'alternate') && ($attribute['type'] == 'application/atom+xml')) {
734 $file = $attribute['href'];
738 $conversation_atom = Network::curl($attribute['href']);
740 if ($conversation_atom['success']) {
741 $xml = $conversation_atom['body'];
751 self::storeConversation($xml, $conversation, $conversation_uri);
755 * @brief Store a feed in several conversation entries
757 * @param string $xml The feed
758 * @param string $conversation conversation
759 * @param string $conversation_uri conversation uri
762 private static function storeConversation($xml, $conversation = '', $conversation_uri = '')
764 $doc = new DOMDocument();
765 @$doc->loadXML($xml);
767 $xpath = new DOMXPath($doc);
768 $xpath->registerNamespace('atom', NAMESPACE_ATOM1);
769 $xpath->registerNamespace('thr', NAMESPACE_THREAD);
770 $xpath->registerNamespace('ostatus', NAMESPACE_OSTATUS);
772 $entries = $xpath->query('/atom:feed/atom:entry');
774 // Now store the entries
775 foreach ($entries as $entry) {
776 $doc2 = new DOMDocument();
777 $doc2->preserveWhiteSpace = false;
778 $doc2->formatOutput = true;
782 $conv_data['protocol'] = PROTOCOL_SPLITTED_CONV;
783 $conv_data['network'] = NETWORK_OSTATUS;
784 $conv_data['uri'] = $xpath->query('atom:id/text()', $entry)->item(0)->nodeValue;
786 $inreplyto = $xpath->query('thr:in-reply-to', $entry);
787 if (is_object($inreplyto->item(0))) {
788 foreach ($inreplyto->item(0)->attributes as $attributes) {
789 if ($attributes->name == "ref") {
790 $conv_data['reply-to-uri'] = $attributes->textContent;
795 $conv = $xpath->query('ostatus:conversation/text()', $entry)->item(0)->nodeValue;
796 $conv_data['conversation-uri'] = $conv;
798 $conv = $xpath->query('ostatus:conversation', $entry);
799 if (is_object($conv->item(0))) {
800 foreach ($conv->item(0)->attributes as $attributes) {
801 if ($attributes->name == "ref") {
802 $conv_data['conversation-uri'] = $attributes->textContent;
804 if ($attributes->name == "href") {
805 $conv_data['conversation-href'] = $attributes->textContent;
810 if ($conversation != '') {
811 $conv_data['conversation-uri'] = $conversation;
814 if ($conversation_uri != '') {
815 $conv_data['conversation-uri'] = $conversation_uri;
818 $entry = $doc2->importNode($entry, true);
820 $doc2->appendChild($entry);
822 $conv_data['source'] = $doc2->saveXML();
824 $condition = ['item-uri' => $conv_data['uri'],'protocol' => PROTOCOL_OSTATUS_FEED];
825 if (dba::exists('conversation', $condition)) {
826 logger('Delete deprecated entry for URI '.$conv_data['uri'], LOGGER_DEBUG);
827 dba::delete('conversation', ['item-uri' => $conv_data['uri']]);
830 logger('Store conversation data for uri '.$conv_data['uri'], LOGGER_DEBUG);
831 Conversation::insert($conv_data);
836 * @brief Fetch the own post so that it can be stored later
838 * We want to store the original data for later processing.
839 * This function is meant for cases where we process a feed with multiple entries.
840 * In that case we need to fetch the single posts here.
842 * @param string $self The link to the self item
843 * @param array $item The item array
846 private static function fetchSelf($self, &$item)
848 $condition = ['`item-uri` = ? AND `protocol` IN (?, ?)', $self, PROTOCOL_DFRN, PROTOCOL_OSTATUS_SALMON];
849 if (dba::exists('conversation', $condition)) {
850 logger('Conversation '.$item['uri'].' is already stored.', LOGGER_DEBUG);
854 $self_data = Network::curl($self);
856 if (!$self_data['success']) {
860 // We reformat the XML to make it better readable
861 $doc = new DOMDocument();
862 $doc->loadXML($self_data['body']);
863 $doc->preserveWhiteSpace = false;
864 $doc->formatOutput = true;
865 $xml = $doc->saveXML();
867 $item["protocol"] = PROTOCOL_OSTATUS_SALMON;
868 $item["source"] = $xml;
870 logger('Conversation '.$item['uri'].' is now fetched.', LOGGER_DEBUG);
874 * @brief Fetch related posts and processes them
876 * @param string $related The link to the related item
877 * @param string $related_uri The related item in "uri" format
878 * @param array $importer user record of the importing user
881 private static function fetchRelated($related, $related_uri, $importer)
883 $condition = ['`item-uri` = ? AND `protocol` IN (?, ?)', $related_uri, PROTOCOL_DFRN, PROTOCOL_OSTATUS_SALMON];
884 $conversation = dba::selectFirst('conversation', ['source', 'protocol'], $condition);
885 if (DBM::is_result($conversation)) {
887 $xml = $conversation['source'];
888 if (self::process($xml, $importer, $contact, $hub, $stored, false)) {
889 logger('Got valid cached XML for URI '.$related_uri, LOGGER_DEBUG);
892 if ($conversation['protocol'] == PROTOCOL_OSTATUS_SALMON) {
893 logger('Delete invalid cached XML for URI '.$related_uri, LOGGER_DEBUG);
894 dba::delete('conversation', ['item-uri' => $related_uri]);
899 $related_data = Network::curl($related, false, $redirects, ['accept_content' => 'application/atom+xml, text/html']);
901 if (!$related_data['success']) {
907 if (stristr($related_data['header'], 'Content-Type: application/atom+xml')) {
908 logger('Directly fetched XML for URI '.$related_uri, LOGGER_DEBUG);
909 $xml = $related_data['body'];
913 $doc = new DOMDocument();
914 if (!@$doc->loadHTML($related_data['body'])) {
917 $xpath = new DOMXPath($doc);
921 $links = $xpath->query('//link');
923 foreach ($links as $link) {
924 $attribute = self::readAttributes($link);
925 if (($attribute['rel'] == 'alternate') && ($attribute['type'] == 'application/atom+xml')) {
926 $atom_file = $attribute['href'];
929 if ($atom_file != '') {
930 $related_atom = Network::curl($atom_file);
932 if ($related_atom['success']) {
933 logger('Fetched XML for URI '.$related_uri, LOGGER_DEBUG);
934 $xml = $related_atom['body'];
940 // Workaround for older GNU Social servers
941 if (($xml == '') && strstr($related, '/notice/')) {
942 $related_atom = Network::curl(str_replace('/notice/', '/api/statuses/show/', $related).'.atom');
944 if ($related_atom['success']) {
945 logger('GNU Social workaround to fetch XML for URI '.$related_uri, LOGGER_DEBUG);
946 $xml = $related_atom['body'];
950 // Even more worse workaround for GNU Social ;-)
952 $related_guess = OStatus::convertHref($related_uri);
953 $related_atom = Network::curl(str_replace('/notice/', '/api/statuses/show/', $related_guess).'.atom');
955 if ($related_atom['success']) {
956 logger('GNU Social workaround 2 to fetch XML for URI '.$related_uri, LOGGER_DEBUG);
957 $xml = $related_atom['body'];
961 // Finally we take the data that we fetched from "ostatus:conversation"
963 $condition = ['item-uri' => $related_uri, 'protocol' => PROTOCOL_SPLITTED_CONV];
964 $conversation = dba::selectFirst('conversation', ['source'], $condition);
965 if (DBM::is_result($conversation)) {
967 logger('Got cached XML from conversation for URI '.$related_uri, LOGGER_DEBUG);
968 $xml = $conversation['source'];
973 self::process($xml, $importer, $contact, $hub, $stored, false);
975 logger("XML couldn't be fetched for URI: ".$related_uri." - href: ".$related, LOGGER_DEBUG);
981 * @brief Processes the XML for a repeated post
983 * @param object $xpath The xpath object
984 * @param object $entry The xml entry that is processed
985 * @param array $item The item array
986 * @param array $importer user record of the importing user
988 * @return array with data from links
990 private static function processRepeatedItem($xpath, $entry, &$item, $importer)
992 $activityobjects = $xpath->query('activity:object', $entry)->item(0);
994 if (!is_object($activityobjects)) {
1000 $orig_uri = $xpath->query('atom:id/text()', $activityobjects)->item(0)->nodeValue;
1002 $links = $xpath->query("atom:link", $activityobjects);
1004 $link_data = self::processLinks($links, $item);
1007 $orig_body = $xpath->query('atom:content/text()', $activityobjects)->item(0)->nodeValue;
1008 $orig_created = $xpath->query('atom:published/text()', $activityobjects)->item(0)->nodeValue;
1009 $orig_edited = $xpath->query('atom:updated/text()', $activityobjects)->item(0)->nodeValue;
1011 $orig_author = self::fetchAuthor($xpath, $activityobjects, $importer, $dummy, false);
1013 $item["author-name"] = $orig_author["author-name"];
1014 $item["author-link"] = $orig_author["author-link"];
1015 $item["author-avatar"] = $orig_author["author-avatar"];
1017 $item["body"] = html2bbcode($orig_body);
1018 $item["created"] = $orig_created;
1019 $item["edited"] = $orig_edited;
1021 $item["uri"] = $orig_uri;
1023 $item["verb"] = $xpath->query('activity:verb/text()', $activityobjects)->item(0)->nodeValue;
1025 $item["object-type"] = $xpath->query('activity:object-type/text()', $activityobjects)->item(0)->nodeValue;
1027 $inreplyto = $xpath->query('thr:in-reply-to', $activityobjects);
1028 if (is_object($inreplyto->item(0))) {
1029 foreach ($inreplyto->item(0)->attributes as $attributes) {
1030 if ($attributes->name == "ref") {
1031 $item["parent-uri"] = $attributes->textContent;
1040 * @brief Processes links in the XML
1042 * @param object $links The xml data that contain links
1043 * @param array $item The item array
1045 * @return array with data from the links
1047 private static function processLinks($links, &$item)
1049 $link_data = ['add_body' => '', 'self' => ''];
1051 foreach ($links as $link) {
1052 $attribute = self::readAttributes($link);
1054 if (($attribute['rel'] != "") && ($attribute['href'] != "")) {
1055 switch ($attribute['rel']) {
1057 $item["plink"] = $attribute['href'];
1058 if (($item["object-type"] == ACTIVITY_OBJ_QUESTION)
1059 || ($item["object-type"] == ACTIVITY_OBJ_EVENT)
1061 $item["body"] .= add_page_info($attribute['href']);
1064 case "ostatus:conversation":
1065 $link_data['conversation'] = $attribute['href'];
1066 $item['conversation-href'] = $link_data['conversation'];
1067 if (!isset($item['conversation-uri'])) {
1068 $item['conversation-uri'] = $item['conversation-href'];
1072 $filetype = strtolower(substr($attribute['type'], 0, strpos($attribute['type'], '/')));
1073 if ($filetype == 'image') {
1074 $link_data['add_body'] .= "\n[img]".$attribute['href'].'[/img]';
1076 if (strlen($item["attach"])) {
1077 $item["attach"] .= ',';
1079 if (!isset($attribute['length'])) {
1080 $attribute['length'] = "0";
1082 $item["attach"] .= '[attach]href="'.$attribute['href'].'" length="'.$attribute['length'].'" type="'.$attribute['type'].'" title="'.$attribute['title'].'"[/attach]';
1086 if ($item["object-type"] != ACTIVITY_OBJ_BOOKMARK) {
1087 if (!isset($item["parent-uri"])) {
1088 $item["parent-uri"] = $attribute['href'];
1090 $link_data['related'] = $attribute['href'];
1092 $item["body"] .= add_page_info($attribute['href']);
1096 if ($item["plink"] == '') {
1097 $item["plink"] = $attribute['href'];
1099 $link_data['self'] = $attribute['href'];
1108 * @brief Create an url out of an uri
1110 * @param string $href URI in the format "parameter1:parameter1:..."
1112 * @return string URL in the format http(s)://....
1114 public static function convertHref($href)
1116 $elements = explode(":", $href);
1118 if ((count($elements) <= 2) || ($elements[0] != "tag")) {
1122 $server = explode(",", $elements[1]);
1123 $conversation = explode("=", $elements[2]);
1125 if ((count($elements) == 4) && ($elements[2] == "post")) {
1126 return "http://".$server[0]."/notice/".$elements[3];
1129 if ((count($conversation) != 2) || ($conversation[1] =="")) {
1132 if ($elements[3] == "objectType=thread") {
1133 return "http://".$server[0]."/conversation/".$conversation[1];
1135 return "http://".$server[0]."/notice/".$conversation[1];
1141 * @brief Checks if the current post is a reshare
1143 * @param array $item The item array of thw post
1145 * @return string The guid if the post is a reshare
1147 private static function getResharedGuid($item)
1149 $body = trim($item["body"]);
1151 // Skip if it isn't a pure repeated messages
1152 // Does it start with a share?
1153 if (strpos($body, "[share") > 0) {
1157 // Does it end with a share?
1158 if (strlen($body) > (strrpos($body, "[/share]") + 8)) {
1162 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "$1", $body);
1163 // Skip if there is no shared message in there
1164 if ($body == $attributes) {
1169 preg_match("/guid='(.*?)'/ism", $attributes, $matches);
1170 if ($matches[1] != "") {
1171 $guid = $matches[1];
1174 preg_match('/guid="(.*?)"/ism', $attributes, $matches);
1175 if ($matches[1] != "") {
1176 $guid = $matches[1];
1183 * @brief Cleans the body of a post if it contains picture links
1185 * @param string $body The body
1187 * @return string The cleaned body
1189 private static function formatPicturePost($body)
1191 $siteinfo = BBCode::getAttachedData($body);
1193 if (($siteinfo["type"] == "photo")) {
1194 if (isset($siteinfo["preview"])) {
1195 $preview = $siteinfo["preview"];
1197 $preview = $siteinfo["image"];
1200 // Is it a remote picture? Then make a smaller preview here
1201 $preview = proxy_url($preview, false, PROXY_SIZE_SMALL);
1203 // Is it a local picture? Then make it smaller here
1204 $preview = str_replace(["-0.jpg", "-0.png"], ["-2.jpg", "-2.png"], $preview);
1205 $preview = str_replace(["-1.jpg", "-1.png"], ["-2.jpg", "-2.png"], $preview);
1207 if (isset($siteinfo["url"])) {
1208 $url = $siteinfo["url"];
1210 $url = $siteinfo["image"];
1213 $body = trim($siteinfo["text"])." [url]".$url."[/url]\n[img]".$preview."[/img]";
1220 * @brief Adds the header elements to the XML document
1222 * @param object $doc XML document
1223 * @param array $owner Contact data of the poster
1224 * @param string $filter The related feed filter (activity, posts or comments)
1226 * @return object header root element
1228 private static function addHeader($doc, $owner, $filter)
1232 $root = $doc->createElementNS(NAMESPACE_ATOM1, 'feed');
1233 $doc->appendChild($root);
1235 $root->setAttribute("xmlns:thr", NAMESPACE_THREAD);
1236 $root->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
1237 $root->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
1238 $root->setAttribute("xmlns:media", NAMESPACE_MEDIA);
1239 $root->setAttribute("xmlns:poco", NAMESPACE_POCO);
1240 $root->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
1241 $root->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
1242 $root->setAttribute("xmlns:mastodon", NAMESPACE_MASTODON);
1246 case 'activity': $title = L10n::t('%s\'s timeline', $owner['name']); break;
1247 case 'posts' : $title = L10n::t('%s\'s posts' , $owner['name']); break;
1248 case 'comments': $title = L10n::t('%s\'s comments', $owner['name']); break;
1251 $attributes = ["uri" => "https://friendi.ca", "version" => FRIENDICA_VERSION . "-" . DB_UPDATE_VERSION];
1252 XML::addElement($doc, $root, "generator", FRIENDICA_PLATFORM, $attributes);
1253 XML::addElement($doc, $root, "id", System::baseUrl() . "/profile/" . $owner["nick"]);
1254 XML::addElement($doc, $root, "title", $title);
1255 XML::addElement($doc, $root, "subtitle", sprintf("Updates from %s on %s", $owner["name"], $a->config["sitename"]));
1256 XML::addElement($doc, $root, "logo", $owner["photo"]);
1257 XML::addElement($doc, $root, "updated", DateTimeFormat::utcNow(DateTimeFormat::ATOM));
1259 $author = self::addAuthor($doc, $owner);
1260 $root->appendChild($author);
1262 $attributes = ["href" => $owner["url"], "rel" => "alternate", "type" => "text/html"];
1263 XML::addElement($doc, $root, "link", "", $attributes);
1265 /// @TODO We have to find out what this is
1266 /// $attributes = array("href" => System::baseUrl()."/sup",
1267 /// "rel" => "http://api.friendfeed.com/2008/03#sup",
1268 /// "type" => "application/json");
1269 /// XML::addElement($doc, $root, "link", "", $attributes);
1271 self::hublinks($doc, $root, $owner["nick"]);
1273 $attributes = ["href" => System::baseUrl() . "/salmon/" . $owner["nick"], "rel" => "salmon"];
1274 XML::addElement($doc, $root, "link", "", $attributes);
1276 $attributes = ["href" => System::baseUrl() . "/salmon/" . $owner["nick"], "rel" => "http://salmon-protocol.org/ns/salmon-replies"];
1277 XML::addElement($doc, $root, "link", "", $attributes);
1279 $attributes = ["href" => System::baseUrl() . "/salmon/" . $owner["nick"], "rel" => "http://salmon-protocol.org/ns/salmon-mention"];
1280 XML::addElement($doc, $root, "link", "", $attributes);
1282 $attributes = ["href" => System::baseUrl() . "/api/statuses/user_timeline/" . $owner["nick"] . ".atom",
1283 "rel" => "self", "type" => "application/atom+xml"];
1284 XML::addElement($doc, $root, "link", "", $attributes);
1290 * @brief Add the link to the push hubs to the XML document
1292 * @param object $doc XML document
1293 * @param object $root XML root element where the hub links are added
1294 * @param object $nick nick
1297 public static function hublinks($doc, $root, $nick)
1299 $h = System::baseUrl() . '/pubsubhubbub/'.$nick;
1300 XML::addElement($doc, $root, "link", "", ["href" => $h, "rel" => "hub"]);
1304 * @brief Adds attachement data 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 array $item Data of the item that is to be posted
1311 private static function getAttachment($doc, $root, $item)
1314 $siteinfo = BBCode::getAttachedData($item["body"]);
1316 switch ($siteinfo["type"]) {
1318 $imgdata = Image::getInfoFromURL($siteinfo["image"]);
1319 $attributes = ["rel" => "enclosure",
1320 "href" => $siteinfo["image"],
1321 "type" => $imgdata["mime"],
1322 "length" => intval($imgdata["size"])];
1323 XML::addElement($doc, $root, "link", "", $attributes);
1326 $attributes = ["rel" => "enclosure",
1327 "href" => $siteinfo["url"],
1328 "type" => "text/html; charset=UTF-8",
1330 "title" => $siteinfo["title"]];
1331 XML::addElement($doc, $root, "link", "", $attributes);
1337 if (!Config::get('system', 'ostatus_not_attach_preview') && ($siteinfo["type"] != "photo") && isset($siteinfo["image"])) {
1338 $imgdata = Image::getInfoFromURL($siteinfo["image"]);
1339 $attributes = ["rel" => "enclosure",
1340 "href" => $siteinfo["image"],
1341 "type" => $imgdata["mime"],
1342 "length" => intval($imgdata["size"])];
1344 XML::addElement($doc, $root, "link", "", $attributes);
1347 $arr = explode('[/attach],', $item['attach']);
1349 foreach ($arr as $r) {
1351 $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"|', $r, $matches);
1353 $attributes = ["rel" => "enclosure",
1354 "href" => $matches[1],
1355 "type" => $matches[3]];
1357 if (intval($matches[2])) {
1358 $attributes["length"] = intval($matches[2]);
1360 if (trim($matches[4]) != "") {
1361 $attributes["title"] = trim($matches[4]);
1363 XML::addElement($doc, $root, "link", "", $attributes);
1370 * @brief Adds the author element to the XML document
1372 * @param object $doc XML document
1373 * @param array $owner Contact data of the poster
1375 * @return object author element
1377 private static function addAuthor($doc, $owner)
1379 $profile = dba::selectFirst('profile', ['homepage', 'publish'], ['uid' => $owner['uid'], 'is-default' => true]);
1380 $author = $doc->createElement("author");
1381 XML::addElement($doc, $author, "id", $owner["url"]);
1382 XML::addElement($doc, $author, "activity:object-type", ACTIVITY_OBJ_PERSON);
1383 XML::addElement($doc, $author, "uri", $owner["url"]);
1384 XML::addElement($doc, $author, "name", $owner["nick"]);
1385 XML::addElement($doc, $author, "email", $owner["addr"]);
1386 XML::addElement($doc, $author, "summary", BBCode::convert($owner["about"], false, 7));
1388 $attributes = ["rel" => "alternate", "type" => "text/html", "href" => $owner["url"]];
1389 XML::addElement($doc, $author, "link", "", $attributes);
1393 "type" => "image/jpeg", // To-Do?
1394 "media:width" => 175,
1395 "media:height" => 175,
1396 "href" => $owner["photo"]];
1397 XML::addElement($doc, $author, "link", "", $attributes);
1399 if (isset($owner["thumb"])) {
1402 "type" => "image/jpeg", // To-Do?
1403 "media:width" => 80,
1404 "media:height" => 80,
1405 "href" => $owner["thumb"]];
1406 XML::addElement($doc, $author, "link", "", $attributes);
1409 XML::addElement($doc, $author, "poco:preferredUsername", $owner["nick"]);
1410 XML::addElement($doc, $author, "poco:displayName", $owner["name"]);
1411 XML::addElement($doc, $author, "poco:note", BBCode::convert($owner["about"], false, 7));
1413 if (trim($owner["location"]) != "") {
1414 $element = $doc->createElement("poco:address");
1415 XML::addElement($doc, $element, "poco:formatted", $owner["location"]);
1416 $author->appendChild($element);
1419 if (DBM::is_result($profile)) {
1420 if (trim($profile["homepage"]) != "") {
1421 $urls = $doc->createElement("poco:urls");
1422 XML::addElement($doc, $urls, "poco:type", "homepage");
1423 XML::addElement($doc, $urls, "poco:value", $profile["homepage"]);
1424 XML::addElement($doc, $urls, "poco:primary", "true");
1425 $author->appendChild($urls);
1428 XML::addElement($doc, $author, "followers", "", ["url" => System::baseUrl()."/viewcontacts/".$owner["nick"]]);
1429 XML::addElement($doc, $author, "statusnet:profile_info", "", ["local_id" => $owner["uid"]]);
1432 if ($profile["publish"]) {
1433 XML::addElement($doc, $author, "mastodon:scope", "public");
1439 * @TODO Picture attachments should look like this:
1440 * <a href="https://status.pirati.ca/attachment/572819" title="https://status.pirati.ca/file/heluecht-20151202T222602-rd3u49p.gif"
1441 * class="attachment thumbnail" id="attachment-572819" rel="nofollow external">https://status.pirati.ca/attachment/572819</a>
1445 * @brief Returns the given activity if present - otherwise returns the "post" activity
1447 * @param array $item Data of the item that is to be posted
1449 * @return string activity
1451 private static function constructVerb($item)
1453 if ($item['verb']) {
1454 return $item['verb'];
1457 return ACTIVITY_POST;
1461 * @brief Returns the given object type if present - otherwise returns the "note" object type
1463 * @param array $item Data of the item that is to be posted
1465 * @return string Object type
1467 private static function constructObjecttype($item)
1469 if (in_array($item['object-type'], [ACTIVITY_OBJ_NOTE, ACTIVITY_OBJ_COMMENT]))
1470 return $item['object-type'];
1471 return ACTIVITY_OBJ_NOTE;
1475 * @brief Adds an entry element to the XML document
1477 * @param object $doc XML document
1478 * @param array $item Data of the item that is to be posted
1479 * @param array $owner Contact data of the poster
1480 * @param bool $toplevel optional default false
1482 * @return object Entry element
1484 private static function entry($doc, $item, $owner, $toplevel = false)
1488 $repeated_guid = self::getResharedGuid($item);
1489 if ($repeated_guid != "") {
1490 $xml = self::reshareEntry($doc, $item, $owner, $repeated_guid, $toplevel);
1497 if ($item["verb"] == ACTIVITY_LIKE) {
1498 return self::likeEntry($doc, $item, $owner, $toplevel);
1499 } elseif (in_array($item["verb"], [ACTIVITY_FOLLOW, NAMESPACE_OSTATUS."/unfollow"])) {
1500 return self::followEntry($doc, $item, $owner, $toplevel);
1502 return self::noteEntry($doc, $item, $owner, $toplevel);
1507 * @brief Adds a source entry to the XML document
1509 * @param object $doc XML document
1510 * @param array $contact Array of the contact that is added
1512 * @return object Source element
1514 private static function sourceEntry($doc, $contact)
1516 $source = $doc->createElement("source");
1517 XML::addElement($doc, $source, "id", $contact["poll"]);
1518 XML::addElement($doc, $source, "title", $contact["name"]);
1519 XML::addElement($doc, $source, "link", "", ["rel" => "alternate", "type" => "text/html", "href" => $contact["alias"]]);
1520 XML::addElement($doc, $source, "link", "", ["rel" => "self", "type" => "application/atom+xml", "href" => $contact["poll"]]);
1521 XML::addElement($doc, $source, "icon", $contact["photo"]);
1522 XML::addElement($doc, $source, "updated", DateTimeFormat::utc($contact["success_update"]."+00:00", DateTimeFormat::ATOM));
1528 * @brief Fetches contact data from the contact or the gcontact table
1530 * @param string $url URL of the contact
1531 * @param array $owner Contact data of the poster
1533 * @return array Contact array
1535 private static function contactEntry($url, $owner)
1538 "SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` IN (0, %d) ORDER BY `uid` DESC LIMIT 1",
1539 dbesc(normalise_link($url)),
1540 intval($owner["uid"])
1542 if (DBM::is_result($r)) {
1544 $contact["uid"] = -1;
1547 if (!DBM::is_result($r)) {
1549 "SELECT * FROM `gcontact` WHERE `nurl` = '%s' LIMIT 1",
1550 dbesc(normalise_link($url))
1552 if (DBM::is_result($r)) {
1554 $contact["uid"] = -1;
1555 $contact["success_update"] = $contact["updated"];
1559 if (!DBM::is_result($r)) {
1563 if (!isset($contact["poll"])) {
1564 $data = Probe::uri($url);
1565 $contact["poll"] = $data["poll"];
1567 if (!$contact["alias"]) {
1568 $contact["alias"] = $data["alias"];
1572 if (!isset($contact["alias"])) {
1573 $contact["alias"] = $contact["url"];
1580 * @brief Adds an entry element with reshared content
1582 * @param object $doc XML document
1583 * @param array $item Data of the item that is to be posted
1584 * @param array $owner Contact data of the poster
1585 * @param string $repeated_guid guid
1586 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1588 * @return object Entry element
1590 private static function reshareEntry($doc, $item, $owner, $repeated_guid, $toplevel)
1592 if (($item["id"] != $item["parent"]) && (normalise_link($item["author-link"]) != normalise_link($owner["url"]))) {
1593 logger("OStatus entry is from author ".$owner["url"]." - not from ".$item["author-link"].". Quitting.", LOGGER_DEBUG);
1596 $title = self::entryHeader($doc, $entry, $owner, $toplevel);
1599 "SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' AND NOT `private` AND `network` IN ('%s', '%s', '%s') LIMIT 1",
1600 intval($owner["uid"]),
1601 dbesc($repeated_guid),
1602 dbesc(NETWORK_DFRN),
1603 dbesc(NETWORK_DIASPORA),
1604 dbesc(NETWORK_OSTATUS)
1606 if (DBM::is_result($r)) {
1607 $repeated_item = $r[0];
1611 $contact = self::contactEntry($repeated_item['author-link'], $owner);
1613 $parent_item = (($item['thr-parent']) ? $item['thr-parent'] : $item['parent-uri']);
1615 $title = $owner["nick"]." repeated a notice by ".$contact["nick"];
1617 self::entryContent($doc, $entry, $item, $owner, $title, ACTIVITY_SHARE, false);
1619 $as_object = $doc->createElement("activity:object");
1621 XML::addElement($doc, $as_object, "activity:object-type", NAMESPACE_ACTIVITY_SCHEMA."activity");
1623 self::entryContent($doc, $as_object, $repeated_item, $owner, "", "", false);
1625 $author = self::addAuthor($doc, $contact);
1626 $as_object->appendChild($author);
1628 $as_object2 = $doc->createElement("activity:object");
1630 XML::addElement($doc, $as_object2, "activity:object-type", self::constructObjecttype($repeated_item));
1632 $title = sprintf("New comment by %s", $contact["nick"]);
1634 self::entryContent($doc, $as_object2, $repeated_item, $owner, $title);
1636 $as_object->appendChild($as_object2);
1638 self::entryFooter($doc, $as_object, $item, $owner, false);
1640 $source = self::sourceEntry($doc, $contact);
1642 $as_object->appendChild($source);
1644 $entry->appendChild($as_object);
1646 self::entryFooter($doc, $entry, $item, $owner);
1652 * @brief Adds an entry element with a "like"
1654 * @param object $doc XML document
1655 * @param array $item Data of the item that is to be posted
1656 * @param array $owner Contact data of the poster
1657 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1659 * @return object Entry element with "like"
1661 private static function likeEntry($doc, $item, $owner, $toplevel)
1663 if (($item["id"] != $item["parent"]) && (normalise_link($item["author-link"]) != normalise_link($owner["url"]))) {
1664 logger("OStatus entry is from author ".$owner["url"]." - not from ".$item["author-link"].". Quitting.", LOGGER_DEBUG);
1667 $title = self::entryHeader($doc, $entry, $owner, $toplevel);
1669 $verb = NAMESPACE_ACTIVITY_SCHEMA."favorite";
1670 self::entryContent($doc, $entry, $item, $owner, "Favorite", $verb, false);
1672 $as_object = $doc->createElement("activity:object");
1675 "SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d",
1676 dbesc($item["thr-parent"]),
1677 intval($item["uid"])
1679 $parent_item = (($item['thr-parent']) ? $item['thr-parent'] : $item['parent-uri']);
1681 XML::addElement($doc, $as_object, "activity:object-type", self::constructObjecttype($parent[0]));
1683 self::entryContent($doc, $as_object, $parent[0], $owner, "New entry");
1685 $entry->appendChild($as_object);
1687 self::entryFooter($doc, $entry, $item, $owner);
1693 * @brief Adds the person object element to the XML document
1695 * @param object $doc XML document
1696 * @param array $owner Contact data of the poster
1697 * @param array $contact Contact data of the target
1699 * @return object author element
1701 private static function addPersonObject($doc, $owner, $contact)
1703 $object = $doc->createElement("activity:object");
1704 XML::addElement($doc, $object, "activity:object-type", ACTIVITY_OBJ_PERSON);
1706 if ($contact['network'] == NETWORK_PHANTOM) {
1707 XML::addElement($doc, $object, "id", $contact['url']);
1711 XML::addElement($doc, $object, "id", $contact["alias"]);
1712 XML::addElement($doc, $object, "title", $contact["nick"]);
1714 $attributes = ["rel" => "alternate", "type" => "text/html", "href" => $contact["url"]];
1715 XML::addElement($doc, $object, "link", "", $attributes);
1719 "type" => "image/jpeg", // To-Do?
1720 "media:width" => 175,
1721 "media:height" => 175,
1722 "href" => $contact["photo"]];
1723 XML::addElement($doc, $object, "link", "", $attributes);
1725 XML::addElement($doc, $object, "poco:preferredUsername", $contact["nick"]);
1726 XML::addElement($doc, $object, "poco:displayName", $contact["name"]);
1728 if (trim($contact["location"]) != "") {
1729 $element = $doc->createElement("poco:address");
1730 XML::addElement($doc, $element, "poco:formatted", $contact["location"]);
1731 $object->appendChild($element);
1738 * @brief Adds a follow/unfollow entry element
1740 * @param object $doc XML document
1741 * @param array $item Data of the follow/unfollow message
1742 * @param array $owner Contact data of the poster
1743 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1745 * @return object Entry element
1747 private static function followEntry($doc, $item, $owner, $toplevel)
1749 $item["id"] = $item["parent"] = 0;
1750 $item["created"] = $item["edited"] = date("c");
1751 $item["private"] = true;
1753 $contact = Probe::uri($item['follow']);
1755 if ($contact['alias'] == '') {
1756 $contact['alias'] = $contact["url"];
1758 $item['follow'] = $contact['alias'];
1762 "SELECT `id` FROM `contact` WHERE `uid` = %d AND `nurl` = '%s'",
1763 intval($owner['uid']),
1764 dbesc(normalise_link($contact["url"]))
1767 if (DBM::is_result($r)) {
1768 $connect_id = $r[0]['id'];
1773 if ($item['verb'] == ACTIVITY_FOLLOW) {
1774 $message = L10n::t('%s is now following %s.');
1775 $title = L10n::t('following');
1776 $action = "subscription";
1778 $message = L10n::t('%s stopped following %s.');
1779 $title = L10n::t('stopped following');
1780 $action = "unfollow";
1783 $item["uri"] = $item['parent-uri'] = $item['thr-parent']
1784 = 'tag:'.get_app()->get_hostname().
1785 ','.date('Y-m-d').':'.$action.':'.$owner['uid'].
1786 ':person:'.$connect_id.':'.$item['created'];
1788 $item["body"] = sprintf($message, $owner["nick"], $contact["nick"]);
1790 self::entryHeader($doc, $entry, $owner, $toplevel);
1792 self::entryContent($doc, $entry, $item, $owner, $title);
1794 $object = self::addPersonObject($doc, $owner, $contact);
1795 $entry->appendChild($object);
1797 self::entryFooter($doc, $entry, $item, $owner);
1803 * @brief Adds a regular entry element
1805 * @param object $doc XML document
1806 * @param array $item Data of the item that is to be posted
1807 * @param array $owner Contact data of the poster
1808 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1810 * @return object Entry element
1812 private static function noteEntry($doc, $item, $owner, $toplevel)
1814 if (($item["id"] != $item["parent"]) && (normalise_link($item["author-link"]) != normalise_link($owner["url"]))) {
1815 logger("OStatus entry is from author ".$owner["url"]." - not from ".$item["author-link"].". Quitting.", LOGGER_DEBUG);
1818 $title = self::entryHeader($doc, $entry, $owner, $toplevel);
1820 XML::addElement($doc, $entry, "activity:object-type", ACTIVITY_OBJ_NOTE);
1822 self::entryContent($doc, $entry, $item, $owner, $title);
1824 self::entryFooter($doc, $entry, $item, $owner);
1830 * @brief Adds a header element to the XML document
1832 * @param object $doc XML document
1833 * @param object $entry The entry element where the elements are added
1834 * @param array $owner Contact data of the poster
1835 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1837 * @return string The title for the element
1839 private static function entryHeader($doc, &$entry, $owner, $toplevel)
1841 /// @todo Check if this title stuff is really needed (I guess not)
1843 $entry = $doc->createElement("entry");
1844 $title = sprintf("New note by %s", $owner["nick"]);
1846 $entry = $doc->createElementNS(NAMESPACE_ATOM1, "entry");
1848 $entry->setAttribute("xmlns:thr", NAMESPACE_THREAD);
1849 $entry->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
1850 $entry->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
1851 $entry->setAttribute("xmlns:media", NAMESPACE_MEDIA);
1852 $entry->setAttribute("xmlns:poco", NAMESPACE_POCO);
1853 $entry->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
1854 $entry->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
1855 $entry->setAttribute("xmlns:mastodon", NAMESPACE_MASTODON);
1857 $author = self::addAuthor($doc, $owner);
1858 $entry->appendChild($author);
1860 $title = sprintf("New comment by %s", $owner["nick"]);
1866 * @brief Adds elements to the XML document
1868 * @param object $doc XML document
1869 * @param object $entry Entry element where the content is added
1870 * @param array $item Data of the item that is to be posted
1871 * @param array $owner Contact data of the poster
1872 * @param string $title Title for the post
1873 * @param string $verb The activity verb
1874 * @param bool $complete Add the "status_net" element?
1877 private static function entryContent($doc, $entry, $item, $owner, $title, $verb = "", $complete = true)
1880 $verb = self::constructVerb($item);
1883 XML::addElement($doc, $entry, "id", $item["uri"]);
1884 XML::addElement($doc, $entry, "title", $title);
1886 $body = self::formatPicturePost($item['body']);
1888 if ($item['title'] != "") {
1889 $body = "[b]".$item['title']."[/b]\n\n".$body;
1892 $body = BBCode::convert($body, false, 7);
1894 XML::addElement($doc, $entry, "content", $body, ["type" => "html"]);
1896 XML::addElement($doc, $entry, "link", "", ["rel" => "alternate", "type" => "text/html",
1897 "href" => System::baseUrl()."/display/".$item["guid"]]
1900 if ($complete && ($item["id"] > 0)) {
1901 XML::addElement($doc, $entry, "status_net", "", ["notice_id" => $item["id"]]);
1904 XML::addElement($doc, $entry, "activity:verb", $verb);
1906 XML::addElement($doc, $entry, "published", DateTimeFormat::utc($item["created"]."+00:00", DateTimeFormat::ATOM));
1907 XML::addElement($doc, $entry, "updated", DateTimeFormat::utc($item["edited"]."+00:00", DateTimeFormat::ATOM));
1911 * @brief Adds the elements at the foot of an entry to the XML document
1913 * @param object $doc XML document
1914 * @param object $entry The entry element where the elements are added
1915 * @param array $item Data of the item that is to be posted
1916 * @param array $owner Contact data of the poster
1917 * @param bool $complete default true
1920 private static function entryFooter($doc, $entry, $item, $owner, $complete = true)
1924 if (($item['parent'] != $item['id']) || ($item['parent-uri'] !== $item['uri']) || (($item['thr-parent'] !== '') && ($item['thr-parent'] !== $item['uri']))) {
1925 $parent = q("SELECT `guid`, `author-link`, `owner-link` FROM `item` WHERE `id` = %d", intval($item["parent"]));
1926 $parent_item = (($item['thr-parent']) ? $item['thr-parent'] : $item['parent-uri']);
1929 "SELECT `guid`, `author-link`, `owner-link`, `plink` FROM `item` WHERE `uid` = %d AND `uri` = '%s'",
1930 intval($owner["uid"]),
1934 $mentioned[$thrparent[0]["author-link"]] = $thrparent[0]["author-link"];
1935 $mentioned[$thrparent[0]["owner-link"]] = $thrparent[0]["owner-link"];
1936 $parent_plink = $thrparent[0]["plink"];
1938 $mentioned[$parent[0]["author-link"]] = $parent[0]["author-link"];
1939 $mentioned[$parent[0]["owner-link"]] = $parent[0]["owner-link"];
1940 $parent_plink = System::baseUrl()."/display/".$parent[0]["guid"];
1944 "ref" => $parent_item,
1945 "href" => $parent_plink];
1946 XML::addElement($doc, $entry, "thr:in-reply-to", "", $attributes);
1950 "href" => $parent_plink];
1951 XML::addElement($doc, $entry, "link", "", $attributes);
1954 if (intval($item["parent"]) > 0) {
1955 $conversation_href = System::baseUrl()."/display/".$owner["nick"]."/".$item["parent"];
1956 $conversation_uri = $conversation_href;
1958 if (isset($parent_item)) {
1959 $r = dba::fetch_first("SELECT `conversation-uri`, `conversation-href` FROM `conversation` WHERE `item-uri` = ?", $parent_item);
1960 if (DBM::is_result($r)) {
1961 if ($r['conversation-uri'] != '') {
1962 $conversation_uri = $r['conversation-uri'];
1964 if ($r['conversation-href'] != '') {
1965 $conversation_href = $r['conversation-href'];
1970 XML::addElement($doc, $entry, "link", "", ["rel" => "ostatus:conversation", "href" => $conversation_href]);
1973 "href" => $conversation_href,
1974 "local_id" => $item["parent"],
1975 "ref" => $conversation_uri];
1977 XML::addElement($doc, $entry, "ostatus:conversation", $conversation_uri, $attributes);
1980 $tags = item::getFeedTags($item);
1983 foreach ($tags as $t) {
1985 $mentioned[$t[1]] = $t[1];
1990 // Make sure that mentions are accepted (GNU Social has problems with mixing HTTP and HTTPS)
1992 foreach ($mentioned as $mention) {
1993 $newmentions[str_replace("http://", "https://", $mention)] = str_replace("http://", "https://", $mention);
1994 $newmentions[str_replace("https://", "http://", $mention)] = str_replace("https://", "http://", $mention);
1996 $mentioned = $newmentions;
1998 foreach ($mentioned as $mention) {
2000 "SELECT `forum`, `prv` FROM `contact` WHERE `uid` = %d AND `nurl` = '%s'",
2001 intval($owner["uid"]),
2002 dbesc(normalise_link($mention))
2004 if ($r[0]["forum"] || $r[0]["prv"]) {
2005 XML::addElement($doc, $entry, "link", "",
2007 "rel" => "mentioned",
2008 "ostatus:object-type" => ACTIVITY_OBJ_GROUP,
2012 XML::addElement($doc, $entry, "link", "",
2014 "rel" => "mentioned",
2015 "ostatus:object-type" => ACTIVITY_OBJ_PERSON,
2021 if (!$item["private"]) {
2022 XML::addElement($doc, $entry, "link", "", ["rel" => "ostatus:attention",
2023 "href" => "http://activityschema.org/collection/public"]);
2024 XML::addElement($doc, $entry, "link", "", ["rel" => "mentioned",
2025 "ostatus:object-type" => "http://activitystrea.ms/schema/1.0/collection",
2026 "href" => "http://activityschema.org/collection/public"]);
2027 XML::addElement($doc, $entry, "mastodon:scope", "public");
2031 foreach ($tags as $t) {
2033 XML::addElement($doc, $entry, "category", "", ["term" => $t[2]]);
2038 self::getAttachment($doc, $entry, $item);
2040 if ($complete && ($item["id"] > 0)) {
2041 $app = $item["app"];
2046 $attributes = ["local_id" => $item["id"], "source" => $app];
2048 if (isset($parent["id"])) {
2049 $attributes["repeat_of"] = $parent["id"];
2052 if ($item["coord"] != "") {
2053 XML::addElement($doc, $entry, "georss:point", $item["coord"]);
2056 XML::addElement($doc, $entry, "statusnet:notice_info", "", $attributes);
2061 * Creates the XML feed for a given nickname
2063 * Supported filters:
2064 * - activity (default): all the public posts
2065 * - posts: all the public top-level posts
2066 * - comments: all the public replies
2068 * Updates the provided last_update parameter if the result comes from the
2069 * cache or it is empty
2071 * @brief Creates the XML feed for a given nickname
2073 * @param string $owner_nick Nickname of the feed owner
2074 * @param string $last_update Date of the last update
2075 * @param integer $max_items Number of maximum items to fetch
2076 * @param string $filter Feed items filter (activity, posts or comments)
2077 * @param boolean $nocache Wether to bypass caching
2079 * @return string XML feed
2081 public static function feed($owner_nick, &$last_update, $max_items = 300, $filter = 'activity', $nocache = false)
2083 $stamp = microtime(true);
2085 $cachekey = "ostatus:feed:" . $owner_nick . ":" . $filter . ":" . $last_update;
2087 $previous_created = $last_update;
2089 $result = Cache::get($cachekey);
2090 if (!$nocache && !is_null($result)) {
2091 logger('Feed duration: ' . number_format(microtime(true) - $stamp, 3) . ' - ' . $owner_nick . ' - ' . $filter . ' - ' . $previous_created . ' (cached)', LOGGER_DEBUG);
2092 $last_update = $result['last_update'];
2093 return $result['feed'];
2096 $owner = dba::fetch_first(
2097 "SELECT `contact`.*, `user`.`nickname`, `user`.`timezone`, `user`.`page-flags`
2098 FROM `contact` INNER JOIN `user` ON `user`.`uid` = `contact`.`uid`
2099 WHERE `contact`.`self` AND `user`.`nickname` = ? LIMIT 1",
2102 if (!DBM::is_result($owner)) {
2106 if (!strlen($last_update)) {
2107 $last_update = 'now -30 days';
2110 $check_date = DateTimeFormat::utc($last_update);
2111 $authorid = Contact::getIdForURL($owner["url"], 0, true);
2114 if ($filter === 'posts') {
2115 $sql_extra .= ' AND `item`.`id` = `item`.`parent` ';
2118 if ($filter === 'comments') {
2119 $sql_extra .= sprintf(" AND `item`.`object-type` = '%s' ", dbesc(ACTIVITY_OBJ_COMMENT));
2123 "SELECT `item`.*, `item`.`id` AS `item_id` FROM `item` USE INDEX (`uid_contactid_created`)
2124 STRAIGHT_JOIN `thread` ON `thread`.`iid` = `item`.`parent`
2125 WHERE `item`.`uid` = %d
2126 AND `item`.`contact-id` = %d
2127 AND `item`.`author-id` = %d
2128 AND `item`.`created` > '%s'
2129 AND NOT `item`.`deleted`
2130 AND NOT `item`.`private`
2131 AND `item`.`visible`
2132 AND `thread`.`network` IN ('%s', '%s')
2134 ORDER BY `item`.`created` DESC LIMIT %d",
2135 intval($owner["uid"]),
2136 intval($owner["id"]),
2139 dbesc(NETWORK_OSTATUS),
2140 dbesc(NETWORK_DFRN),
2144 $doc = new DOMDocument('1.0', 'utf-8');
2145 $doc->formatOutput = true;
2147 $root = self::addHeader($doc, $owner, $filter);
2149 foreach ($items as $item) {
2150 if (Config::get('system', 'ostatus_debug')) {
2151 $item['body'] .= '🍼';
2153 $entry = self::entry($doc, $item, $owner);
2154 $root->appendChild($entry);
2156 if ($last_update < $item['created']) {
2157 $last_update = $item['created'];
2161 $feeddata = trim($doc->saveXML());
2163 $msg = ['feed' => $feeddata, 'last_update' => $last_update];
2164 Cache::set($cachekey, $msg, CACHE_QUARTER_HOUR);
2166 logger('Feed duration: ' . number_format(microtime(true) - $stamp, 3) . ' - ' . $owner_nick . ' - ' . $filter . ' - ' . $previous_created, LOGGER_DEBUG);
2172 * @brief Creates the XML for a salmon message
2174 * @param array $item Data of the item that is to be posted
2175 * @param array $owner Contact data of the poster
2177 * @return string XML for the salmon
2179 public static function salmon($item, $owner)
2181 $doc = new DOMDocument('1.0', 'utf-8');
2182 $doc->formatOutput = true;
2184 if (Config::get('system', 'ostatus_debug')) {
2185 $item['body'] .= '🐟';
2188 $entry = self::entry($doc, $item, $owner, true);
2190 $doc->appendChild($entry);
2192 return trim($doc->saveXML());