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/bbcode.php';
30 require_once 'include/items.php';
31 require_once 'mod/share.php';
32 require_once 'include/enotify.php';
33 require_once 'include/api.php';
34 require_once 'mod/proxy.php';
37 * @brief This class contain functions for the OStatus protocol
41 private static $itemlist;
42 private static $conv_list = [];
45 * @brief Fetches author data
47 * @param object $xpath The xpath object
48 * @param object $context The xml context of the author details
49 * @param array $importer user record of the importing user
50 * @param array $contact Called by reference, will contain the fetched contact
51 * @param bool $onlyfetch Only fetch the header without updating the contact entries
53 * @return array Array of author related entries for the item
55 private static function fetchAuthor($xpath, $context, $importer, &$contact, $onlyfetch)
58 $author["author-link"] = $xpath->evaluate('atom:author/atom:uri/text()', $context)->item(0)->nodeValue;
59 $author["author-name"] = $xpath->evaluate('atom:author/atom:name/text()', $context)->item(0)->nodeValue;
60 $addr = $xpath->evaluate('atom:author/atom:email/text()', $context)->item(0)->nodeValue;
62 $aliaslink = $author["author-link"];
64 $alternate = $xpath->query("atom:author/atom:link[@rel='alternate']", $context)->item(0)->attributes;
65 if (is_object($alternate)) {
66 foreach ($alternate as $attributes) {
67 if (($attributes->name == "href") && ($attributes->textContent != "")) {
68 $author["author-link"] = $attributes->textContent;
72 $author["contact-id"] = $contact["id"];
75 if ($aliaslink != '') {
76 $condition = ["`uid` = ? AND `alias` = ? AND `network` != ?",
77 $importer["uid"], $aliaslink, NETWORK_STATUSNET];
78 $contact = dba::selectFirst('contact', [], $condition);
81 if (!DBM::is_result($contact) && $author["author-link"] != '') {
82 if ($aliaslink == "") {
83 $aliaslink = $author["author-link"];
86 $condition = ["`uid` = ? AND `nurl` IN (?, ?) AND `network` != ?", $importer["uid"],
87 normalise_link($author["author-link"]), normalise_link($aliaslink), NETWORK_STATUSNET];
88 $contact = dba::selectFirst('contact', [], $condition);
91 if (!DBM::is_result($contact) && ($addr != '')) {
92 $condition = ["`uid` = ? AND `addr` = ? AND `network` != ?",
93 $importer["uid"], $addr, NETWORK_STATUSNET];
94 $contact = dba::selectFirst('contact', [], $condition);
97 if (DBM::is_result($contact)) {
98 if ($contact['blocked']) {
101 $author["contact-id"] = $contact["id"];
105 $avatars = $xpath->query("atom:author/atom:link[@rel='avatar']", $context);
106 foreach ($avatars as $avatar) {
109 foreach ($avatar->attributes as $attributes) {
110 if ($attributes->name == "href") {
111 $href = $attributes->textContent;
113 if ($attributes->name == "width") {
114 $width = $attributes->textContent;
118 $avatarlist[$width] = $href;
121 if (count($avatarlist) > 0) {
123 $author["author-avatar"] = Probe::fixAvatar(current($avatarlist), $author["author-link"]);
126 $displayname = $xpath->evaluate('atom:author/poco:displayName/text()', $context)->item(0)->nodeValue;
127 if ($displayname != "") {
128 $author["author-name"] = $displayname;
131 $author["owner-name"] = $author["author-name"];
132 $author["owner-link"] = $author["author-link"];
133 $author["owner-avatar"] = $author["author-avatar"];
135 // Only update the contacts if it is an OStatus contact
136 if (DBM::is_result($contact) && ($contact['id'] > 0) && !$onlyfetch && ($contact["network"] == NETWORK_OSTATUS)) {
138 // Update contact data
140 unset($current['name-date']);
142 // This query doesn't seem to work
143 // $value = $xpath->query("atom:link[@rel='salmon']", $context)->item(0)->nodeValue;
145 // $contact["notify"] = $value;
147 // This query doesn't seem to work as well - I hate these queries
148 // $value = $xpath->query("atom:link[@rel='self' and @type='application/atom+xml']", $context)->item(0)->nodeValue;
150 // $contact["poll"] = $value;
152 $contact['url'] = $author["author-link"];
153 $contact['nurl'] = normalise_link($contact['url']);
155 $value = $xpath->evaluate('atom:author/atom:uri/text()', $context)->item(0)->nodeValue;
157 $contact["alias"] = $value;
160 $value = $xpath->evaluate('atom:author/poco:displayName/text()', $context)->item(0)->nodeValue;
162 $contact["name"] = $value;
165 $value = $xpath->evaluate('atom:author/poco:preferredUsername/text()', $context)->item(0)->nodeValue;
167 $contact["nick"] = $value;
170 $value = $xpath->evaluate('atom:author/poco:note/text()', $context)->item(0)->nodeValue;
172 $contact["about"] = html2bbcode($value);
175 $value = $xpath->evaluate('atom:author/poco:address/poco:formatted/text()', $context)->item(0)->nodeValue;
177 $contact["location"] = $value;
180 $contact['name-date'] = DateTimeFormat::utcNow();
182 dba::update('contact', $contact, ['id' => $contact["id"]], $current);
184 if (!empty($author["author-avatar"]) && ($author["author-avatar"] != $current['avatar'])) {
185 logger("Update profile picture for contact ".$contact["id"], LOGGER_DEBUG);
186 Contact::updateAvatar($author["author-avatar"], $importer["uid"], $contact["id"]);
189 // Ensure that we are having this contact (with uid=0)
190 $cid = Contact::getIdForURL($aliaslink, 0);
193 $fields = ['url', 'nurl', 'name', 'nick', 'alias', 'about', 'location'];
194 $old_contact = dba::selectFirst('contact', $fields, ['id' => $cid]);
196 // Update it with the current values
197 $fields = ['url' => $author["author-link"], 'name' => $contact["name"],
198 'nurl' => normalise_link($author["author-link"]),
199 'nick' => $contact["nick"], 'alias' => $contact["alias"],
200 'about' => $contact["about"], 'location' => $contact["location"],
201 'success_update' => DateTimeFormat::utcNow(), 'last-update' => DateTimeFormat::utcNow()];
203 dba::update('contact', $fields, ['id' => $cid], $old_contact);
206 Contact::updateAvatar($author["author-avatar"], 0, $cid);
209 $contact["generation"] = 2;
210 $contact["hide"] = false; // OStatus contacts are never hidden
211 $contact["photo"] = $author["author-avatar"];
212 $gcid = GContact::update($contact);
214 GContact::link($gcid, $contact["uid"], $contact["id"]);
221 * @brief Fetches author data from a given XML string
223 * @param string $xml The XML
224 * @param array $importer user record of the importing user
226 * @return array Array of author related entries for the item
228 public static function salmonAuthor($xml, $importer)
234 $doc = new DOMDocument();
235 @$doc->loadXML($xml);
237 $xpath = new DOMXPath($doc);
238 $xpath->registerNamespace('atom', NAMESPACE_ATOM1);
239 $xpath->registerNamespace('thr', NAMESPACE_THREAD);
240 $xpath->registerNamespace('georss', NAMESPACE_GEORSS);
241 $xpath->registerNamespace('activity', NAMESPACE_ACTIVITY);
242 $xpath->registerNamespace('media', NAMESPACE_MEDIA);
243 $xpath->registerNamespace('poco', NAMESPACE_POCO);
244 $xpath->registerNamespace('ostatus', NAMESPACE_OSTATUS);
245 $xpath->registerNamespace('statusnet', NAMESPACE_STATUSNET);
247 $entries = $xpath->query('/atom:entry');
249 foreach ($entries as $entry) {
251 $author = self::fetchAuthor($xpath, $entry, $importer, $contact, true);
257 * @brief Read attributes from element
259 * @param object $element Element object
261 * @return array attributes
263 private static function readAttributes($element)
267 foreach ($element->attributes as $attributes) {
268 $attribute[$attributes->name] = $attributes->textContent;
275 * @brief Imports an XML string containing OStatus elements
277 * @param string $xml The XML
278 * @param array $importer user record of the importing user
279 * @param array $contact contact
280 * @param string $hub Called by reference, returns the fetched hub data
283 public static function import($xml, $importer, &$contact, &$hub)
285 self::process($xml, $importer, $contact, $hub);
289 * @brief Internal feed processing
291 * @param string $xml The XML
292 * @param array $importer user record of the importing user
293 * @param array $contact contact
294 * @param string $hub Called by reference, returns the fetched hub data
295 * @param boolean $stored Is the post fresh imported or from the database?
296 * @param boolean $initialize Is it the leading post so that data has to be initialized?
298 * @return boolean Could the XML be processed?
300 private static function process($xml, $importer, &$contact, &$hub, $stored = false, $initialize = true)
303 self::$itemlist = [];
304 self::$conv_list = [];
307 logger("Import OStatus message", LOGGER_DEBUG);
312 $doc = new DOMDocument();
313 @$doc->loadXML($xml);
315 $xpath = new DOMXPath($doc);
316 $xpath->registerNamespace('atom', NAMESPACE_ATOM1);
317 $xpath->registerNamespace('thr', NAMESPACE_THREAD);
318 $xpath->registerNamespace('georss', NAMESPACE_GEORSS);
319 $xpath->registerNamespace('activity', NAMESPACE_ACTIVITY);
320 $xpath->registerNamespace('media', NAMESPACE_MEDIA);
321 $xpath->registerNamespace('poco', NAMESPACE_POCO);
322 $xpath->registerNamespace('ostatus', NAMESPACE_OSTATUS);
323 $xpath->registerNamespace('statusnet', NAMESPACE_STATUSNET);
326 $hub_attributes = $xpath->query("/atom:feed/atom:link[@rel='hub']")->item(0)->attributes;
327 if (is_object($hub_attributes)) {
328 foreach ($hub_attributes as $hub_attribute) {
329 if ($hub_attribute->name == "href") {
330 $hub = $hub_attribute->textContent;
331 logger("Found hub ".$hub, LOGGER_DEBUG);
337 $header["uid"] = $importer["uid"];
338 $header["network"] = NETWORK_OSTATUS;
339 $header["type"] = "remote";
341 $header["origin"] = 0;
342 $header["gravity"] = GRAVITY_PARENT;
344 $first_child = $doc->firstChild->tagName;
346 if ($first_child == "feed") {
347 $entries = $xpath->query('/atom:feed/atom:entry');
349 $entries = $xpath->query('/atom:entry');
352 if ($entries->length == 1) {
353 // We reformat the XML to make it better readable
354 $doc2 = new DOMDocument();
355 $doc2->loadXML($xml);
356 $doc2->preserveWhiteSpace = false;
357 $doc2->formatOutput = true;
358 $xml2 = $doc2->saveXML();
360 $header["protocol"] = PROTOCOL_OSTATUS_SALMON;
361 $header["source"] = $xml2;
362 } elseif (!$initialize) {
366 // Fetch the first author
367 $authordata = $xpath->query('//author')->item(0);
368 $author = self::fetchAuthor($xpath, $authordata, $importer, $contact, $stored);
370 $entry = $xpath->query('/atom:entry');
372 // Reverse the order of the entries
375 foreach ($entries as $entry) {
376 $entrylist[] = $entry;
379 foreach (array_reverse($entrylist) as $entry) {
381 $authorelement = $xpath->query('/atom:entry/atom:author', $entry);
383 if ($authorelement->length == 0) {
384 $authorelement = $xpath->query('atom:author', $entry);
387 if ($authorelement->length > 0) {
388 $author = self::fetchAuthor($xpath, $entry, $importer, $contact, $stored);
391 $value = $xpath->evaluate('atom:author/poco:preferredUsername/text()', $entry)->item(0)->nodeValue;
395 $nickname = $author["author-name"];
398 $item = array_merge($header, $author);
400 $item["uri"] = $xpath->query('atom:id/text()', $entry)->item(0)->nodeValue;
402 $item["verb"] = $xpath->query('activity:verb/text()', $entry)->item(0)->nodeValue;
405 if (in_array($item["verb"], ['qvitter-delete-notice', ACTIVITY_DELETE, 'delete'])) {
406 self::deleteNotice($item);
410 if (in_array($item["verb"], [NAMESPACE_OSTATUS."/unfavorite", ACTIVITY_UNFAVORITE])) {
411 // Ignore "Unfavorite" message
412 logger("Ignore unfavorite message ".print_r($item, true), LOGGER_DEBUG);
416 // Deletions come with the same uri, so we check for duplicates after processing deletions
417 if (dba::exists('item', ['uid' => $importer["uid"], 'uri' => $item["uri"]])) {
418 logger('Post with URI '.$item["uri"].' already existed for user '.$importer["uid"].'.', LOGGER_DEBUG);
421 logger('Processing post with URI '.$item["uri"].' for user '.$importer["uid"].'.', LOGGER_DEBUG);
424 if ($item["verb"] == ACTIVITY_JOIN) {
425 // ignore "Join" messages
426 logger("Ignore join message ".print_r($item, true), LOGGER_DEBUG);
430 if ($item["verb"] == "http://mastodon.social/schema/1.0/block") {
431 // ignore mastodon "block" messages
432 logger("Ignore block message ".print_r($item, true), LOGGER_DEBUG);
436 if ($item["verb"] == ACTIVITY_FOLLOW) {
437 Contact::addRelationship($importer, $contact, $item, $nickname);
441 if ($item["verb"] == NAMESPACE_OSTATUS."/unfollow") {
442 Contact::removeFollower($importer, $contact, $item, $dummy);
446 if ($item["verb"] == ACTIVITY_FAVORITE) {
447 $orig_uri = $xpath->query("activity:object/atom:id", $entry)->item(0)->nodeValue;
448 logger("Favorite ".$orig_uri." ".print_r($item, true));
450 $item["verb"] = ACTIVITY_LIKE;
451 $item["parent-uri"] = $orig_uri;
452 $item["gravity"] = GRAVITY_LIKE;
455 // http://activitystrea.ms/schema/1.0/rsvp-yes
456 if (!in_array($item["verb"], [ACTIVITY_POST, ACTIVITY_LIKE, ACTIVITY_SHARE])) {
457 logger("Unhandled verb ".$item["verb"]." ".print_r($item, true), LOGGER_DEBUG);
460 self::processPost($xpath, $entry, $item, $importer);
462 if ($initialize && (count(self::$itemlist) > 0)) {
463 if (self::$itemlist[0]['uri'] == self::$itemlist[0]['parent-uri']) {
464 // We will import it everytime, when it is started by our contacts
465 $valid = !empty(self::$itemlist[0]['contact-id']);
467 // If not, then it depends on this setting
468 $valid = !Config::get('system', 'ostatus_full_threads');
471 // Never post a thread when the only interaction by our contact was a like
473 $verbs = [ACTIVITY_POST, ACTIVITY_SHARE];
474 foreach (self::$itemlist as $item) {
475 if (!empty($item['contact-id']) && in_array($item['verb'], $verbs)) {
481 // But we will only import complete threads
482 $valid = dba::exists('item', ['uid' => $importer["uid"], 'uri' => self::$itemlist[0]['parent-uri']]);
486 $default_contact = 0;
487 $key = count(self::$itemlist);
488 for ($key = count(self::$itemlist) - 1; $key >= 0; $key--) {
489 if (empty(self::$itemlist[$key]['contact-id'])) {
490 self::$itemlist[$key]['contact-id'] = $default_contact;
492 $default_contact = $item['contact-id'];
495 foreach (self::$itemlist as $item) {
496 $found = dba::exists('item', ['uid' => $importer["uid"], 'uri' => $item["uri"]]);
498 logger("Item with uri ".$item["uri"]." for user ".$importer["uid"]." already exists.", LOGGER_DEBUG);
499 } elseif ($item['contact-id'] < 0) {
500 logger("Item with uri ".$item["uri"]." is from a blocked contact.", LOGGER_DEBUG);
502 // We are having duplicated entries. Hopefully this solves it.
503 if (Lock::set('ostatus_process_item_insert')) {
504 $ret = Item::insert($item);
505 Lock::remove('ostatus_process_item_insert');
506 logger("Item with uri ".$item["uri"]." for user ".$importer["uid"].' stored. Return value: '.$ret);
508 $ret = Item::insert($item);
509 logger("We couldn't lock - but tried to store the item anyway. Return value is ".$ret);
514 self::$itemlist = [];
516 logger('Processing done for post with URI '.$item["uri"].' for user '.$importer["uid"].'.', LOGGER_DEBUG);
522 * @param object $item item
525 private static function deleteNotice($item)
527 $condition = ['uid' => $item['uid'], 'author-link' => $item['author-link'], 'uri' => $item['uri']];
528 $deleted = dba::selectFirst('item', ['id', 'parent-uri'], $condition);
529 if (!DBM::is_result($deleted)) {
530 logger('Item from '.$item['author-link'].' with uri '.$item['uri'].' for user '.$item['uid']." wasn't found. We don't delete it. ");
534 Item::deleteById($deleted["id"]);
536 logger('Deleted item with uri '.$item['uri'].' for user '.$item['uid']);
540 * @brief Processes the XML for a post
542 * @param object $xpath The xpath object
543 * @param object $entry The xml entry that is processed
544 * @param array $item The item array
545 * @param array $importer user record of the importing user
548 private static function processPost($xpath, $entry, &$item, $importer)
550 $item["body"] = html2bbcode($xpath->query('atom:content/text()', $entry)->item(0)->nodeValue);
551 $item["object-type"] = $xpath->query('activity:object-type/text()', $entry)->item(0)->nodeValue;
552 if (($item["object-type"] == ACTIVITY_OBJ_BOOKMARK) || ($item["object-type"] == ACTIVITY_OBJ_EVENT)) {
553 $item["title"] = $xpath->query('atom:title/text()', $entry)->item(0)->nodeValue;
554 $item["body"] = $xpath->query('atom:summary/text()', $entry)->item(0)->nodeValue;
555 } elseif ($item["object-type"] == ACTIVITY_OBJ_QUESTION) {
556 $item["title"] = $xpath->query('atom:title/text()', $entry)->item(0)->nodeValue;
559 $item["created"] = $xpath->query('atom:published/text()', $entry)->item(0)->nodeValue;
560 $item["edited"] = $xpath->query('atom:updated/text()', $entry)->item(0)->nodeValue;
561 $conversation = $xpath->query('ostatus:conversation/text()', $entry)->item(0)->nodeValue;
562 $item['conversation-uri'] = $conversation;
564 $conv = $xpath->query('ostatus:conversation', $entry);
565 if (is_object($conv->item(0))) {
566 foreach ($conv->item(0)->attributes as $attributes) {
567 if ($attributes->name == "ref") {
568 $item['conversation-uri'] = $attributes->textContent;
570 if ($attributes->name == "href") {
571 $item['conversation-href'] = $attributes->textContent;
578 $inreplyto = $xpath->query('thr:in-reply-to', $entry);
579 if (is_object($inreplyto->item(0))) {
580 foreach ($inreplyto->item(0)->attributes as $attributes) {
581 if ($attributes->name == "ref") {
582 $item["parent-uri"] = $attributes->textContent;
584 if ($attributes->name == "href") {
585 $related = $attributes->textContent;
590 $georsspoint = $xpath->query('georss:point', $entry);
591 if (!empty($georsspoint) && ($georsspoint->length > 0)) {
592 $item["coord"] = $georsspoint->item(0)->nodeValue;
595 $categories = $xpath->query('atom:category', $entry);
597 foreach ($categories as $category) {
598 foreach ($category->attributes as $attributes) {
599 if ($attributes->name == "term") {
600 $term = $attributes->textContent;
601 if (strlen($item["tag"])) {
604 $item["tag"] .= "#[url=".System::baseUrl()."/search?tag=".$term."]".$term."[/url]";
613 $links = $xpath->query('atom:link', $entry);
615 $link_data = self::processLinks($links, $item);
616 $self = $link_data['self'];
617 $add_body = $link_data['add_body'];
622 $notice_info = $xpath->query('statusnet:notice_info', $entry);
623 if ($notice_info && ($notice_info->length > 0)) {
624 foreach ($notice_info->item(0)->attributes as $attributes) {
625 if ($attributes->name == "source") {
626 $item["app"] = strip_tags($attributes->textContent);
628 if ($attributes->name == "repeat_of") {
629 $repeat_of = $attributes->textContent;
633 // Is it a repeated post?
634 if (($repeat_of != "") || ($item["verb"] == ACTIVITY_SHARE)) {
635 $link_data = self::processRepeatedItem($xpath, $entry, $item, $importer);
636 if (!empty($link_data['add_body'])) {
637 $add_body .= $link_data['add_body'];
641 $item["body"] .= $add_body;
643 // Only add additional data when there is no picture in the post
644 if (!strstr($item["body"], '[/img]')) {
645 $item["body"] = add_page_info_to_body($item["body"]);
648 // Mastodon Content Warning
649 if (($item["verb"] == ACTIVITY_POST) && $xpath->evaluate('boolean(atom:summary)', $entry)) {
650 $clear_text = $xpath->query('atom:summary/text()', $entry)->item(0)->nodeValue;
652 $item["body"] = html2bbcode($clear_text) . '[spoiler]' . $item["body"] . '[/spoiler]';
655 if (($self != '') && empty($item['protocol'])) {
656 self::fetchSelf($self, $item);
659 if (!empty($item["conversation-href"])) {
660 self::fetchConversation($item['conversation-href'], $item['conversation-uri']);
663 if (isset($item["parent-uri"]) && ($related != '')) {
664 if (!dba::exists('item', ['uid' => $importer["uid"], 'uri' => $item['parent-uri']])) {
665 self::fetchRelated($related, $item["parent-uri"], $importer);
667 logger('Reply with URI '.$item["uri"].' already existed for user '.$importer["uid"].'.', LOGGER_DEBUG);
670 $item["type"] = 'remote-comment';
671 $item["gravity"] = GRAVITY_COMMENT;
673 $item["parent-uri"] = $item["uri"];
676 if (($item['author-link'] != '') && !empty($item['protocol'])) {
677 $item = Conversation::insert($item);
680 self::$itemlist[] = $item;
684 * @brief Fetch the conversation for posts
686 * @param string $conversation The link to the conversation
687 * @param string $conversation_uri The conversation in "uri" format
690 private static function fetchConversation($conversation, $conversation_uri)
692 // Ensure that we only store a conversation once in a process
693 if (isset(self::$conv_list[$conversation])) {
697 self::$conv_list[$conversation] = true;
699 $conversation_data = Network::curl($conversation, false, $redirects, ['accept_content' => 'application/atom+xml, text/html']);
701 if (!$conversation_data['success']) {
707 if (stristr($conversation_data['header'], 'Content-Type: application/atom+xml')) {
708 $xml = $conversation_data['body'];
712 $doc = new DOMDocument();
713 if (!@$doc->loadHTML($conversation_data['body'])) {
716 $xpath = new DOMXPath($doc);
718 $links = $xpath->query('//link');
721 foreach ($links as $link) {
722 $attribute = self::readAttributes($link);
723 if (($attribute['rel'] == 'alternate') && ($attribute['type'] == 'application/atom+xml')) {
724 $file = $attribute['href'];
728 $conversation_atom = Network::curl($attribute['href']);
730 if ($conversation_atom['success']) {
731 $xml = $conversation_atom['body'];
741 self::storeConversation($xml, $conversation, $conversation_uri);
745 * @brief Store a feed in several conversation entries
747 * @param string $xml The feed
748 * @param string $conversation conversation
749 * @param string $conversation_uri conversation uri
752 private static function storeConversation($xml, $conversation = '', $conversation_uri = '')
754 $doc = new DOMDocument();
755 @$doc->loadXML($xml);
757 $xpath = new DOMXPath($doc);
758 $xpath->registerNamespace('atom', NAMESPACE_ATOM1);
759 $xpath->registerNamespace('thr', NAMESPACE_THREAD);
760 $xpath->registerNamespace('ostatus', NAMESPACE_OSTATUS);
762 $entries = $xpath->query('/atom:feed/atom:entry');
764 // Now store the entries
765 foreach ($entries as $entry) {
766 $doc2 = new DOMDocument();
767 $doc2->preserveWhiteSpace = false;
768 $doc2->formatOutput = true;
772 $conv_data['protocol'] = PROTOCOL_SPLITTED_CONV;
773 $conv_data['network'] = NETWORK_OSTATUS;
774 $conv_data['uri'] = $xpath->query('atom:id/text()', $entry)->item(0)->nodeValue;
776 $inreplyto = $xpath->query('thr:in-reply-to', $entry);
777 if (is_object($inreplyto->item(0))) {
778 foreach ($inreplyto->item(0)->attributes as $attributes) {
779 if ($attributes->name == "ref") {
780 $conv_data['reply-to-uri'] = $attributes->textContent;
785 $conv = $xpath->query('ostatus:conversation/text()', $entry)->item(0)->nodeValue;
786 $conv_data['conversation-uri'] = $conv;
788 $conv = $xpath->query('ostatus:conversation', $entry);
789 if (is_object($conv->item(0))) {
790 foreach ($conv->item(0)->attributes as $attributes) {
791 if ($attributes->name == "ref") {
792 $conv_data['conversation-uri'] = $attributes->textContent;
794 if ($attributes->name == "href") {
795 $conv_data['conversation-href'] = $attributes->textContent;
800 if ($conversation != '') {
801 $conv_data['conversation-uri'] = $conversation;
804 if ($conversation_uri != '') {
805 $conv_data['conversation-uri'] = $conversation_uri;
808 $entry = $doc2->importNode($entry, true);
810 $doc2->appendChild($entry);
812 $conv_data['source'] = $doc2->saveXML();
814 $condition = ['item-uri' => $conv_data['uri'],'protocol' => PROTOCOL_OSTATUS_FEED];
815 if (dba::exists('conversation', $condition)) {
816 logger('Delete deprecated entry for URI '.$conv_data['uri'], LOGGER_DEBUG);
817 dba::delete('conversation', ['item-uri' => $conv_data['uri']]);
820 logger('Store conversation data for uri '.$conv_data['uri'], LOGGER_DEBUG);
821 Conversation::insert($conv_data);
826 * @brief Fetch the own post so that it can be stored later
828 * We want to store the original data for later processing.
829 * This function is meant for cases where we process a feed with multiple entries.
830 * In that case we need to fetch the single posts here.
832 * @param string $self The link to the self item
833 * @param array $item The item array
836 private static function fetchSelf($self, &$item)
838 $condition = ['`item-uri` = ? AND `protocol` IN (?, ?)', $self, PROTOCOL_DFRN, PROTOCOL_OSTATUS_SALMON];
839 if (dba::exists('conversation', $condition)) {
840 logger('Conversation '.$item['uri'].' is already stored.', LOGGER_DEBUG);
844 $self_data = Network::curl($self);
846 if (!$self_data['success']) {
850 // We reformat the XML to make it better readable
851 $doc = new DOMDocument();
852 $doc->loadXML($self_data['body']);
853 $doc->preserveWhiteSpace = false;
854 $doc->formatOutput = true;
855 $xml = $doc->saveXML();
857 $item["protocol"] = PROTOCOL_OSTATUS_SALMON;
858 $item["source"] = $xml;
860 logger('Conversation '.$item['uri'].' is now fetched.', LOGGER_DEBUG);
864 * @brief Fetch related posts and processes them
866 * @param string $related The link to the related item
867 * @param string $related_uri The related item in "uri" format
868 * @param array $importer user record of the importing user
871 private static function fetchRelated($related, $related_uri, $importer)
873 $condition = ['`item-uri` = ? AND `protocol` IN (?, ?)', $related_uri, PROTOCOL_DFRN, PROTOCOL_OSTATUS_SALMON];
874 $conversation = dba::selectFirst('conversation', ['source', 'protocol'], $condition);
875 if (DBM::is_result($conversation)) {
877 $xml = $conversation['source'];
878 if (self::process($xml, $importer, $contact, $hub, $stored, false)) {
879 logger('Got valid cached XML for URI '.$related_uri, LOGGER_DEBUG);
882 if ($conversation['protocol'] == PROTOCOL_OSTATUS_SALMON) {
883 logger('Delete invalid cached XML for URI '.$related_uri, LOGGER_DEBUG);
884 dba::delete('conversation', ['item-uri' => $related_uri]);
889 $related_data = Network::curl($related, false, $redirects, ['accept_content' => 'application/atom+xml, text/html']);
891 if (!$related_data['success']) {
897 if (stristr($related_data['header'], 'Content-Type: application/atom+xml')) {
898 logger('Directly fetched XML for URI '.$related_uri, LOGGER_DEBUG);
899 $xml = $related_data['body'];
903 $doc = new DOMDocument();
904 if (!@$doc->loadHTML($related_data['body'])) {
907 $xpath = new DOMXPath($doc);
911 $links = $xpath->query('//link');
913 foreach ($links as $link) {
914 $attribute = self::readAttributes($link);
915 if (($attribute['rel'] == 'alternate') && ($attribute['type'] == 'application/atom+xml')) {
916 $atom_file = $attribute['href'];
919 if ($atom_file != '') {
920 $related_atom = Network::curl($atom_file);
922 if ($related_atom['success']) {
923 logger('Fetched XML for URI '.$related_uri, LOGGER_DEBUG);
924 $xml = $related_atom['body'];
930 // Workaround for older GNU Social servers
931 if (($xml == '') && strstr($related, '/notice/')) {
932 $related_atom = Network::curl(str_replace('/notice/', '/api/statuses/show/', $related).'.atom');
934 if ($related_atom['success']) {
935 logger('GNU Social workaround to fetch XML for URI '.$related_uri, LOGGER_DEBUG);
936 $xml = $related_atom['body'];
940 // Even more worse workaround for GNU Social ;-)
942 $related_guess = OStatus::convertHref($related_uri);
943 $related_atom = Network::curl(str_replace('/notice/', '/api/statuses/show/', $related_guess).'.atom');
945 if ($related_atom['success']) {
946 logger('GNU Social workaround 2 to fetch XML for URI '.$related_uri, LOGGER_DEBUG);
947 $xml = $related_atom['body'];
951 // Finally we take the data that we fetched from "ostatus:conversation"
953 $condition = ['item-uri' => $related_uri, 'protocol' => PROTOCOL_SPLITTED_CONV];
954 $conversation = dba::selectFirst('conversation', ['source'], $condition);
955 if (DBM::is_result($conversation)) {
957 logger('Got cached XML from conversation for URI '.$related_uri, LOGGER_DEBUG);
958 $xml = $conversation['source'];
963 self::process($xml, $importer, $contact, $hub, $stored, false);
965 logger("XML couldn't be fetched for URI: ".$related_uri." - href: ".$related, LOGGER_DEBUG);
971 * @brief Processes the XML for a repeated post
973 * @param object $xpath The xpath object
974 * @param object $entry The xml entry that is processed
975 * @param array $item The item array
976 * @param array $importer user record of the importing user
978 * @return array with data from links
980 private static function processRepeatedItem($xpath, $entry, &$item, $importer)
982 $activityobjects = $xpath->query('activity:object', $entry)->item(0);
984 if (!is_object($activityobjects)) {
990 $orig_uri = $xpath->query('atom:id/text()', $activityobjects)->item(0)->nodeValue;
992 $links = $xpath->query("atom:link", $activityobjects);
994 $link_data = self::processLinks($links, $item);
997 $orig_body = $xpath->query('atom:content/text()', $activityobjects)->item(0)->nodeValue;
998 $orig_created = $xpath->query('atom:published/text()', $activityobjects)->item(0)->nodeValue;
999 $orig_edited = $xpath->query('atom:updated/text()', $activityobjects)->item(0)->nodeValue;
1001 $orig_author = self::fetchAuthor($xpath, $activityobjects, $importer, $dummy, false);
1003 $item["author-name"] = $orig_author["author-name"];
1004 $item["author-link"] = $orig_author["author-link"];
1005 $item["author-avatar"] = $orig_author["author-avatar"];
1007 $item["body"] = html2bbcode($orig_body);
1008 $item["created"] = $orig_created;
1009 $item["edited"] = $orig_edited;
1011 $item["uri"] = $orig_uri;
1013 $item["verb"] = $xpath->query('activity:verb/text()', $activityobjects)->item(0)->nodeValue;
1015 $item["object-type"] = $xpath->query('activity:object-type/text()', $activityobjects)->item(0)->nodeValue;
1017 $inreplyto = $xpath->query('thr:in-reply-to', $activityobjects);
1018 if (is_object($inreplyto->item(0))) {
1019 foreach ($inreplyto->item(0)->attributes as $attributes) {
1020 if ($attributes->name == "ref") {
1021 $item["parent-uri"] = $attributes->textContent;
1030 * @brief Processes links in the XML
1032 * @param object $links The xml data that contain links
1033 * @param array $item The item array
1035 * @return array with data from the links
1037 private static function processLinks($links, &$item)
1039 $link_data = ['add_body' => '', 'self' => ''];
1041 foreach ($links as $link) {
1042 $attribute = self::readAttributes($link);
1044 if (($attribute['rel'] != "") && ($attribute['href'] != "")) {
1045 switch ($attribute['rel']) {
1047 $item["plink"] = $attribute['href'];
1048 if (($item["object-type"] == ACTIVITY_OBJ_QUESTION)
1049 || ($item["object-type"] == ACTIVITY_OBJ_EVENT)
1051 $item["body"] .= add_page_info($attribute['href']);
1054 case "ostatus:conversation":
1055 $link_data['conversation'] = $attribute['href'];
1056 $item['conversation-href'] = $link_data['conversation'];
1057 if (!isset($item['conversation-uri'])) {
1058 $item['conversation-uri'] = $item['conversation-href'];
1062 $filetype = strtolower(substr($attribute['type'], 0, strpos($attribute['type'], '/')));
1063 if ($filetype == 'image') {
1064 $link_data['add_body'] .= "\n[img]".$attribute['href'].'[/img]';
1066 if (strlen($item["attach"])) {
1067 $item["attach"] .= ',';
1069 if (!isset($attribute['length'])) {
1070 $attribute['length'] = "0";
1072 $item["attach"] .= '[attach]href="'.$attribute['href'].'" length="'.$attribute['length'].'" type="'.$attribute['type'].'" title="'.$attribute['title'].'"[/attach]';
1076 if ($item["object-type"] != ACTIVITY_OBJ_BOOKMARK) {
1077 if (!isset($item["parent-uri"])) {
1078 $item["parent-uri"] = $attribute['href'];
1080 $link_data['related'] = $attribute['href'];
1082 $item["body"] .= add_page_info($attribute['href']);
1086 if ($item["plink"] == '') {
1087 $item["plink"] = $attribute['href'];
1089 $link_data['self'] = $attribute['href'];
1098 * @brief Create an url out of an uri
1100 * @param string $href URI in the format "parameter1:parameter1:..."
1102 * @return string URL in the format http(s)://....
1104 public static function convertHref($href)
1106 $elements = explode(":", $href);
1108 if ((count($elements) <= 2) || ($elements[0] != "tag")) {
1112 $server = explode(",", $elements[1]);
1113 $conversation = explode("=", $elements[2]);
1115 if ((count($elements) == 4) && ($elements[2] == "post")) {
1116 return "http://".$server[0]."/notice/".$elements[3];
1119 if ((count($conversation) != 2) || ($conversation[1] =="")) {
1122 if ($elements[3] == "objectType=thread") {
1123 return "http://".$server[0]."/conversation/".$conversation[1];
1125 return "http://".$server[0]."/notice/".$conversation[1];
1131 * @brief Checks if the current post is a reshare
1133 * @param array $item The item array of thw post
1135 * @return string The guid if the post is a reshare
1137 private static function getResharedGuid($item)
1139 $body = trim($item["body"]);
1141 // Skip if it isn't a pure repeated messages
1142 // Does it start with a share?
1143 if (strpos($body, "[share") > 0) {
1147 // Does it end with a share?
1148 if (strlen($body) > (strrpos($body, "[/share]") + 8)) {
1152 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "$1", $body);
1153 // Skip if there is no shared message in there
1154 if ($body == $attributes) {
1159 preg_match("/guid='(.*?)'/ism", $attributes, $matches);
1160 if ($matches[1] != "") {
1161 $guid = $matches[1];
1164 preg_match('/guid="(.*?)"/ism', $attributes, $matches);
1165 if ($matches[1] != "") {
1166 $guid = $matches[1];
1173 * @brief Cleans the body of a post if it contains picture links
1175 * @param string $body The body
1177 * @return string The cleaned body
1179 private static function formatPicturePost($body)
1181 $siteinfo = BBCode::getAttachedData($body);
1183 if (($siteinfo["type"] == "photo")) {
1184 if (isset($siteinfo["preview"])) {
1185 $preview = $siteinfo["preview"];
1187 $preview = $siteinfo["image"];
1190 // Is it a remote picture? Then make a smaller preview here
1191 $preview = proxy_url($preview, false, PROXY_SIZE_SMALL);
1193 // Is it a local picture? Then make it smaller here
1194 $preview = str_replace(["-0.jpg", "-0.png"], ["-2.jpg", "-2.png"], $preview);
1195 $preview = str_replace(["-1.jpg", "-1.png"], ["-2.jpg", "-2.png"], $preview);
1197 if (isset($siteinfo["url"])) {
1198 $url = $siteinfo["url"];
1200 $url = $siteinfo["image"];
1203 $body = trim($siteinfo["text"])." [url]".$url."[/url]\n[img]".$preview."[/img]";
1210 * @brief Adds the header elements to the XML document
1212 * @param object $doc XML document
1213 * @param array $owner Contact data of the poster
1214 * @param string $filter The related feed filter (activity, posts or comments)
1216 * @return object header root element
1218 private static function addHeader($doc, $owner, $filter)
1222 $root = $doc->createElementNS(NAMESPACE_ATOM1, 'feed');
1223 $doc->appendChild($root);
1225 $root->setAttribute("xmlns:thr", NAMESPACE_THREAD);
1226 $root->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
1227 $root->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
1228 $root->setAttribute("xmlns:media", NAMESPACE_MEDIA);
1229 $root->setAttribute("xmlns:poco", NAMESPACE_POCO);
1230 $root->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
1231 $root->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
1232 $root->setAttribute("xmlns:mastodon", NAMESPACE_MASTODON);
1236 case 'activity': $title = L10n::t('%s\'s timeline', $owner['name']); break;
1237 case 'posts' : $title = L10n::t('%s\'s posts' , $owner['name']); break;
1238 case 'comments': $title = L10n::t('%s\'s comments', $owner['name']); break;
1241 $attributes = ["uri" => "https://friendi.ca", "version" => FRIENDICA_VERSION . "-" . DB_UPDATE_VERSION];
1242 XML::addElement($doc, $root, "generator", FRIENDICA_PLATFORM, $attributes);
1243 XML::addElement($doc, $root, "id", System::baseUrl() . "/profile/" . $owner["nick"]);
1244 XML::addElement($doc, $root, "title", $title);
1245 XML::addElement($doc, $root, "subtitle", sprintf("Updates from %s on %s", $owner["name"], $a->config["sitename"]));
1246 XML::addElement($doc, $root, "logo", $owner["photo"]);
1247 XML::addElement($doc, $root, "updated", DateTimeFormat::utcNow(DateTimeFormat::ATOM));
1249 $author = self::addAuthor($doc, $owner);
1250 $root->appendChild($author);
1252 $attributes = ["href" => $owner["url"], "rel" => "alternate", "type" => "text/html"];
1253 XML::addElement($doc, $root, "link", "", $attributes);
1255 /// @TODO We have to find out what this is
1256 /// $attributes = array("href" => System::baseUrl()."/sup",
1257 /// "rel" => "http://api.friendfeed.com/2008/03#sup",
1258 /// "type" => "application/json");
1259 /// XML::addElement($doc, $root, "link", "", $attributes);
1261 self::hublinks($doc, $root, $owner["nick"]);
1263 $attributes = ["href" => System::baseUrl() . "/salmon/" . $owner["nick"], "rel" => "salmon"];
1264 XML::addElement($doc, $root, "link", "", $attributes);
1266 $attributes = ["href" => System::baseUrl() . "/salmon/" . $owner["nick"], "rel" => "http://salmon-protocol.org/ns/salmon-replies"];
1267 XML::addElement($doc, $root, "link", "", $attributes);
1269 $attributes = ["href" => System::baseUrl() . "/salmon/" . $owner["nick"], "rel" => "http://salmon-protocol.org/ns/salmon-mention"];
1270 XML::addElement($doc, $root, "link", "", $attributes);
1272 $attributes = ["href" => System::baseUrl() . "/api/statuses/user_timeline/" . $owner["nick"] . ".atom",
1273 "rel" => "self", "type" => "application/atom+xml"];
1274 XML::addElement($doc, $root, "link", "", $attributes);
1280 * @brief Add the link to the push hubs to the XML document
1282 * @param object $doc XML document
1283 * @param object $root XML root element where the hub links are added
1284 * @param object $nick nick
1287 public static function hublinks($doc, $root, $nick)
1289 $h = System::baseUrl() . '/pubsubhubbub/'.$nick;
1290 XML::addElement($doc, $root, "link", "", ["href" => $h, "rel" => "hub"]);
1294 * @brief Adds attachement data to the XML document
1296 * @param object $doc XML document
1297 * @param object $root XML root element where the hub links are added
1298 * @param array $item Data of the item that is to be posted
1301 private static function getAttachment($doc, $root, $item)
1304 $siteinfo = BBCode::getAttachedData($item["body"]);
1306 switch ($siteinfo["type"]) {
1308 $imgdata = Image::getInfoFromURL($siteinfo["image"]);
1309 $attributes = ["rel" => "enclosure",
1310 "href" => $siteinfo["image"],
1311 "type" => $imgdata["mime"],
1312 "length" => intval($imgdata["size"])];
1313 XML::addElement($doc, $root, "link", "", $attributes);
1316 $attributes = ["rel" => "enclosure",
1317 "href" => $siteinfo["url"],
1318 "type" => "text/html; charset=UTF-8",
1320 "title" => $siteinfo["title"]];
1321 XML::addElement($doc, $root, "link", "", $attributes);
1327 if (!Config::get('system', 'ostatus_not_attach_preview') && ($siteinfo["type"] != "photo") && isset($siteinfo["image"])) {
1328 $imgdata = Image::getInfoFromURL($siteinfo["image"]);
1329 $attributes = ["rel" => "enclosure",
1330 "href" => $siteinfo["image"],
1331 "type" => $imgdata["mime"],
1332 "length" => intval($imgdata["size"])];
1334 XML::addElement($doc, $root, "link", "", $attributes);
1337 $arr = explode('[/attach],', $item['attach']);
1339 foreach ($arr as $r) {
1341 $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"|', $r, $matches);
1343 $attributes = ["rel" => "enclosure",
1344 "href" => $matches[1],
1345 "type" => $matches[3]];
1347 if (intval($matches[2])) {
1348 $attributes["length"] = intval($matches[2]);
1350 if (trim($matches[4]) != "") {
1351 $attributes["title"] = trim($matches[4]);
1353 XML::addElement($doc, $root, "link", "", $attributes);
1360 * @brief Adds the author element to the XML document
1362 * @param object $doc XML document
1363 * @param array $owner Contact data of the poster
1365 * @return object author element
1367 private static function addAuthor($doc, $owner)
1369 $profile = dba::selectFirst('profile', ['homepage', 'publish'], ['uid' => $owner['uid'], 'is-default' => true]);
1370 $author = $doc->createElement("author");
1371 XML::addElement($doc, $author, "id", $owner["url"]);
1372 XML::addElement($doc, $author, "activity:object-type", ACTIVITY_OBJ_PERSON);
1373 XML::addElement($doc, $author, "uri", $owner["url"]);
1374 XML::addElement($doc, $author, "name", $owner["nick"]);
1375 XML::addElement($doc, $author, "email", $owner["addr"]);
1376 XML::addElement($doc, $author, "summary", BBCode::convert($owner["about"], false, 7));
1378 $attributes = ["rel" => "alternate", "type" => "text/html", "href" => $owner["url"]];
1379 XML::addElement($doc, $author, "link", "", $attributes);
1383 "type" => "image/jpeg", // To-Do?
1384 "media:width" => 175,
1385 "media:height" => 175,
1386 "href" => $owner["photo"]];
1387 XML::addElement($doc, $author, "link", "", $attributes);
1389 if (isset($owner["thumb"])) {
1392 "type" => "image/jpeg", // To-Do?
1393 "media:width" => 80,
1394 "media:height" => 80,
1395 "href" => $owner["thumb"]];
1396 XML::addElement($doc, $author, "link", "", $attributes);
1399 XML::addElement($doc, $author, "poco:preferredUsername", $owner["nick"]);
1400 XML::addElement($doc, $author, "poco:displayName", $owner["name"]);
1401 XML::addElement($doc, $author, "poco:note", BBCode::convert($owner["about"], false, 7));
1403 if (trim($owner["location"]) != "") {
1404 $element = $doc->createElement("poco:address");
1405 XML::addElement($doc, $element, "poco:formatted", $owner["location"]);
1406 $author->appendChild($element);
1409 if (DBM::is_result($profile)) {
1410 if (trim($profile["homepage"]) != "") {
1411 $urls = $doc->createElement("poco:urls");
1412 XML::addElement($doc, $urls, "poco:type", "homepage");
1413 XML::addElement($doc, $urls, "poco:value", $profile["homepage"]);
1414 XML::addElement($doc, $urls, "poco:primary", "true");
1415 $author->appendChild($urls);
1418 XML::addElement($doc, $author, "followers", "", ["url" => System::baseUrl()."/viewcontacts/".$owner["nick"]]);
1419 XML::addElement($doc, $author, "statusnet:profile_info", "", ["local_id" => $owner["uid"]]);
1422 if ($profile["publish"]) {
1423 XML::addElement($doc, $author, "mastodon:scope", "public");
1429 * @TODO Picture attachments should look like this:
1430 * <a href="https://status.pirati.ca/attachment/572819" title="https://status.pirati.ca/file/heluecht-20151202T222602-rd3u49p.gif"
1431 * class="attachment thumbnail" id="attachment-572819" rel="nofollow external">https://status.pirati.ca/attachment/572819</a>
1435 * @brief Returns the given activity if present - otherwise returns the "post" activity
1437 * @param array $item Data of the item that is to be posted
1439 * @return string activity
1441 private static function constructVerb($item)
1443 if ($item['verb']) {
1444 return $item['verb'];
1447 return ACTIVITY_POST;
1451 * @brief Returns the given object type if present - otherwise returns the "note" object type
1453 * @param array $item Data of the item that is to be posted
1455 * @return string Object type
1457 private static function constructObjecttype($item)
1459 if (in_array($item['object-type'], [ACTIVITY_OBJ_NOTE, ACTIVITY_OBJ_COMMENT]))
1460 return $item['object-type'];
1461 return ACTIVITY_OBJ_NOTE;
1465 * @brief Adds an entry element to the XML document
1467 * @param object $doc XML document
1468 * @param array $item Data of the item that is to be posted
1469 * @param array $owner Contact data of the poster
1470 * @param bool $toplevel optional default false
1472 * @return object Entry element
1474 private static function entry($doc, $item, $owner, $toplevel = false)
1478 $repeated_guid = self::getResharedGuid($item);
1479 if ($repeated_guid != "") {
1480 $xml = self::reshareEntry($doc, $item, $owner, $repeated_guid, $toplevel);
1487 if ($item["verb"] == ACTIVITY_LIKE) {
1488 return self::likeEntry($doc, $item, $owner, $toplevel);
1489 } elseif (in_array($item["verb"], [ACTIVITY_FOLLOW, NAMESPACE_OSTATUS."/unfollow"])) {
1490 return self::followEntry($doc, $item, $owner, $toplevel);
1492 return self::noteEntry($doc, $item, $owner, $toplevel);
1497 * @brief Adds a source entry to the XML document
1499 * @param object $doc XML document
1500 * @param array $contact Array of the contact that is added
1502 * @return object Source element
1504 private static function sourceEntry($doc, $contact)
1506 $source = $doc->createElement("source");
1507 XML::addElement($doc, $source, "id", $contact["poll"]);
1508 XML::addElement($doc, $source, "title", $contact["name"]);
1509 XML::addElement($doc, $source, "link", "", ["rel" => "alternate", "type" => "text/html", "href" => $contact["alias"]]);
1510 XML::addElement($doc, $source, "link", "", ["rel" => "self", "type" => "application/atom+xml", "href" => $contact["poll"]]);
1511 XML::addElement($doc, $source, "icon", $contact["photo"]);
1512 XML::addElement($doc, $source, "updated", DateTimeFormat::utc($contact["success_update"]."+00:00", DateTimeFormat::ATOM));
1518 * @brief Fetches contact data from the contact or the gcontact table
1520 * @param string $url URL of the contact
1521 * @param array $owner Contact data of the poster
1523 * @return array Contact array
1525 private static function contactEntry($url, $owner)
1528 "SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` IN (0, %d) ORDER BY `uid` DESC LIMIT 1",
1529 dbesc(normalise_link($url)),
1530 intval($owner["uid"])
1532 if (DBM::is_result($r)) {
1534 $contact["uid"] = -1;
1537 if (!DBM::is_result($r)) {
1539 "SELECT * FROM `gcontact` WHERE `nurl` = '%s' LIMIT 1",
1540 dbesc(normalise_link($url))
1542 if (DBM::is_result($r)) {
1544 $contact["uid"] = -1;
1545 $contact["success_update"] = $contact["updated"];
1549 if (!DBM::is_result($r)) {
1553 if (!isset($contact["poll"])) {
1554 $data = Probe::uri($url);
1555 $contact["poll"] = $data["poll"];
1557 if (!$contact["alias"]) {
1558 $contact["alias"] = $data["alias"];
1562 if (!isset($contact["alias"])) {
1563 $contact["alias"] = $contact["url"];
1570 * @brief Adds an entry element with reshared content
1572 * @param object $doc XML document
1573 * @param array $item Data of the item that is to be posted
1574 * @param array $owner Contact data of the poster
1575 * @param string $repeated_guid guid
1576 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1578 * @return object Entry element
1580 private static function reshareEntry($doc, $item, $owner, $repeated_guid, $toplevel)
1582 if (($item["id"] != $item["parent"]) && (normalise_link($item["author-link"]) != normalise_link($owner["url"]))) {
1583 logger("OStatus entry is from author ".$owner["url"]." - not from ".$item["author-link"].". Quitting.", LOGGER_DEBUG);
1586 $title = self::entryHeader($doc, $entry, $owner, $toplevel);
1589 "SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' AND NOT `private` AND `network` IN ('%s', '%s', '%s') LIMIT 1",
1590 intval($owner["uid"]),
1591 dbesc($repeated_guid),
1592 dbesc(NETWORK_DFRN),
1593 dbesc(NETWORK_DIASPORA),
1594 dbesc(NETWORK_OSTATUS)
1596 if (DBM::is_result($r)) {
1597 $repeated_item = $r[0];
1601 $contact = self::contactEntry($repeated_item['author-link'], $owner);
1603 $parent_item = (($item['thr-parent']) ? $item['thr-parent'] : $item['parent-uri']);
1605 $title = $owner["nick"]." repeated a notice by ".$contact["nick"];
1607 self::entryContent($doc, $entry, $item, $owner, $title, ACTIVITY_SHARE, false);
1609 $as_object = $doc->createElement("activity:object");
1611 XML::addElement($doc, $as_object, "activity:object-type", NAMESPACE_ACTIVITY_SCHEMA."activity");
1613 self::entryContent($doc, $as_object, $repeated_item, $owner, "", "", false);
1615 $author = self::addAuthor($doc, $contact);
1616 $as_object->appendChild($author);
1618 $as_object2 = $doc->createElement("activity:object");
1620 XML::addElement($doc, $as_object2, "activity:object-type", self::constructObjecttype($repeated_item));
1622 $title = sprintf("New comment by %s", $contact["nick"]);
1624 self::entryContent($doc, $as_object2, $repeated_item, $owner, $title);
1626 $as_object->appendChild($as_object2);
1628 self::entryFooter($doc, $as_object, $item, $owner, false);
1630 $source = self::sourceEntry($doc, $contact);
1632 $as_object->appendChild($source);
1634 $entry->appendChild($as_object);
1636 self::entryFooter($doc, $entry, $item, $owner);
1642 * @brief Adds an entry element with a "like"
1644 * @param object $doc XML document
1645 * @param array $item Data of the item that is to be posted
1646 * @param array $owner Contact data of the poster
1647 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1649 * @return object Entry element with "like"
1651 private static function likeEntry($doc, $item, $owner, $toplevel)
1653 if (($item["id"] != $item["parent"]) && (normalise_link($item["author-link"]) != normalise_link($owner["url"]))) {
1654 logger("OStatus entry is from author ".$owner["url"]." - not from ".$item["author-link"].". Quitting.", LOGGER_DEBUG);
1657 $title = self::entryHeader($doc, $entry, $owner, $toplevel);
1659 $verb = NAMESPACE_ACTIVITY_SCHEMA."favorite";
1660 self::entryContent($doc, $entry, $item, $owner, "Favorite", $verb, false);
1662 $as_object = $doc->createElement("activity:object");
1665 "SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d",
1666 dbesc($item["thr-parent"]),
1667 intval($item["uid"])
1669 $parent_item = (($item['thr-parent']) ? $item['thr-parent'] : $item['parent-uri']);
1671 XML::addElement($doc, $as_object, "activity:object-type", self::constructObjecttype($parent[0]));
1673 self::entryContent($doc, $as_object, $parent[0], $owner, "New entry");
1675 $entry->appendChild($as_object);
1677 self::entryFooter($doc, $entry, $item, $owner);
1683 * @brief Adds the person object element to the XML document
1685 * @param object $doc XML document
1686 * @param array $owner Contact data of the poster
1687 * @param array $contact Contact data of the target
1689 * @return object author element
1691 private static function addPersonObject($doc, $owner, $contact)
1693 $object = $doc->createElement("activity:object");
1694 XML::addElement($doc, $object, "activity:object-type", ACTIVITY_OBJ_PERSON);
1696 if ($contact['network'] == NETWORK_PHANTOM) {
1697 XML::addElement($doc, $object, "id", $contact['url']);
1701 XML::addElement($doc, $object, "id", $contact["alias"]);
1702 XML::addElement($doc, $object, "title", $contact["nick"]);
1704 $attributes = ["rel" => "alternate", "type" => "text/html", "href" => $contact["url"]];
1705 XML::addElement($doc, $object, "link", "", $attributes);
1709 "type" => "image/jpeg", // To-Do?
1710 "media:width" => 175,
1711 "media:height" => 175,
1712 "href" => $contact["photo"]];
1713 XML::addElement($doc, $object, "link", "", $attributes);
1715 XML::addElement($doc, $object, "poco:preferredUsername", $contact["nick"]);
1716 XML::addElement($doc, $object, "poco:displayName", $contact["name"]);
1718 if (trim($contact["location"]) != "") {
1719 $element = $doc->createElement("poco:address");
1720 XML::addElement($doc, $element, "poco:formatted", $contact["location"]);
1721 $object->appendChild($element);
1728 * @brief Adds a follow/unfollow entry element
1730 * @param object $doc XML document
1731 * @param array $item Data of the follow/unfollow message
1732 * @param array $owner Contact data of the poster
1733 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1735 * @return object Entry element
1737 private static function followEntry($doc, $item, $owner, $toplevel)
1739 $item["id"] = $item["parent"] = 0;
1740 $item["created"] = $item["edited"] = date("c");
1741 $item["private"] = true;
1743 $contact = Probe::uri($item['follow']);
1745 if ($contact['alias'] == '') {
1746 $contact['alias'] = $contact["url"];
1748 $item['follow'] = $contact['alias'];
1752 "SELECT `id` FROM `contact` WHERE `uid` = %d AND `nurl` = '%s'",
1753 intval($owner['uid']),
1754 dbesc(normalise_link($contact["url"]))
1757 if (DBM::is_result($r)) {
1758 $connect_id = $r[0]['id'];
1763 if ($item['verb'] == ACTIVITY_FOLLOW) {
1764 $message = L10n::t('%s is now following %s.');
1765 $title = L10n::t('following');
1766 $action = "subscription";
1768 $message = L10n::t('%s stopped following %s.');
1769 $title = L10n::t('stopped following');
1770 $action = "unfollow";
1773 $item["uri"] = $item['parent-uri'] = $item['thr-parent']
1774 = 'tag:'.get_app()->get_hostname().
1775 ','.date('Y-m-d').':'.$action.':'.$owner['uid'].
1776 ':person:'.$connect_id.':'.$item['created'];
1778 $item["body"] = sprintf($message, $owner["nick"], $contact["nick"]);
1780 self::entryHeader($doc, $entry, $owner, $toplevel);
1782 self::entryContent($doc, $entry, $item, $owner, $title);
1784 $object = self::addPersonObject($doc, $owner, $contact);
1785 $entry->appendChild($object);
1787 self::entryFooter($doc, $entry, $item, $owner);
1793 * @brief Adds a regular entry element
1795 * @param object $doc XML document
1796 * @param array $item Data of the item that is to be posted
1797 * @param array $owner Contact data of the poster
1798 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1800 * @return object Entry element
1802 private static function noteEntry($doc, $item, $owner, $toplevel)
1804 if (($item["id"] != $item["parent"]) && (normalise_link($item["author-link"]) != normalise_link($owner["url"]))) {
1805 logger("OStatus entry is from author ".$owner["url"]." - not from ".$item["author-link"].". Quitting.", LOGGER_DEBUG);
1808 $title = self::entryHeader($doc, $entry, $owner, $toplevel);
1810 XML::addElement($doc, $entry, "activity:object-type", ACTIVITY_OBJ_NOTE);
1812 self::entryContent($doc, $entry, $item, $owner, $title);
1814 self::entryFooter($doc, $entry, $item, $owner);
1820 * @brief Adds a header element to the XML document
1822 * @param object $doc XML document
1823 * @param object $entry The entry element where the elements are added
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 string The title for the element
1829 private static function entryHeader($doc, &$entry, $owner, $toplevel)
1831 /// @todo Check if this title stuff is really needed (I guess not)
1833 $entry = $doc->createElement("entry");
1834 $title = sprintf("New note by %s", $owner["nick"]);
1836 $entry = $doc->createElementNS(NAMESPACE_ATOM1, "entry");
1838 $entry->setAttribute("xmlns:thr", NAMESPACE_THREAD);
1839 $entry->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
1840 $entry->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
1841 $entry->setAttribute("xmlns:media", NAMESPACE_MEDIA);
1842 $entry->setAttribute("xmlns:poco", NAMESPACE_POCO);
1843 $entry->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
1844 $entry->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
1845 $entry->setAttribute("xmlns:mastodon", NAMESPACE_MASTODON);
1847 $author = self::addAuthor($doc, $owner);
1848 $entry->appendChild($author);
1850 $title = sprintf("New comment by %s", $owner["nick"]);
1856 * @brief Adds elements to the XML document
1858 * @param object $doc XML document
1859 * @param object $entry Entry element where the content is added
1860 * @param array $item Data of the item that is to be posted
1861 * @param array $owner Contact data of the poster
1862 * @param string $title Title for the post
1863 * @param string $verb The activity verb
1864 * @param bool $complete Add the "status_net" element?
1867 private static function entryContent($doc, $entry, $item, $owner, $title, $verb = "", $complete = true)
1870 $verb = self::constructVerb($item);
1873 XML::addElement($doc, $entry, "id", $item["uri"]);
1874 XML::addElement($doc, $entry, "title", $title);
1876 $body = self::formatPicturePost($item['body']);
1878 if ($item['title'] != "") {
1879 $body = "[b]".$item['title']."[/b]\n\n".$body;
1882 $body = BBCode::convert($body, false, 7);
1884 XML::addElement($doc, $entry, "content", $body, ["type" => "html"]);
1886 XML::addElement($doc, $entry, "link", "", ["rel" => "alternate", "type" => "text/html",
1887 "href" => System::baseUrl()."/display/".$item["guid"]]
1890 if ($complete && ($item["id"] > 0)) {
1891 XML::addElement($doc, $entry, "status_net", "", ["notice_id" => $item["id"]]);
1894 XML::addElement($doc, $entry, "activity:verb", $verb);
1896 XML::addElement($doc, $entry, "published", DateTimeFormat::utc($item["created"]."+00:00", DateTimeFormat::ATOM));
1897 XML::addElement($doc, $entry, "updated", DateTimeFormat::utc($item["edited"]."+00:00", DateTimeFormat::ATOM));
1901 * @brief Adds the elements at the foot of an entry to the XML document
1903 * @param object $doc XML document
1904 * @param object $entry The entry element where the elements are added
1905 * @param array $item Data of the item that is to be posted
1906 * @param array $owner Contact data of the poster
1907 * @param bool $complete default true
1910 private static function entryFooter($doc, $entry, $item, $owner, $complete = true)
1914 if (($item['parent'] != $item['id']) || ($item['parent-uri'] !== $item['uri']) || (($item['thr-parent'] !== '') && ($item['thr-parent'] !== $item['uri']))) {
1915 $parent = q("SELECT `guid`, `author-link`, `owner-link` FROM `item` WHERE `id` = %d", intval($item["parent"]));
1916 $parent_item = (($item['thr-parent']) ? $item['thr-parent'] : $item['parent-uri']);
1919 "SELECT `guid`, `author-link`, `owner-link`, `plink` FROM `item` WHERE `uid` = %d AND `uri` = '%s'",
1920 intval($owner["uid"]),
1924 $mentioned[$thrparent[0]["author-link"]] = $thrparent[0]["author-link"];
1925 $mentioned[$thrparent[0]["owner-link"]] = $thrparent[0]["owner-link"];
1926 $parent_plink = $thrparent[0]["plink"];
1928 $mentioned[$parent[0]["author-link"]] = $parent[0]["author-link"];
1929 $mentioned[$parent[0]["owner-link"]] = $parent[0]["owner-link"];
1930 $parent_plink = System::baseUrl()."/display/".$parent[0]["guid"];
1934 "ref" => $parent_item,
1935 "href" => $parent_plink];
1936 XML::addElement($doc, $entry, "thr:in-reply-to", "", $attributes);
1940 "href" => $parent_plink];
1941 XML::addElement($doc, $entry, "link", "", $attributes);
1944 if (intval($item["parent"]) > 0) {
1945 $conversation_href = System::baseUrl()."/display/".$owner["nick"]."/".$item["parent"];
1946 $conversation_uri = $conversation_href;
1948 if (isset($parent_item)) {
1949 $r = dba::fetch_first("SELECT `conversation-uri`, `conversation-href` FROM `conversation` WHERE `item-uri` = ?", $parent_item);
1950 if (DBM::is_result($r)) {
1951 if ($r['conversation-uri'] != '') {
1952 $conversation_uri = $r['conversation-uri'];
1954 if ($r['conversation-href'] != '') {
1955 $conversation_href = $r['conversation-href'];
1960 XML::addElement($doc, $entry, "link", "", ["rel" => "ostatus:conversation", "href" => $conversation_href]);
1963 "href" => $conversation_href,
1964 "local_id" => $item["parent"],
1965 "ref" => $conversation_uri];
1967 XML::addElement($doc, $entry, "ostatus:conversation", $conversation_uri, $attributes);
1970 $tags = item::getFeedTags($item);
1973 foreach ($tags as $t) {
1975 $mentioned[$t[1]] = $t[1];
1980 // Make sure that mentions are accepted (GNU Social has problems with mixing HTTP and HTTPS)
1982 foreach ($mentioned as $mention) {
1983 $newmentions[str_replace("http://", "https://", $mention)] = str_replace("http://", "https://", $mention);
1984 $newmentions[str_replace("https://", "http://", $mention)] = str_replace("https://", "http://", $mention);
1986 $mentioned = $newmentions;
1988 foreach ($mentioned as $mention) {
1990 "SELECT `forum`, `prv` FROM `contact` WHERE `uid` = %d AND `nurl` = '%s'",
1991 intval($owner["uid"]),
1992 dbesc(normalise_link($mention))
1994 if ($r[0]["forum"] || $r[0]["prv"]) {
1995 XML::addElement($doc, $entry, "link", "",
1997 "rel" => "mentioned",
1998 "ostatus:object-type" => ACTIVITY_OBJ_GROUP,
2002 XML::addElement($doc, $entry, "link", "",
2004 "rel" => "mentioned",
2005 "ostatus:object-type" => ACTIVITY_OBJ_PERSON,
2011 if (!$item["private"]) {
2012 XML::addElement($doc, $entry, "link", "", ["rel" => "ostatus:attention",
2013 "href" => "http://activityschema.org/collection/public"]);
2014 XML::addElement($doc, $entry, "link", "", ["rel" => "mentioned",
2015 "ostatus:object-type" => "http://activitystrea.ms/schema/1.0/collection",
2016 "href" => "http://activityschema.org/collection/public"]);
2017 XML::addElement($doc, $entry, "mastodon:scope", "public");
2021 foreach ($tags as $t) {
2023 XML::addElement($doc, $entry, "category", "", ["term" => $t[2]]);
2028 self::getAttachment($doc, $entry, $item);
2030 if ($complete && ($item["id"] > 0)) {
2031 $app = $item["app"];
2036 $attributes = ["local_id" => $item["id"], "source" => $app];
2038 if (isset($parent["id"])) {
2039 $attributes["repeat_of"] = $parent["id"];
2042 if ($item["coord"] != "") {
2043 XML::addElement($doc, $entry, "georss:point", $item["coord"]);
2046 XML::addElement($doc, $entry, "statusnet:notice_info", "", $attributes);
2051 * Creates the XML feed for a given nickname
2053 * Supported filters:
2054 * - activity (default): all the public posts
2055 * - posts: all the public top-level posts
2056 * - comments: all the public replies
2058 * Updates the provided last_update parameter if the result comes from the
2059 * cache or it is empty
2061 * @brief Creates the XML feed for a given nickname
2063 * @param string $owner_nick Nickname of the feed owner
2064 * @param string $last_update Date of the last update
2065 * @param integer $max_items Number of maximum items to fetch
2066 * @param string $filter Feed items filter (activity, posts or comments)
2067 * @param boolean $nocache Wether to bypass caching
2069 * @return string XML feed
2071 public static function feed($owner_nick, &$last_update, $max_items = 300, $filter = 'activity', $nocache = false)
2073 $stamp = microtime(true);
2075 $cachekey = "ostatus:feed:" . $owner_nick . ":" . $filter . ":" . $last_update;
2077 $previous_created = $last_update;
2079 $result = Cache::get($cachekey);
2080 if (!$nocache && !is_null($result)) {
2081 logger('Feed duration: ' . number_format(microtime(true) - $stamp, 3) . ' - ' . $owner_nick . ' - ' . $filter . ' - ' . $previous_created . ' (cached)', LOGGER_DEBUG);
2082 $last_update = $result['last_update'];
2083 return $result['feed'];
2086 $owner = dba::fetch_first(
2087 "SELECT `contact`.*, `user`.`nickname`, `user`.`timezone`, `user`.`page-flags`
2088 FROM `contact` INNER JOIN `user` ON `user`.`uid` = `contact`.`uid`
2089 WHERE `contact`.`self` AND `user`.`nickname` = ? LIMIT 1",
2092 if (!DBM::is_result($owner)) {
2096 if (!strlen($last_update)) {
2097 $last_update = 'now -30 days';
2100 $check_date = DateTimeFormat::utc($last_update);
2101 $authorid = Contact::getIdForURL($owner["url"], 0);
2104 if ($filter === 'posts') {
2105 $sql_extra .= ' AND `item`.`id` = `item`.`parent` ';
2108 if ($filter === 'comments') {
2109 $sql_extra .= sprintf(" AND `item`.`object-type` = '%s' ", dbesc(ACTIVITY_OBJ_COMMENT));
2113 "SELECT `item`.*, `item`.`id` AS `item_id` FROM `item` USE INDEX (`uid_contactid_created`)
2114 STRAIGHT_JOIN `thread` ON `thread`.`iid` = `item`.`parent`
2115 WHERE `item`.`uid` = %d
2116 AND `item`.`contact-id` = %d
2117 AND `item`.`author-id` = %d
2118 AND `item`.`created` > '%s'
2119 AND NOT `item`.`deleted`
2120 AND NOT `item`.`private`
2121 AND `thread`.`network` IN ('%s', '%s')
2123 ORDER BY `item`.`created` DESC LIMIT %d",
2124 intval($owner["uid"]),
2125 intval($owner["id"]),
2128 dbesc(NETWORK_OSTATUS),
2129 dbesc(NETWORK_DFRN),
2133 $doc = new DOMDocument('1.0', 'utf-8');
2134 $doc->formatOutput = true;
2136 $root = self::addHeader($doc, $owner, $filter);
2138 foreach ($items as $item) {
2139 if (Config::get('system', 'ostatus_debug')) {
2140 $item['body'] .= '🍼';
2142 $entry = self::entry($doc, $item, $owner);
2143 $root->appendChild($entry);
2145 if ($last_update < $item['created']) {
2146 $last_update = $item['created'];
2150 $feeddata = trim($doc->saveXML());
2152 $msg = ['feed' => $feeddata, 'last_update' => $last_update];
2153 Cache::set($cachekey, $msg, CACHE_QUARTER_HOUR);
2155 logger('Feed duration: ' . number_format(microtime(true) - $stamp, 3) . ' - ' . $owner_nick . ' - ' . $filter . ' - ' . $previous_created, LOGGER_DEBUG);
2161 * @brief Creates the XML for a salmon message
2163 * @param array $item Data of the item that is to be posted
2164 * @param array $owner Contact data of the poster
2166 * @return string XML for the salmon
2168 public static function salmon($item, $owner)
2170 $doc = new DOMDocument('1.0', 'utf-8');
2171 $doc->formatOutput = true;
2173 if (Config::get('system', 'ostatus_debug')) {
2174 $item['body'] .= '🐟';
2177 $entry = self::entry($doc, $item, $owner, true);
2179 $doc->appendChild($entry);
2181 return trim($doc->saveXML());