3 * @file src/Protocol/OStatus.php
5 namespace Friendica\Protocol;
8 use Friendica\Content\Text\BBCode;
9 use Friendica\Core\Cache;
10 use Friendica\Core\Config;
11 use Friendica\Core\L10n;
12 use Friendica\Core\System;
13 use Friendica\Database\DBM;
14 use Friendica\Model\Contact;
15 use Friendica\Model\GContact;
16 use Friendica\Model\Conversation;
17 use Friendica\Network\Probe;
18 use Friendica\Object\Image;
19 use Friendica\Util\Lock;
20 use Friendica\Util\Network;
21 use Friendica\Util\XML;
26 require_once 'include/dba.php';
27 require_once 'include/threads.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"];
76 if ($aliaslink != '') {
77 $condition = ["`uid` = ? AND `alias` = ? AND `network` != ?",
78 $importer["uid"], $aliaslink, NETWORK_STATUSNET];
79 $r = dba::selectFirst('contact', [], $condition);
81 if (DBM::is_result($r)) {
87 $author["contact-id"] = $r["id"];
91 if (!$found && ($author["author-link"] != "")) {
92 if ($aliaslink == "") {
93 $aliaslink = $author["author-link"];
96 $condition = ["`uid` = ? AND `nurl` IN (?, ?) AND `network` != ?", $importer["uid"],
97 normalise_link($author["author-link"]), normalise_link($aliaslink), NETWORK_STATUSNET];
98 $r = dba::selectFirst('contact', [], $condition);
100 if (DBM::is_result($r)) {
106 $author["contact-id"] = $r["id"];
110 if (!$found && ($addr != "")) {
111 $condition = ["`uid` = ? AND `addr` = ? AND `network` != ?",
112 $importer["uid"], $addr, NETWORK_STATUSNET];
113 $r = dba::selectFirst('contact', [], $condition);
115 if (DBM::is_result($r)) {
121 $author["contact-id"] = $r["id"];
126 $avatars = $xpath->query("atom:author/atom:link[@rel='avatar']", $context);
127 foreach ($avatars as $avatar) {
130 foreach ($avatar->attributes as $attributes) {
131 if ($attributes->name == "href") {
132 $href = $attributes->textContent;
134 if ($attributes->name == "width") {
135 $width = $attributes->textContent;
139 $avatarlist[$width] = $href;
142 if (count($avatarlist) > 0) {
144 $author["author-avatar"] = Probe::fixAvatar(current($avatarlist), $author["author-link"]);
147 $displayname = $xpath->evaluate('atom:author/poco:displayName/text()', $context)->item(0)->nodeValue;
148 if ($displayname != "") {
149 $author["author-name"] = $displayname;
152 $author["owner-name"] = $author["author-name"];
153 $author["owner-link"] = $author["author-link"];
154 $author["owner-avatar"] = $author["author-avatar"];
156 // Only update the contacts if it is an OStatus contact
157 if ($r && ($r['id'] > 0) && !$onlyfetch && ($contact["network"] == NETWORK_OSTATUS)) {
159 // Update contact data
161 unset($current['name-date']);
163 // This query doesn't seem to work
164 // $value = $xpath->query("atom:link[@rel='salmon']", $context)->item(0)->nodeValue;
166 // $contact["notify"] = $value;
168 // This query doesn't seem to work as well - I hate these queries
169 // $value = $xpath->query("atom:link[@rel='self' and @type='application/atom+xml']", $context)->item(0)->nodeValue;
171 // $contact["poll"] = $value;
173 $contact['url'] = $author["author-link"];
174 $contact['nurl'] = normalise_link($contact['url']);
176 $value = $xpath->evaluate('atom:author/atom:uri/text()', $context)->item(0)->nodeValue;
178 $contact["alias"] = $value;
181 $value = $xpath->evaluate('atom:author/poco:displayName/text()', $context)->item(0)->nodeValue;
183 $contact["name"] = $value;
186 $value = $xpath->evaluate('atom:author/poco:preferredUsername/text()', $context)->item(0)->nodeValue;
188 $contact["nick"] = $value;
191 $value = $xpath->evaluate('atom:author/poco:note/text()', $context)->item(0)->nodeValue;
193 $contact["about"] = html2bbcode($value);
196 $value = $xpath->evaluate('atom:author/poco:address/poco:formatted/text()', $context)->item(0)->nodeValue;
198 $contact["location"] = $value;
201 $contact['name-date'] = datetime_convert();
203 dba::update('contact', $contact, ['id' => $contact["id"]], $current);
205 if (!empty($author["author-avatar"]) && ($author["author-avatar"] != $current['avatar'])) {
206 logger("Update profile picture for contact ".$contact["id"], LOGGER_DEBUG);
207 Contact::updateAvatar($author["author-avatar"], $importer["uid"], $contact["id"]);
210 // Ensure that we are having this contact (with uid=0)
211 $cid = Contact::getIdForURL($aliaslink, 0);
214 $fields = ['url', 'nurl', 'name', 'nick', 'alias', 'about', 'location'];
215 $old_contact = dba::selectFirst('contact', $fields, ['id' => $cid]);
217 // Update it with the current values
218 $fields = ['url' => $author["author-link"], 'name' => $contact["name"],
219 'nurl' => normalise_link($author["author-link"]),
220 'nick' => $contact["nick"], 'alias' => $contact["alias"],
221 'about' => $contact["about"], 'location' => $contact["location"],
222 'success_update' => datetime_convert(), 'last-update' => datetime_convert()];
224 dba::update('contact', $fields, ['id' => $cid], $old_contact);
227 Contact::updateAvatar($author["author-avatar"], 0, $cid);
230 $contact["generation"] = 2;
231 $contact["hide"] = false; // OStatus contacts are never hidden
232 $contact["photo"] = $author["author-avatar"];
233 $gcid = GContact::update($contact);
235 GContact::link($gcid, $contact["uid"], $contact["id"]);
242 * @brief Fetches author data from a given XML string
244 * @param string $xml The XML
245 * @param array $importer user record of the importing user
247 * @return array Array of author related entries for the item
249 public static function salmonAuthor($xml, $importer)
255 $doc = new DOMDocument();
256 @$doc->loadXML($xml);
258 $xpath = new DOMXPath($doc);
259 $xpath->registerNamespace('atom', NAMESPACE_ATOM1);
260 $xpath->registerNamespace('thr', NAMESPACE_THREAD);
261 $xpath->registerNamespace('georss', NAMESPACE_GEORSS);
262 $xpath->registerNamespace('activity', NAMESPACE_ACTIVITY);
263 $xpath->registerNamespace('media', NAMESPACE_MEDIA);
264 $xpath->registerNamespace('poco', NAMESPACE_POCO);
265 $xpath->registerNamespace('ostatus', NAMESPACE_OSTATUS);
266 $xpath->registerNamespace('statusnet', NAMESPACE_STATUSNET);
268 $entries = $xpath->query('/atom:entry');
270 foreach ($entries as $entry) {
272 $author = self::fetchAuthor($xpath, $entry, $importer, $contact, true);
278 * @brief Read attributes from element
280 * @param object $element Element object
282 * @return array attributes
284 private static function readAttributes($element)
288 foreach ($element->attributes as $attributes) {
289 $attribute[$attributes->name] = $attributes->textContent;
296 * @brief Imports an XML string containing OStatus elements
298 * @param string $xml The XML
299 * @param array $importer user record of the importing user
300 * @param array $contact contact
301 * @param string $hub Called by reference, returns the fetched hub data
304 public static function import($xml, $importer, &$contact, &$hub)
306 self::process($xml, $importer, $contact, $hub);
310 * @brief Internal feed processing
312 * @param string $xml The XML
313 * @param array $importer user record of the importing user
314 * @param array $contact contact
315 * @param string $hub Called by reference, returns the fetched hub data
316 * @param boolean $stored Is the post fresh imported or from the database?
317 * @param boolean $initialize Is it the leading post so that data has to be initialized?
319 * @return boolean Could the XML be processed?
321 private static function process($xml, $importer, &$contact, &$hub, $stored = false, $initialize = true)
324 self::$itemlist = [];
325 self::$conv_list = [];
328 logger("Import OStatus message", LOGGER_DEBUG);
333 $doc = new DOMDocument();
334 @$doc->loadXML($xml);
336 $xpath = new DOMXPath($doc);
337 $xpath->registerNamespace('atom', NAMESPACE_ATOM1);
338 $xpath->registerNamespace('thr', NAMESPACE_THREAD);
339 $xpath->registerNamespace('georss', NAMESPACE_GEORSS);
340 $xpath->registerNamespace('activity', NAMESPACE_ACTIVITY);
341 $xpath->registerNamespace('media', NAMESPACE_MEDIA);
342 $xpath->registerNamespace('poco', NAMESPACE_POCO);
343 $xpath->registerNamespace('ostatus', NAMESPACE_OSTATUS);
344 $xpath->registerNamespace('statusnet', NAMESPACE_STATUSNET);
347 $hub_attributes = $xpath->query("/atom:feed/atom:link[@rel='hub']")->item(0)->attributes;
348 if (is_object($hub_attributes)) {
349 foreach ($hub_attributes as $hub_attribute) {
350 if ($hub_attribute->name == "href") {
351 $hub = $hub_attribute->textContent;
352 logger("Found hub ".$hub, LOGGER_DEBUG);
358 $header["uid"] = $importer["uid"];
359 $header["network"] = NETWORK_OSTATUS;
360 $header["type"] = "remote";
362 $header["origin"] = 0;
363 $header["gravity"] = GRAVITY_PARENT;
365 $first_child = $doc->firstChild->tagName;
367 if ($first_child == "feed") {
368 $entries = $xpath->query('/atom:feed/atom:entry');
370 $entries = $xpath->query('/atom:entry');
373 if ($entries->length == 1) {
374 // We reformat the XML to make it better readable
375 $doc2 = new DOMDocument();
376 $doc2->loadXML($xml);
377 $doc2->preserveWhiteSpace = false;
378 $doc2->formatOutput = true;
379 $xml2 = $doc2->saveXML();
381 $header["protocol"] = PROTOCOL_OSTATUS_SALMON;
382 $header["source"] = $xml2;
383 } elseif (!$initialize) {
387 // Fetch the first author
388 $authordata = $xpath->query('//author')->item(0);
389 $author = self::fetchAuthor($xpath, $authordata, $importer, $contact, $stored);
391 $entry = $xpath->query('/atom:entry');
393 // Reverse the order of the entries
396 foreach ($entries as $entry) {
397 $entrylist[] = $entry;
400 foreach (array_reverse($entrylist) as $entry) {
402 $authorelement = $xpath->query('/atom:entry/atom:author', $entry);
404 if ($authorelement->length == 0) {
405 $authorelement = $xpath->query('atom:author', $entry);
408 if ($authorelement->length > 0) {
409 $author = self::fetchAuthor($xpath, $entry, $importer, $contact, $stored);
412 $value = $xpath->evaluate('atom:author/poco:preferredUsername/text()', $entry)->item(0)->nodeValue;
416 $nickname = $author["author-name"];
419 $item = array_merge($header, $author);
421 $item["uri"] = $xpath->query('atom:id/text()', $entry)->item(0)->nodeValue;
423 $item["verb"] = $xpath->query('activity:verb/text()', $entry)->item(0)->nodeValue;
426 if (in_array($item["verb"], ['qvitter-delete-notice', ACTIVITY_DELETE, 'delete'])) {
427 self::deleteNotice($item);
431 if (in_array($item["verb"], [NAMESPACE_OSTATUS."/unfavorite", ACTIVITY_UNFAVORITE])) {
432 // Ignore "Unfavorite" message
433 logger("Ignore unfavorite message ".print_r($item, true), LOGGER_DEBUG);
437 // Deletions come with the same uri, so we check for duplicates after processing deletions
438 if (dba::exists('item', ['uid' => $importer["uid"], 'uri' => $item["uri"]])) {
439 logger('Post with URI '.$item["uri"].' already existed for user '.$importer["uid"].'.', LOGGER_DEBUG);
442 logger('Processing post with URI '.$item["uri"].' for user '.$importer["uid"].'.', LOGGER_DEBUG);
445 if ($item["verb"] == ACTIVITY_JOIN) {
446 // ignore "Join" messages
447 logger("Ignore join message ".print_r($item, true), LOGGER_DEBUG);
451 if ($item["verb"] == "http://mastodon.social/schema/1.0/block") {
452 // ignore mastodon "block" messages
453 logger("Ignore block message ".print_r($item, true), LOGGER_DEBUG);
457 if ($item["verb"] == ACTIVITY_FOLLOW) {
458 new_follower($importer, $contact, $item, $nickname);
462 if ($item["verb"] == NAMESPACE_OSTATUS."/unfollow") {
463 lose_follower($importer, $contact, $item, $dummy);
467 if ($item["verb"] == ACTIVITY_FAVORITE) {
468 $orig_uri = $xpath->query("activity:object/atom:id", $entry)->item(0)->nodeValue;
469 logger("Favorite ".$orig_uri." ".print_r($item, true));
471 $item["verb"] = ACTIVITY_LIKE;
472 $item["parent-uri"] = $orig_uri;
473 $item["gravity"] = GRAVITY_LIKE;
476 // http://activitystrea.ms/schema/1.0/rsvp-yes
477 if (!in_array($item["verb"], [ACTIVITY_POST, ACTIVITY_LIKE, ACTIVITY_SHARE])) {
478 logger("Unhandled verb ".$item["verb"]." ".print_r($item, true), LOGGER_DEBUG);
481 self::processPost($xpath, $entry, $item, $importer);
483 if ($initialize && (count(self::$itemlist) > 0)) {
484 if (self::$itemlist[0]['uri'] == self::$itemlist[0]['parent-uri']) {
485 // We will import it everytime, when it is started by our contacts
486 $valid = !empty(self::$itemlist[0]['contact-id']);
488 // If not, then it depends on this setting
489 $valid = !Config::get('system', 'ostatus_full_threads');
492 // Never post a thread when the only interaction by our contact was a like
494 $verbs = [ACTIVITY_POST, ACTIVITY_SHARE];
495 foreach (self::$itemlist as $item) {
496 if (!empty($item['contact-id']) && in_array($item['verb'], $verbs)) {
502 // But we will only import complete threads
503 $valid = dba::exists('item', ['uid' => $importer["uid"], 'uri' => self::$itemlist[0]['parent-uri']]);
507 $default_contact = 0;
508 $key = count(self::$itemlist);
509 for ($key = count(self::$itemlist) - 1; $key >= 0; $key--) {
510 if (empty(self::$itemlist[$key]['contact-id'])) {
511 self::$itemlist[$key]['contact-id'] = $default_contact;
513 $default_contact = $item['contact-id'];
516 foreach (self::$itemlist as $item) {
517 $found = dba::exists('item', ['uid' => $importer["uid"], 'uri' => $item["uri"]]);
519 logger("Item with uri ".$item["uri"]." for user ".$importer["uid"]." already exists.", LOGGER_DEBUG);
520 } elseif ($item['contact-id'] < 0) {
521 logger("Item with uri ".$item["uri"]." is from a blocked contact.", LOGGER_DEBUG);
523 // We are having duplicated entries. Hopefully this solves it.
524 if (Lock::set('ostatus_process_item_store')) {
525 $ret = item_store($item);
526 Lock::remove('ostatus_process_item_store');
527 logger("Item with uri ".$item["uri"]." for user ".$importer["uid"].' stored. Return value: '.$ret);
529 $ret = item_store($item);
530 logger("We couldn't lock - but tried to store the item anyway. Return value is ".$ret);
535 self::$itemlist = [];
537 logger('Processing done for post with URI '.$item["uri"].' for user '.$importer["uid"].'.', LOGGER_DEBUG);
543 * @param object $item item
546 private static function deleteNotice($item)
548 $condition = ['uid' => $item['uid'], 'author-link' => $item['author-link'], 'uri' => $item['uri']];
549 $deleted = dba::selectFirst('item', ['id', 'parent-uri'], $condition);
550 if (!DBM::is_result($deleted)) {
551 logger('Item from '.$item['author-link'].' with uri '.$item['uri'].' for user '.$item['uid']." wasn't found. We don't delete it. ");
555 // Currently we don't have a central deletion function that we could use in this case
556 // The function "item_drop" doesn't work for that case
559 ['deleted' => true, 'title' => '', 'body' => '',
560 'edited' => datetime_convert(), 'changed' => datetime_convert()],
561 ['id' => $deleted["id"]]
564 delete_thread($deleted["id"], $deleted["parent-uri"]);
566 logger('Deleted item with uri '.$item['uri'].' for user '.$item['uid']);
570 * @brief Processes the XML for a post
572 * @param object $xpath The xpath object
573 * @param object $entry The xml entry that is processed
574 * @param array $item The item array
575 * @param array $importer user record of the importing user
578 private static function processPost($xpath, $entry, &$item, $importer)
580 $item["body"] = html2bbcode($xpath->query('atom:content/text()', $entry)->item(0)->nodeValue);
581 $item["object-type"] = $xpath->query('activity:object-type/text()', $entry)->item(0)->nodeValue;
582 if (($item["object-type"] == ACTIVITY_OBJ_BOOKMARK) || ($item["object-type"] == ACTIVITY_OBJ_EVENT)) {
583 $item["title"] = $xpath->query('atom:title/text()', $entry)->item(0)->nodeValue;
584 $item["body"] = $xpath->query('atom:summary/text()', $entry)->item(0)->nodeValue;
585 } elseif ($item["object-type"] == ACTIVITY_OBJ_QUESTION) {
586 $item["title"] = $xpath->query('atom:title/text()', $entry)->item(0)->nodeValue;
589 $item["created"] = $xpath->query('atom:published/text()', $entry)->item(0)->nodeValue;
590 $item["edited"] = $xpath->query('atom:updated/text()', $entry)->item(0)->nodeValue;
591 $conversation = $xpath->query('ostatus:conversation/text()', $entry)->item(0)->nodeValue;
592 $item['conversation-uri'] = $conversation;
594 $conv = $xpath->query('ostatus:conversation', $entry);
595 if (is_object($conv->item(0))) {
596 foreach ($conv->item(0)->attributes as $attributes) {
597 if ($attributes->name == "ref") {
598 $item['conversation-uri'] = $attributes->textContent;
600 if ($attributes->name == "href") {
601 $item['conversation-href'] = $attributes->textContent;
608 $inreplyto = $xpath->query('thr:in-reply-to', $entry);
609 if (is_object($inreplyto->item(0))) {
610 foreach ($inreplyto->item(0)->attributes as $attributes) {
611 if ($attributes->name == "ref") {
612 $item["parent-uri"] = $attributes->textContent;
614 if ($attributes->name == "href") {
615 $related = $attributes->textContent;
620 $georsspoint = $xpath->query('georss:point', $entry);
621 if (!empty($georsspoint) && ($georsspoint->length > 0)) {
622 $item["coord"] = $georsspoint->item(0)->nodeValue;
625 $categories = $xpath->query('atom:category', $entry);
627 foreach ($categories as $category) {
628 foreach ($category->attributes as $attributes) {
629 if ($attributes->name == "term") {
630 $term = $attributes->textContent;
631 if (strlen($item["tag"])) {
634 $item["tag"] .= "#[url=".System::baseUrl()."/search?tag=".$term."]".$term."[/url]";
643 $links = $xpath->query('atom:link', $entry);
645 $link_data = self::processLinks($links, $item);
646 $self = $link_data['self'];
647 $add_body = $link_data['add_body'];
652 $notice_info = $xpath->query('statusnet:notice_info', $entry);
653 if ($notice_info && ($notice_info->length > 0)) {
654 foreach ($notice_info->item(0)->attributes as $attributes) {
655 if ($attributes->name == "source") {
656 $item["app"] = strip_tags($attributes->textContent);
658 if ($attributes->name == "repeat_of") {
659 $repeat_of = $attributes->textContent;
663 // Is it a repeated post?
664 if (($repeat_of != "") || ($item["verb"] == ACTIVITY_SHARE)) {
665 $link_data = self::processRepeatedItem($xpath, $entry, $item, $importer);
666 if (!empty($link_data['add_body'])) {
667 $add_body .= $link_data['add_body'];
671 $item["body"] .= $add_body;
673 // Only add additional data when there is no picture in the post
674 if (!strstr($item["body"], '[/img]')) {
675 $item["body"] = add_page_info_to_body($item["body"]);
678 // Mastodon Content Warning
679 if (($item["verb"] == ACTIVITY_POST) && $xpath->evaluate('boolean(atom:summary)', $entry)) {
680 $clear_text = $xpath->query('atom:summary/text()', $entry)->item(0)->nodeValue;
682 $item["body"] = html2bbcode($clear_text) . '[spoiler]' . $item["body"] . '[/spoiler]';
685 if (($self != '') && empty($item['protocol'])) {
686 self::fetchSelf($self, $item);
689 if (!empty($item["conversation-href"])) {
690 self::fetchConversation($item['conversation-href'], $item['conversation-uri']);
693 if (isset($item["parent-uri"]) && ($related != '')) {
694 if (!dba::exists('item', ['uid' => $importer["uid"], 'uri' => $item['parent-uri']])) {
695 self::fetchRelated($related, $item["parent-uri"], $importer);
697 logger('Reply with URI '.$item["uri"].' already existed for user '.$importer["uid"].'.', LOGGER_DEBUG);
700 $item["type"] = 'remote-comment';
701 $item["gravity"] = GRAVITY_COMMENT;
703 $item["parent-uri"] = $item["uri"];
706 if (($item['author-link'] != '') && !empty($item['protocol'])) {
707 $item = Conversation::insert($item);
710 self::$itemlist[] = $item;
714 * @brief Fetch the conversation for posts
716 * @param string $conversation The link to the conversation
717 * @param string $conversation_uri The conversation in "uri" format
720 private static function fetchConversation($conversation, $conversation_uri)
722 // Ensure that we only store a conversation once in a process
723 if (isset(self::$conv_list[$conversation])) {
727 self::$conv_list[$conversation] = true;
729 $conversation_data = Network::curl($conversation, false, $redirects, ['accept_content' => 'application/atom+xml, text/html']);
731 if (!$conversation_data['success']) {
737 if (stristr($conversation_data['header'], 'Content-Type: application/atom+xml')) {
738 $xml = $conversation_data['body'];
742 $doc = new DOMDocument();
743 if (!@$doc->loadHTML($conversation_data['body'])) {
746 $xpath = new DOMXPath($doc);
748 $links = $xpath->query('//link');
750 foreach ($links as $link) {
751 $attribute = self::readAttributes($link);
752 if (($attribute['rel'] == 'alternate') && ($attribute['type'] == 'application/atom+xml')) {
753 $file = $attribute['href'];
757 $conversation_atom = Network::curl($attribute['href']);
759 if ($conversation_atom['success']) {
760 $xml = $conversation_atom['body'];
770 self::storeConversation($xml, $conversation, $conversation_uri);
774 * @brief Store a feed in several conversation entries
776 * @param string $xml The feed
777 * @param string $conversation conversation
778 * @param string $conversation_uri conversation uri
781 private static function storeConversation($xml, $conversation = '', $conversation_uri = '')
783 $doc = new DOMDocument();
784 @$doc->loadXML($xml);
786 $xpath = new DOMXPath($doc);
787 $xpath->registerNamespace('atom', NAMESPACE_ATOM1);
788 $xpath->registerNamespace('thr', NAMESPACE_THREAD);
789 $xpath->registerNamespace('ostatus', NAMESPACE_OSTATUS);
791 $entries = $xpath->query('/atom:feed/atom:entry');
793 // Now store the entries
794 foreach ($entries as $entry) {
795 $doc2 = new DOMDocument();
796 $doc2->preserveWhiteSpace = false;
797 $doc2->formatOutput = true;
801 $conv_data['protocol'] = PROTOCOL_SPLITTED_CONV;
802 $conv_data['network'] = NETWORK_OSTATUS;
803 $conv_data['uri'] = $xpath->query('atom:id/text()', $entry)->item(0)->nodeValue;
805 $inreplyto = $xpath->query('thr:in-reply-to', $entry);
806 if (is_object($inreplyto->item(0))) {
807 foreach ($inreplyto->item(0)->attributes as $attributes) {
808 if ($attributes->name == "ref") {
809 $conv_data['reply-to-uri'] = $attributes->textContent;
814 $conv = $xpath->query('ostatus:conversation/text()', $entry)->item(0)->nodeValue;
815 $conv_data['conversation-uri'] = $conv;
817 $conv = $xpath->query('ostatus:conversation', $entry);
818 if (is_object($conv->item(0))) {
819 foreach ($conv->item(0)->attributes as $attributes) {
820 if ($attributes->name == "ref") {
821 $conv_data['conversation-uri'] = $attributes->textContent;
823 if ($attributes->name == "href") {
824 $conv_data['conversation-href'] = $attributes->textContent;
829 if ($conversation != '') {
830 $conv_data['conversation-uri'] = $conversation;
833 if ($conversation_uri != '') {
834 $conv_data['conversation-uri'] = $conversation_uri;
837 $entry = $doc2->importNode($entry, true);
839 $doc2->appendChild($entry);
841 $conv_data['source'] = $doc2->saveXML();
843 $condition = ['item-uri' => $conv_data['uri'],'protocol' => PROTOCOL_OSTATUS_FEED];
844 if (dba::exists('conversation', $condition)) {
845 logger('Delete deprecated entry for URI '.$conv_data['uri'], LOGGER_DEBUG);
846 dba::delete('conversation', ['item-uri' => $conv_data['uri']]);
849 logger('Store conversation data for uri '.$conv_data['uri'], LOGGER_DEBUG);
850 Conversation::insert($conv_data);
855 * @brief Fetch the own post so that it can be stored later
857 * We want to store the original data for later processing.
858 * This function is meant for cases where we process a feed with multiple entries.
859 * In that case we need to fetch the single posts here.
861 * @param string $self The link to the self item
862 * @param array $item The item array
865 private static function fetchSelf($self, &$item)
867 $condition = ['`item-uri` = ? AND `protocol` IN (?, ?)', $self, PROTOCOL_DFRN, PROTOCOL_OSTATUS_SALMON];
868 if (dba::exists('conversation', $condition)) {
869 logger('Conversation '.$item['uri'].' is already stored.', LOGGER_DEBUG);
873 $self_data = Network::curl($self);
875 if (!$self_data['success']) {
879 // We reformat the XML to make it better readable
880 $doc = new DOMDocument();
881 $doc->loadXML($self_data['body']);
882 $doc->preserveWhiteSpace = false;
883 $doc->formatOutput = true;
884 $xml = $doc->saveXML();
886 $item["protocol"] = PROTOCOL_OSTATUS_SALMON;
887 $item["source"] = $xml;
889 logger('Conversation '.$item['uri'].' is now fetched.', LOGGER_DEBUG);
893 * @brief Fetch related posts and processes them
895 * @param string $related The link to the related item
896 * @param string $related_uri The related item in "uri" format
897 * @param array $importer user record of the importing user
900 private static function fetchRelated($related, $related_uri, $importer)
902 $condition = ['`item-uri` = ? AND `protocol` IN (?, ?)', $related_uri, PROTOCOL_DFRN, PROTOCOL_OSTATUS_SALMON];
903 $conversation = dba::selectFirst('conversation', ['source', 'protocol'], $condition);
904 if (DBM::is_result($conversation)) {
906 $xml = $conversation['source'];
907 if (self::process($xml, $importer, $contact, $hub, $stored, false)) {
908 logger('Got valid cached XML for URI '.$related_uri, LOGGER_DEBUG);
911 if ($conversation['protocol'] == PROTOCOL_OSTATUS_SALMON) {
912 logger('Delete invalid cached XML for URI '.$related_uri, LOGGER_DEBUG);
913 dba::delete('conversation', ['item-uri' => $related_uri]);
918 $related_data = Network::curl($related, false, $redirects, ['accept_content' => 'application/atom+xml, text/html']);
920 if (!$related_data['success']) {
926 if (stristr($related_data['header'], 'Content-Type: application/atom+xml')) {
927 logger('Directly fetched XML for URI '.$related_uri, LOGGER_DEBUG);
928 $xml = $related_data['body'];
932 $doc = new DOMDocument();
933 if (!@$doc->loadHTML($related_data['body'])) {
936 $xpath = new DOMXPath($doc);
940 $links = $xpath->query('//link');
942 foreach ($links as $link) {
943 $attribute = self::readAttributes($link);
944 if (($attribute['rel'] == 'alternate') && ($attribute['type'] == 'application/atom+xml')) {
945 $atom_file = $attribute['href'];
948 if ($atom_file != '') {
949 $related_atom = Network::curl($atom_file);
951 if ($related_atom['success']) {
952 logger('Fetched XML for URI '.$related_uri, LOGGER_DEBUG);
953 $xml = $related_atom['body'];
959 // Workaround for older GNU Social servers
960 if (($xml == '') && strstr($related, '/notice/')) {
961 $related_atom = Network::curl(str_replace('/notice/', '/api/statuses/show/', $related).'.atom');
963 if ($related_atom['success']) {
964 logger('GNU Social workaround to fetch XML for URI '.$related_uri, LOGGER_DEBUG);
965 $xml = $related_atom['body'];
969 // Even more worse workaround for GNU Social ;-)
971 $related_guess = OStatus::convertHref($related_uri);
972 $related_atom = Network::curl(str_replace('/notice/', '/api/statuses/show/', $related_guess).'.atom');
974 if ($related_atom['success']) {
975 logger('GNU Social workaround 2 to fetch XML for URI '.$related_uri, LOGGER_DEBUG);
976 $xml = $related_atom['body'];
980 // Finally we take the data that we fetched from "ostatus:conversation"
982 $condition = ['item-uri' => $related_uri, 'protocol' => PROTOCOL_SPLITTED_CONV];
983 $conversation = dba::selectFirst('conversation', ['source'], $condition);
984 if (DBM::is_result($conversation)) {
986 logger('Got cached XML from conversation for URI '.$related_uri, LOGGER_DEBUG);
987 $xml = $conversation['source'];
992 self::process($xml, $importer, $contact, $hub, $stored, false);
994 logger("XML couldn't be fetched for URI: ".$related_uri." - href: ".$related, LOGGER_DEBUG);
1000 * @brief Processes the XML for a repeated post
1002 * @param object $xpath The xpath object
1003 * @param object $entry The xml entry that is processed
1004 * @param array $item The item array
1005 * @param array $importer user record of the importing user
1007 * @return array with data from links
1009 private static function processRepeatedItem($xpath, $entry, &$item, $importer)
1011 $activityobjects = $xpath->query('activity:object', $entry)->item(0);
1013 if (!is_object($activityobjects)) {
1019 $orig_uri = $xpath->query('atom:id/text()', $activityobjects)->item(0)->nodeValue;
1021 $links = $xpath->query("atom:link", $activityobjects);
1023 $link_data = self::processLinks($links, $item);
1026 $orig_body = $xpath->query('atom:content/text()', $activityobjects)->item(0)->nodeValue;
1027 $orig_created = $xpath->query('atom:published/text()', $activityobjects)->item(0)->nodeValue;
1028 $orig_edited = $xpath->query('atom:updated/text()', $activityobjects)->item(0)->nodeValue;
1030 $orig_author = self::fetchAuthor($xpath, $activityobjects, $importer, $dummy, false);
1032 $item["author-name"] = $orig_author["author-name"];
1033 $item["author-link"] = $orig_author["author-link"];
1034 $item["author-avatar"] = $orig_author["author-avatar"];
1036 $item["body"] = html2bbcode($orig_body);
1037 $item["created"] = $orig_created;
1038 $item["edited"] = $orig_edited;
1040 $item["uri"] = $orig_uri;
1042 $item["verb"] = $xpath->query('activity:verb/text()', $activityobjects)->item(0)->nodeValue;
1044 $item["object-type"] = $xpath->query('activity:object-type/text()', $activityobjects)->item(0)->nodeValue;
1046 $inreplyto = $xpath->query('thr:in-reply-to', $activityobjects);
1047 if (is_object($inreplyto->item(0))) {
1048 foreach ($inreplyto->item(0)->attributes as $attributes) {
1049 if ($attributes->name == "ref") {
1050 $item["parent-uri"] = $attributes->textContent;
1059 * @brief Processes links in the XML
1061 * @param object $links The xml data that contain links
1062 * @param array $item The item array
1064 * @return array with data from the links
1066 private static function processLinks($links, &$item)
1068 $link_data = ['add_body' => '', 'self' => ''];
1070 foreach ($links as $link) {
1071 $attribute = self::readAttributes($link);
1073 if (($attribute['rel'] != "") && ($attribute['href'] != "")) {
1074 switch ($attribute['rel']) {
1076 $item["plink"] = $attribute['href'];
1077 if (($item["object-type"] == ACTIVITY_OBJ_QUESTION)
1078 || ($item["object-type"] == ACTIVITY_OBJ_EVENT)
1080 $item["body"] .= add_page_info($attribute['href']);
1083 case "ostatus:conversation":
1084 $link_data['conversation'] = $attribute['href'];
1085 $item['conversation-href'] = $link_data['conversation'];
1086 if (!isset($item['conversation-uri'])) {
1087 $item['conversation-uri'] = $item['conversation-href'];
1091 $filetype = strtolower(substr($attribute['type'], 0, strpos($attribute['type'], '/')));
1092 if ($filetype == 'image') {
1093 $link_data['add_body'] .= "\n[img]".$attribute['href'].'[/img]';
1095 if (strlen($item["attach"])) {
1096 $item["attach"] .= ',';
1098 if (!isset($attribute['length'])) {
1099 $attribute['length'] = "0";
1101 $item["attach"] .= '[attach]href="'.$attribute['href'].'" length="'.$attribute['length'].'" type="'.$attribute['type'].'" title="'.$attribute['title'].'"[/attach]';
1105 if ($item["object-type"] != ACTIVITY_OBJ_BOOKMARK) {
1106 if (!isset($item["parent-uri"])) {
1107 $item["parent-uri"] = $attribute['href'];
1109 $link_data['related'] = $attribute['href'];
1111 $item["body"] .= add_page_info($attribute['href']);
1115 if ($item["plink"] == '') {
1116 $item["plink"] = $attribute['href'];
1118 $link_data['self'] = $attribute['href'];
1127 * @brief Create an url out of an uri
1129 * @param string $href URI in the format "parameter1:parameter1:..."
1131 * @return string URL in the format http(s)://....
1133 public static function convertHref($href)
1135 $elements = explode(":", $href);
1137 if ((count($elements) <= 2) || ($elements[0] != "tag")) {
1141 $server = explode(",", $elements[1]);
1142 $conversation = explode("=", $elements[2]);
1144 if ((count($elements) == 4) && ($elements[2] == "post")) {
1145 return "http://".$server[0]."/notice/".$elements[3];
1148 if ((count($conversation) != 2) || ($conversation[1] =="")) {
1151 if ($elements[3] == "objectType=thread") {
1152 return "http://".$server[0]."/conversation/".$conversation[1];
1154 return "http://".$server[0]."/notice/".$conversation[1];
1160 * @brief Checks if the current post is a reshare
1162 * @param array $item The item array of thw post
1164 * @return string The guid if the post is a reshare
1166 private static function getResharedGuid($item)
1168 $body = trim($item["body"]);
1170 // Skip if it isn't a pure repeated messages
1171 // Does it start with a share?
1172 if (strpos($body, "[share") > 0) {
1176 // Does it end with a share?
1177 if (strlen($body) > (strrpos($body, "[/share]") + 8)) {
1181 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "$1", $body);
1182 // Skip if there is no shared message in there
1183 if ($body == $attributes) {
1188 preg_match("/guid='(.*?)'/ism", $attributes, $matches);
1189 if ($matches[1] != "") {
1190 $guid = $matches[1];
1193 preg_match('/guid="(.*?)"/ism', $attributes, $matches);
1194 if ($matches[1] != "") {
1195 $guid = $matches[1];
1202 * @brief Cleans the body of a post if it contains picture links
1204 * @param string $body The body
1206 * @return string The cleaned body
1208 private static function formatPicturePost($body)
1210 $siteinfo = BBCode::getAttachedData($body);
1212 if (($siteinfo["type"] == "photo")) {
1213 if (isset($siteinfo["preview"])) {
1214 $preview = $siteinfo["preview"];
1216 $preview = $siteinfo["image"];
1219 // Is it a remote picture? Then make a smaller preview here
1220 $preview = proxy_url($preview, false, PROXY_SIZE_SMALL);
1222 // Is it a local picture? Then make it smaller here
1223 $preview = str_replace(["-0.jpg", "-0.png"], ["-2.jpg", "-2.png"], $preview);
1224 $preview = str_replace(["-1.jpg", "-1.png"], ["-2.jpg", "-2.png"], $preview);
1226 if (isset($siteinfo["url"])) {
1227 $url = $siteinfo["url"];
1229 $url = $siteinfo["image"];
1232 $body = trim($siteinfo["text"])." [url]".$url."[/url]\n[img]".$preview."[/img]";
1239 * @brief Adds the header elements to the XML document
1241 * @param object $doc XML document
1242 * @param array $owner Contact data of the poster
1243 * @param string $filter The related feed filter (activity, posts or comments)
1245 * @return object header root element
1247 private static function addHeader($doc, $owner, $filter)
1251 $root = $doc->createElementNS(NAMESPACE_ATOM1, 'feed');
1252 $doc->appendChild($root);
1254 $root->setAttribute("xmlns:thr", NAMESPACE_THREAD);
1255 $root->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
1256 $root->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
1257 $root->setAttribute("xmlns:media", NAMESPACE_MEDIA);
1258 $root->setAttribute("xmlns:poco", NAMESPACE_POCO);
1259 $root->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
1260 $root->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
1261 $root->setAttribute("xmlns:mastodon", NAMESPACE_MASTODON);
1264 case 'activity': $title = L10n::t('%s\'s timeline', $owner['name']); break;
1265 case 'posts' : $title = L10n::t('%s\'s posts' , $owner['name']); break;
1266 case 'comments': $title = L10n::t('%s\'s comments', $owner['name']); break;
1269 $attributes = ["uri" => "https://friendi.ca", "version" => FRIENDICA_VERSION . "-" . DB_UPDATE_VERSION];
1270 XML::addElement($doc, $root, "generator", FRIENDICA_PLATFORM, $attributes);
1271 XML::addElement($doc, $root, "id", System::baseUrl() . "/profile/" . $owner["nick"]);
1272 XML::addElement($doc, $root, "title", $title);
1273 XML::addElement($doc, $root, "subtitle", sprintf("Updates from %s on %s", $owner["name"], $a->config["sitename"]));
1274 XML::addElement($doc, $root, "logo", $owner["photo"]);
1275 XML::addElement($doc, $root, "updated", datetime_convert("UTC", "UTC", "now", ATOM_TIME));
1277 $author = self::addAuthor($doc, $owner);
1278 $root->appendChild($author);
1280 $attributes = ["href" => $owner["url"], "rel" => "alternate", "type" => "text/html"];
1281 XML::addElement($doc, $root, "link", "", $attributes);
1283 /// @TODO We have to find out what this is
1284 /// $attributes = array("href" => System::baseUrl()."/sup",
1285 /// "rel" => "http://api.friendfeed.com/2008/03#sup",
1286 /// "type" => "application/json");
1287 /// XML::addElement($doc, $root, "link", "", $attributes);
1289 self::hublinks($doc, $root, $owner["nick"]);
1291 $attributes = ["href" => System::baseUrl() . "/salmon/" . $owner["nick"], "rel" => "salmon"];
1292 XML::addElement($doc, $root, "link", "", $attributes);
1294 $attributes = ["href" => System::baseUrl() . "/salmon/" . $owner["nick"], "rel" => "http://salmon-protocol.org/ns/salmon-replies"];
1295 XML::addElement($doc, $root, "link", "", $attributes);
1297 $attributes = ["href" => System::baseUrl() . "/salmon/" . $owner["nick"], "rel" => "http://salmon-protocol.org/ns/salmon-mention"];
1298 XML::addElement($doc, $root, "link", "", $attributes);
1300 $attributes = ["href" => System::baseUrl() . "/api/statuses/user_timeline/" . $owner["nick"] . ".atom",
1301 "rel" => "self", "type" => "application/atom+xml"];
1302 XML::addElement($doc, $root, "link", "", $attributes);
1308 * @brief Add the link to the push hubs to the XML document
1310 * @param object $doc XML document
1311 * @param object $root XML root element where the hub links are added
1312 * @param object $nick nick
1315 public static function hublinks($doc, $root, $nick)
1317 $h = System::baseUrl() . '/pubsubhubbub/'.$nick;
1318 XML::addElement($doc, $root, "link", "", ["href" => $h, "rel" => "hub"]);
1322 * @brief Adds attachement data to the XML document
1324 * @param object $doc XML document
1325 * @param object $root XML root element where the hub links are added
1326 * @param array $item Data of the item that is to be posted
1329 private static function getAttachment($doc, $root, $item)
1332 $siteinfo = BBCode::getAttachedData($item["body"]);
1334 switch ($siteinfo["type"]) {
1336 $imgdata = Image::getInfoFromURL($siteinfo["image"]);
1337 $attributes = ["rel" => "enclosure",
1338 "href" => $siteinfo["image"],
1339 "type" => $imgdata["mime"],
1340 "length" => intval($imgdata["size"])];
1341 XML::addElement($doc, $root, "link", "", $attributes);
1344 $attributes = ["rel" => "enclosure",
1345 "href" => $siteinfo["url"],
1346 "type" => "text/html; charset=UTF-8",
1348 "title" => $siteinfo["title"]];
1349 XML::addElement($doc, $root, "link", "", $attributes);
1355 if (!Config::get('system', 'ostatus_not_attach_preview') && ($siteinfo["type"] != "photo") && isset($siteinfo["image"])) {
1356 $imgdata = Image::getInfoFromURL($siteinfo["image"]);
1357 $attributes = ["rel" => "enclosure",
1358 "href" => $siteinfo["image"],
1359 "type" => $imgdata["mime"],
1360 "length" => intval($imgdata["size"])];
1362 XML::addElement($doc, $root, "link", "", $attributes);
1365 $arr = explode('[/attach],', $item['attach']);
1367 foreach ($arr as $r) {
1369 $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"|', $r, $matches);
1371 $attributes = ["rel" => "enclosure",
1372 "href" => $matches[1],
1373 "type" => $matches[3]];
1375 if (intval($matches[2])) {
1376 $attributes["length"] = intval($matches[2]);
1378 if (trim($matches[4]) != "") {
1379 $attributes["title"] = trim($matches[4]);
1381 XML::addElement($doc, $root, "link", "", $attributes);
1388 * @brief Adds the author element to the XML document
1390 * @param object $doc XML document
1391 * @param array $owner Contact data of the poster
1393 * @return object author element
1395 private static function addAuthor($doc, $owner)
1397 $r = q("SELECT `homepage`, `publish` FROM `profile` WHERE `uid` = %d AND `is-default` LIMIT 1", intval($owner["uid"]));
1398 if (DBM::is_result($r)) {
1401 $author = $doc->createElement("author");
1402 XML::addElement($doc, $author, "id", $owner["url"]);
1403 XML::addElement($doc, $author, "activity:object-type", ACTIVITY_OBJ_PERSON);
1404 XML::addElement($doc, $author, "uri", $owner["url"]);
1405 XML::addElement($doc, $author, "name", $owner["nick"]);
1406 XML::addElement($doc, $author, "email", $owner["addr"]);
1407 XML::addElement($doc, $author, "summary", bbcode($owner["about"], false, false, 7));
1409 $attributes = ["rel" => "alternate", "type" => "text/html", "href" => $owner["url"]];
1410 XML::addElement($doc, $author, "link", "", $attributes);
1414 "type" => "image/jpeg", // To-Do?
1415 "media:width" => 175,
1416 "media:height" => 175,
1417 "href" => $owner["photo"]];
1418 XML::addElement($doc, $author, "link", "", $attributes);
1420 if (isset($owner["thumb"])) {
1423 "type" => "image/jpeg", // To-Do?
1424 "media:width" => 80,
1425 "media:height" => 80,
1426 "href" => $owner["thumb"]];
1427 XML::addElement($doc, $author, "link", "", $attributes);
1430 XML::addElement($doc, $author, "poco:preferredUsername", $owner["nick"]);
1431 XML::addElement($doc, $author, "poco:displayName", $owner["name"]);
1432 XML::addElement($doc, $author, "poco:note", bbcode($owner["about"], false, false, 7));
1434 if (trim($owner["location"]) != "") {
1435 $element = $doc->createElement("poco:address");
1436 XML::addElement($doc, $element, "poco:formatted", $owner["location"]);
1437 $author->appendChild($element);
1440 if (trim($profile["homepage"]) != "") {
1441 $urls = $doc->createElement("poco:urls");
1442 XML::addElement($doc, $urls, "poco:type", "homepage");
1443 XML::addElement($doc, $urls, "poco:value", $profile["homepage"]);
1444 XML::addElement($doc, $urls, "poco:primary", "true");
1445 $author->appendChild($urls);
1448 if (count($profile)) {
1449 XML::addElement($doc, $author, "followers", "", ["url" => System::baseUrl()."/viewcontacts/".$owner["nick"]]);
1450 XML::addElement($doc, $author, "statusnet:profile_info", "", ["local_id" => $owner["uid"]]);
1453 if ($profile["publish"]) {
1454 XML::addElement($doc, $author, "mastodon:scope", "public");
1460 * @TODO Picture attachments should look like this:
1461 * <a href="https://status.pirati.ca/attachment/572819" title="https://status.pirati.ca/file/heluecht-20151202T222602-rd3u49p.gif"
1462 * class="attachment thumbnail" id="attachment-572819" rel="nofollow external">https://status.pirati.ca/attachment/572819</a>
1466 * @brief Returns the given activity if present - otherwise returns the "post" activity
1468 * @param array $item Data of the item that is to be posted
1470 * @return string activity
1472 private static function constructVerb($item)
1474 if ($item['verb']) {
1475 return $item['verb'];
1478 return ACTIVITY_POST;
1482 * @brief Returns the given object type if present - otherwise returns the "note" object type
1484 * @param array $item Data of the item that is to be posted
1486 * @return string Object type
1488 private static function constructObjecttype($item)
1490 if (in_array($item['object-type'], [ACTIVITY_OBJ_NOTE, ACTIVITY_OBJ_COMMENT]))
1491 return $item['object-type'];
1492 return ACTIVITY_OBJ_NOTE;
1496 * @brief Adds an entry element to the XML document
1498 * @param object $doc XML document
1499 * @param array $item Data of the item that is to be posted
1500 * @param array $owner Contact data of the poster
1501 * @param bool $toplevel optional default false
1503 * @return object Entry element
1505 private static function entry($doc, $item, $owner, $toplevel = false)
1507 $repeated_guid = self::getResharedGuid($item);
1508 if ($repeated_guid != "") {
1509 $xml = self::reshareEntry($doc, $item, $owner, $repeated_guid, $toplevel);
1516 if ($item["verb"] == ACTIVITY_LIKE) {
1517 return self::likeEntry($doc, $item, $owner, $toplevel);
1518 } elseif (in_array($item["verb"], [ACTIVITY_FOLLOW, NAMESPACE_OSTATUS."/unfollow"])) {
1519 return self::followEntry($doc, $item, $owner, $toplevel);
1521 return self::noteEntry($doc, $item, $owner, $toplevel);
1526 * @brief Adds a source entry to the XML document
1528 * @param object $doc XML document
1529 * @param array $contact Array of the contact that is added
1531 * @return object Source element
1533 private static function sourceEntry($doc, $contact)
1535 $source = $doc->createElement("source");
1536 XML::addElement($doc, $source, "id", $contact["poll"]);
1537 XML::addElement($doc, $source, "title", $contact["name"]);
1538 XML::addElement($doc, $source, "link", "", ["rel" => "alternate", "type" => "text/html", "href" => $contact["alias"]]);
1539 XML::addElement($doc, $source, "link", "", ["rel" => "self", "type" => "application/atom+xml", "href" => $contact["poll"]]);
1540 XML::addElement($doc, $source, "icon", $contact["photo"]);
1541 XML::addElement($doc, $source, "updated", datetime_convert("UTC", "UTC", $contact["success_update"]."+00:00", ATOM_TIME));
1547 * @brief Fetches contact data from the contact or the gcontact table
1549 * @param string $url URL of the contact
1550 * @param array $owner Contact data of the poster
1552 * @return array Contact array
1554 private static function contactEntry($url, $owner)
1557 "SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` IN (0, %d) ORDER BY `uid` DESC LIMIT 1",
1558 dbesc(normalise_link($url)),
1559 intval($owner["uid"])
1561 if (DBM::is_result($r)) {
1563 $contact["uid"] = -1;
1566 if (!DBM::is_result($r)) {
1568 "SELECT * FROM `gcontact` WHERE `nurl` = '%s' LIMIT 1",
1569 dbesc(normalise_link($url))
1571 if (DBM::is_result($r)) {
1573 $contact["uid"] = -1;
1574 $contact["success_update"] = $contact["updated"];
1578 if (!DBM::is_result($r)) {
1582 if (!isset($contact["poll"])) {
1583 $data = Probe::uri($url);
1584 $contact["poll"] = $data["poll"];
1586 if (!$contact["alias"]) {
1587 $contact["alias"] = $data["alias"];
1591 if (!isset($contact["alias"])) {
1592 $contact["alias"] = $contact["url"];
1599 * @brief Adds an entry element with reshared content
1601 * @param object $doc XML document
1602 * @param array $item Data of the item that is to be posted
1603 * @param array $owner Contact data of the poster
1604 * @param string $repeated_guid guid
1605 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1607 * @return object Entry element
1609 private static function reshareEntry($doc, $item, $owner, $repeated_guid, $toplevel)
1611 if (($item["id"] != $item["parent"]) && (normalise_link($item["author-link"]) != normalise_link($owner["url"]))) {
1612 logger("OStatus entry is from author ".$owner["url"]." - not from ".$item["author-link"].". Quitting.", LOGGER_DEBUG);
1615 $title = self::entryHeader($doc, $entry, $owner, $toplevel);
1618 "SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' AND NOT `private` AND `network` IN ('%s', '%s', '%s') LIMIT 1",
1619 intval($owner["uid"]),
1620 dbesc($repeated_guid),
1621 dbesc(NETWORK_DFRN),
1622 dbesc(NETWORK_DIASPORA),
1623 dbesc(NETWORK_OSTATUS)
1625 if (DBM::is_result($r)) {
1626 $repeated_item = $r[0];
1630 $contact = self::contactEntry($repeated_item['author-link'], $owner);
1632 $parent_item = (($item['thr-parent']) ? $item['thr-parent'] : $item['parent-uri']);
1634 $title = $owner["nick"]." repeated a notice by ".$contact["nick"];
1636 self::entryContent($doc, $entry, $item, $owner, $title, ACTIVITY_SHARE, false);
1638 $as_object = $doc->createElement("activity:object");
1640 XML::addElement($doc, $as_object, "activity:object-type", NAMESPACE_ACTIVITY_SCHEMA."activity");
1642 self::entryContent($doc, $as_object, $repeated_item, $owner, "", "", false);
1644 $author = self::addAuthor($doc, $contact);
1645 $as_object->appendChild($author);
1647 $as_object2 = $doc->createElement("activity:object");
1649 XML::addElement($doc, $as_object2, "activity:object-type", self::constructObjecttype($repeated_item));
1651 $title = sprintf("New comment by %s", $contact["nick"]);
1653 self::entryContent($doc, $as_object2, $repeated_item, $owner, $title);
1655 $as_object->appendChild($as_object2);
1657 self::entryFooter($doc, $as_object, $item, $owner, false);
1659 $source = self::sourceEntry($doc, $contact);
1661 $as_object->appendChild($source);
1663 $entry->appendChild($as_object);
1665 self::entryFooter($doc, $entry, $item, $owner);
1671 * @brief Adds an entry element with a "like"
1673 * @param object $doc XML document
1674 * @param array $item Data of the item that is to be posted
1675 * @param array $owner Contact data of the poster
1676 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1678 * @return object Entry element with "like"
1680 private static function likeEntry($doc, $item, $owner, $toplevel)
1682 if (($item["id"] != $item["parent"]) && (normalise_link($item["author-link"]) != normalise_link($owner["url"]))) {
1683 logger("OStatus entry is from author ".$owner["url"]." - not from ".$item["author-link"].". Quitting.", LOGGER_DEBUG);
1686 $title = self::entryHeader($doc, $entry, $owner, $toplevel);
1688 $verb = NAMESPACE_ACTIVITY_SCHEMA."favorite";
1689 self::entryContent($doc, $entry, $item, $owner, "Favorite", $verb, false);
1691 $as_object = $doc->createElement("activity:object");
1694 "SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d",
1695 dbesc($item["thr-parent"]),
1696 intval($item["uid"])
1698 $parent_item = (($item['thr-parent']) ? $item['thr-parent'] : $item['parent-uri']);
1700 XML::addElement($doc, $as_object, "activity:object-type", self::constructObjecttype($parent[0]));
1702 self::entryContent($doc, $as_object, $parent[0], $owner, "New entry");
1704 $entry->appendChild($as_object);
1706 self::entryFooter($doc, $entry, $item, $owner);
1712 * @brief Adds the person object element to the XML document
1714 * @param object $doc XML document
1715 * @param array $owner Contact data of the poster
1716 * @param array $contact Contact data of the target
1718 * @return object author element
1720 private static function addPersonObject($doc, $owner, $contact)
1722 $object = $doc->createElement("activity:object");
1723 XML::addElement($doc, $object, "activity:object-type", ACTIVITY_OBJ_PERSON);
1725 if ($contact['network'] == NETWORK_PHANTOM) {
1726 XML::addElement($doc, $object, "id", $contact['url']);
1730 XML::addElement($doc, $object, "id", $contact["alias"]);
1731 XML::addElement($doc, $object, "title", $contact["nick"]);
1733 $attributes = ["rel" => "alternate", "type" => "text/html", "href" => $contact["url"]];
1734 XML::addElement($doc, $object, "link", "", $attributes);
1738 "type" => "image/jpeg", // To-Do?
1739 "media:width" => 175,
1740 "media:height" => 175,
1741 "href" => $contact["photo"]];
1742 XML::addElement($doc, $object, "link", "", $attributes);
1744 XML::addElement($doc, $object, "poco:preferredUsername", $contact["nick"]);
1745 XML::addElement($doc, $object, "poco:displayName", $contact["name"]);
1747 if (trim($contact["location"]) != "") {
1748 $element = $doc->createElement("poco:address");
1749 XML::addElement($doc, $element, "poco:formatted", $contact["location"]);
1750 $object->appendChild($element);
1757 * @brief Adds a follow/unfollow entry element
1759 * @param object $doc XML document
1760 * @param array $item Data of the follow/unfollow message
1761 * @param array $owner Contact data of the poster
1762 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1764 * @return object Entry element
1766 private static function followEntry($doc, $item, $owner, $toplevel)
1768 $item["id"] = $item["parent"] = 0;
1769 $item["created"] = $item["edited"] = date("c");
1770 $item["private"] = true;
1772 $contact = Probe::uri($item['follow']);
1774 if ($contact['alias'] == '') {
1775 $contact['alias'] = $contact["url"];
1777 $item['follow'] = $contact['alias'];
1781 "SELECT `id` FROM `contact` WHERE `uid` = %d AND `nurl` = '%s'",
1782 intval($owner['uid']),
1783 dbesc(normalise_link($contact["url"]))
1786 if (DBM::is_result($r)) {
1787 $connect_id = $r[0]['id'];
1792 if ($item['verb'] == ACTIVITY_FOLLOW) {
1793 $message = L10n::t('%s is now following %s.');
1794 $title = L10n::t('following');
1795 $action = "subscription";
1797 $message = L10n::t('%s stopped following %s.');
1798 $title = L10n::t('stopped following');
1799 $action = "unfollow";
1802 $item["uri"] = $item['parent-uri'] = $item['thr-parent']
1803 = 'tag:'.get_app()->get_hostname().
1804 ','.date('Y-m-d').':'.$action.':'.$owner['uid'].
1805 ':person:'.$connect_id.':'.$item['created'];
1807 $item["body"] = sprintf($message, $owner["nick"], $contact["nick"]);
1809 self::entryHeader($doc, $entry, $owner, $toplevel);
1811 self::entryContent($doc, $entry, $item, $owner, $title);
1813 $object = self::addPersonObject($doc, $owner, $contact);
1814 $entry->appendChild($object);
1816 self::entryFooter($doc, $entry, $item, $owner);
1822 * @brief Adds a regular entry element
1824 * @param object $doc XML document
1825 * @param array $item Data of the item that is to be posted
1826 * @param array $owner Contact data of the poster
1827 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1829 * @return object Entry element
1831 private static function noteEntry($doc, $item, $owner, $toplevel)
1833 if (($item["id"] != $item["parent"]) && (normalise_link($item["author-link"]) != normalise_link($owner["url"]))) {
1834 logger("OStatus entry is from author ".$owner["url"]." - not from ".$item["author-link"].". Quitting.", LOGGER_DEBUG);
1837 $title = self::entryHeader($doc, $entry, $owner, $toplevel);
1839 XML::addElement($doc, $entry, "activity:object-type", ACTIVITY_OBJ_NOTE);
1841 self::entryContent($doc, $entry, $item, $owner, $title);
1843 self::entryFooter($doc, $entry, $item, $owner);
1849 * @brief Adds a header element to the XML document
1851 * @param object $doc XML document
1852 * @param object $entry The entry element where the elements are added
1853 * @param array $owner Contact data of the poster
1854 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1856 * @return string The title for the element
1858 private static function entryHeader($doc, &$entry, $owner, $toplevel)
1860 /// @todo Check if this title stuff is really needed (I guess not)
1862 $entry = $doc->createElement("entry");
1863 $title = sprintf("New note by %s", $owner["nick"]);
1865 $entry = $doc->createElementNS(NAMESPACE_ATOM1, "entry");
1867 $entry->setAttribute("xmlns:thr", NAMESPACE_THREAD);
1868 $entry->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
1869 $entry->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
1870 $entry->setAttribute("xmlns:media", NAMESPACE_MEDIA);
1871 $entry->setAttribute("xmlns:poco", NAMESPACE_POCO);
1872 $entry->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
1873 $entry->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
1874 $entry->setAttribute("xmlns:mastodon", NAMESPACE_MASTODON);
1876 $author = self::addAuthor($doc, $owner);
1877 $entry->appendChild($author);
1879 $title = sprintf("New comment by %s", $owner["nick"]);
1885 * @brief Adds elements to the XML document
1887 * @param object $doc XML document
1888 * @param object $entry Entry element where the content is added
1889 * @param array $item Data of the item that is to be posted
1890 * @param array $owner Contact data of the poster
1891 * @param string $title Title for the post
1892 * @param string $verb The activity verb
1893 * @param bool $complete Add the "status_net" element?
1896 private static function entryContent($doc, $entry, $item, $owner, $title, $verb = "", $complete = true)
1899 $verb = self::constructVerb($item);
1902 XML::addElement($doc, $entry, "id", $item["uri"]);
1903 XML::addElement($doc, $entry, "title", $title);
1905 $body = self::formatPicturePost($item['body']);
1907 if ($item['title'] != "") {
1908 $body = "[b]".$item['title']."[/b]\n\n".$body;
1911 $body = bbcode($body, false, false, 7);
1913 XML::addElement($doc, $entry, "content", $body, ["type" => "html"]);
1915 XML::addElement($doc, $entry, "link", "", ["rel" => "alternate", "type" => "text/html",
1916 "href" => System::baseUrl()."/display/".$item["guid"]]
1919 if ($complete && ($item["id"] > 0)) {
1920 XML::addElement($doc, $entry, "status_net", "", ["notice_id" => $item["id"]]);
1923 XML::addElement($doc, $entry, "activity:verb", $verb);
1925 XML::addElement($doc, $entry, "published", datetime_convert("UTC", "UTC", $item["created"]."+00:00", ATOM_TIME));
1926 XML::addElement($doc, $entry, "updated", datetime_convert("UTC", "UTC", $item["edited"]."+00:00", ATOM_TIME));
1930 * @brief Adds the elements at the foot of an entry to the XML document
1932 * @param object $doc XML document
1933 * @param object $entry The entry element where the elements are added
1934 * @param array $item Data of the item that is to be posted
1935 * @param array $owner Contact data of the poster
1936 * @param bool $complete default true
1939 private static function entryFooter($doc, $entry, $item, $owner, $complete = true)
1943 if (($item['parent'] != $item['id']) || ($item['parent-uri'] !== $item['uri']) || (($item['thr-parent'] !== '') && ($item['thr-parent'] !== $item['uri']))) {
1944 $parent = q("SELECT `guid`, `author-link`, `owner-link` FROM `item` WHERE `id` = %d", intval($item["parent"]));
1945 $parent_item = (($item['thr-parent']) ? $item['thr-parent'] : $item['parent-uri']);
1948 "SELECT `guid`, `author-link`, `owner-link`, `plink` FROM `item` WHERE `uid` = %d AND `uri` = '%s'",
1949 intval($owner["uid"]),
1953 $mentioned[$thrparent[0]["author-link"]] = $thrparent[0]["author-link"];
1954 $mentioned[$thrparent[0]["owner-link"]] = $thrparent[0]["owner-link"];
1955 $parent_plink = $thrparent[0]["plink"];
1957 $mentioned[$parent[0]["author-link"]] = $parent[0]["author-link"];
1958 $mentioned[$parent[0]["owner-link"]] = $parent[0]["owner-link"];
1959 $parent_plink = System::baseUrl()."/display/".$parent[0]["guid"];
1963 "ref" => $parent_item,
1964 "href" => $parent_plink];
1965 XML::addElement($doc, $entry, "thr:in-reply-to", "", $attributes);
1969 "href" => $parent_plink];
1970 XML::addElement($doc, $entry, "link", "", $attributes);
1973 if (intval($item["parent"]) > 0) {
1974 $conversation_href = System::baseUrl()."/display/".$owner["nick"]."/".$item["parent"];
1975 $conversation_uri = $conversation_href;
1977 if (isset($parent_item)) {
1978 $r = dba::fetch_first("SELECT `conversation-uri`, `conversation-href` FROM `conversation` WHERE `item-uri` = ?", $parent_item);
1979 if (DBM::is_result($r)) {
1980 if ($r['conversation-uri'] != '') {
1981 $conversation_uri = $r['conversation-uri'];
1983 if ($r['conversation-href'] != '') {
1984 $conversation_href = $r['conversation-href'];
1989 XML::addElement($doc, $entry, "link", "", ["rel" => "ostatus:conversation", "href" => $conversation_href]);
1992 "href" => $conversation_href,
1993 "local_id" => $item["parent"],
1994 "ref" => $conversation_uri];
1996 XML::addElement($doc, $entry, "ostatus:conversation", $conversation_uri, $attributes);
1999 $tags = item_getfeedtags($item);
2002 foreach ($tags as $t) {
2004 $mentioned[$t[1]] = $t[1];
2009 // Make sure that mentions are accepted (GNU Social has problems with mixing HTTP and HTTPS)
2011 foreach ($mentioned as $mention) {
2012 $newmentions[str_replace("http://", "https://", $mention)] = str_replace("http://", "https://", $mention);
2013 $newmentions[str_replace("https://", "http://", $mention)] = str_replace("https://", "http://", $mention);
2015 $mentioned = $newmentions;
2017 foreach ($mentioned as $mention) {
2019 "SELECT `forum`, `prv` FROM `contact` WHERE `uid` = %d AND `nurl` = '%s'",
2020 intval($owner["uid"]),
2021 dbesc(normalise_link($mention))
2023 if ($r[0]["forum"] || $r[0]["prv"]) {
2024 XML::addElement($doc, $entry, "link", "",
2026 "rel" => "mentioned",
2027 "ostatus:object-type" => ACTIVITY_OBJ_GROUP,
2031 XML::addElement($doc, $entry, "link", "",
2033 "rel" => "mentioned",
2034 "ostatus:object-type" => ACTIVITY_OBJ_PERSON,
2040 if (!$item["private"]) {
2041 XML::addElement($doc, $entry, "link", "", ["rel" => "ostatus:attention",
2042 "href" => "http://activityschema.org/collection/public"]);
2043 XML::addElement($doc, $entry, "link", "", ["rel" => "mentioned",
2044 "ostatus:object-type" => "http://activitystrea.ms/schema/1.0/collection",
2045 "href" => "http://activityschema.org/collection/public"]);
2046 XML::addElement($doc, $entry, "mastodon:scope", "public");
2050 foreach ($tags as $t) {
2052 XML::addElement($doc, $entry, "category", "", ["term" => $t[2]]);
2057 self::getAttachment($doc, $entry, $item);
2059 if ($complete && ($item["id"] > 0)) {
2060 $app = $item["app"];
2065 $attributes = ["local_id" => $item["id"], "source" => $app];
2067 if (isset($parent["id"])) {
2068 $attributes["repeat_of"] = $parent["id"];
2071 if ($item["coord"] != "") {
2072 XML::addElement($doc, $entry, "georss:point", $item["coord"]);
2075 XML::addElement($doc, $entry, "statusnet:notice_info", "", $attributes);
2080 * Creates the XML feed for a given nickname
2082 * Supported filters:
2083 * - activity (default): all the public posts
2084 * - posts: all the public top-level posts
2085 * - comments: all the public replies
2087 * Updates the provided last_update parameter if the result comes from the
2088 * cache or it is empty
2090 * @brief Creates the XML feed for a given nickname
2092 * @param string $owner_nick Nickname of the feed owner
2093 * @param string $last_update Date of the last update
2094 * @param integer $max_items Number of maximum items to fetch
2095 * @param string $filter Feed items filter (activity, posts or comments)
2096 * @param boolean $nocache Wether to bypass caching
2098 * @return string XML feed
2100 public static function feed($owner_nick, &$last_update, $max_items = 300, $filter = 'activity', $nocache = false)
2102 $stamp = microtime(true);
2104 $cachekey = "ostatus:feed:" . $owner_nick . ":" . $filter . ":" . $last_update;
2106 $previous_created = $last_update;
2108 $result = Cache::get($cachekey);
2109 if (!$nocache && !is_null($result)) {
2110 logger('Feed duration: ' . number_format(microtime(true) - $stamp, 3) . ' - ' . $owner_nick . ' - ' . $filter . ' - ' . $previous_created . ' (cached)', LOGGER_DEBUG);
2111 $last_update = $result['last_update'];
2112 return $result['feed'];
2115 $owner = dba::fetch_first(
2116 "SELECT `contact`.*, `user`.`nickname`, `user`.`timezone`, `user`.`page-flags`
2117 FROM `contact` INNER JOIN `user` ON `user`.`uid` = `contact`.`uid`
2118 WHERE `contact`.`self` AND `user`.`nickname` = ? LIMIT 1",
2121 if (!DBM::is_result($owner)) {
2125 if (!strlen($last_update)) {
2126 $last_update = 'now -30 days';
2129 $check_date = datetime_convert('UTC', 'UTC', $last_update, 'Y-m-d H:i:s');
2130 $authorid = Contact::getIdForURL($owner["url"], 0);
2133 if ($filter === 'posts') {
2134 $sql_extra .= ' AND `item`.`id` = `item`.`parent` ';
2137 if ($filter === 'comments') {
2138 $sql_extra .= sprintf(" AND `item`.`object-type` = '%s' ", dbesc(ACTIVITY_OBJ_COMMENT));
2142 "SELECT `item`.*, `item`.`id` AS `item_id` FROM `item` USE INDEX (`uid_contactid_created`)
2143 STRAIGHT_JOIN `thread` ON `thread`.`iid` = `item`.`parent`
2144 WHERE `item`.`uid` = %d
2145 AND `item`.`contact-id` = %d
2146 AND `item`.`author-id` = %d
2147 AND `item`.`created` > '%s'
2148 AND NOT `item`.`deleted`
2149 AND NOT `item`.`private`
2150 AND `thread`.`network` IN ('%s', '%s')
2152 ORDER BY `item`.`created` DESC LIMIT %d",
2153 intval($owner["uid"]),
2154 intval($owner["id"]),
2157 dbesc(NETWORK_OSTATUS),
2158 dbesc(NETWORK_DFRN),
2162 $doc = new DOMDocument('1.0', 'utf-8');
2163 $doc->formatOutput = true;
2165 $root = self::addHeader($doc, $owner, $filter);
2167 foreach ($items as $item) {
2168 if (Config::get('system', 'ostatus_debug')) {
2169 $item['body'] .= '🍼';
2171 $entry = self::entry($doc, $item, $owner);
2172 $root->appendChild($entry);
2174 if ($last_update < $item['created']) {
2175 $last_update = $item['created'];
2179 $feeddata = trim($doc->saveXML());
2181 $msg = ['feed' => $feeddata, 'last_update' => $last_update];
2182 Cache::set($cachekey, $msg, CACHE_QUARTER_HOUR);
2184 logger('Feed duration: ' . number_format(microtime(true) - $stamp, 3) . ' - ' . $owner_nick . ' - ' . $filter . ' - ' . $previous_created, LOGGER_DEBUG);
2190 * @brief Creates the XML for a salmon message
2192 * @param array $item Data of the item that is to be posted
2193 * @param array $owner Contact data of the poster
2195 * @return string XML for the salmon
2197 public static function salmon($item, $owner)
2199 $doc = new DOMDocument('1.0', 'utf-8');
2200 $doc->formatOutput = true;
2202 if (Config::get('system', 'ostatus_debug')) {
2203 $item['body'] .= '🐟';
2206 $entry = self::entry($doc, $item, $owner, true);
2208 $doc->appendChild($entry);
2210 return trim($doc->saveXML());