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/threads.php';
29 require_once 'include/html2bbcode.php';
30 require_once 'include/bbcode.php';
31 require_once 'include/items.php';
32 require_once 'mod/share.php';
33 require_once 'include/enotify.php';
34 require_once 'include/api.php';
35 require_once 'mod/proxy.php';
38 * @brief This class contain functions for the OStatus protocol
42 private static $itemlist;
43 private static $conv_list = [];
46 * @brief Fetches author data
48 * @param object $xpath The xpath object
49 * @param object $context The xml context of the author details
50 * @param array $importer user record of the importing user
51 * @param array $contact Called by reference, will contain the fetched contact
52 * @param bool $onlyfetch Only fetch the header without updating the contact entries
54 * @return array Array of author related entries for the item
56 private static function fetchAuthor($xpath, $context, $importer, &$contact, $onlyfetch)
59 $author["author-link"] = $xpath->evaluate('atom:author/atom:uri/text()', $context)->item(0)->nodeValue;
60 $author["author-name"] = $xpath->evaluate('atom:author/atom:name/text()', $context)->item(0)->nodeValue;
61 $addr = $xpath->evaluate('atom:author/atom:email/text()', $context)->item(0)->nodeValue;
63 $aliaslink = $author["author-link"];
65 $alternate = $xpath->query("atom:author/atom:link[@rel='alternate']", $context)->item(0)->attributes;
66 if (is_object($alternate)) {
67 foreach ($alternate as $attributes) {
68 if (($attributes->name == "href") && ($attributes->textContent != "")) {
69 $author["author-link"] = $attributes->textContent;
73 $author["contact-id"] = $contact["id"];
77 if ($aliaslink != '') {
78 $condition = ["`uid` = ? AND `alias` = ? AND `network` != ?",
79 $importer["uid"], $aliaslink, NETWORK_STATUSNET];
80 $r = dba::selectFirst('contact', [], $condition);
82 if (DBM::is_result($r)) {
88 $author["contact-id"] = $r["id"];
92 if (!$found && ($author["author-link"] != "")) {
93 if ($aliaslink == "") {
94 $aliaslink = $author["author-link"];
97 $condition = ["`uid` = ? AND `nurl` IN (?, ?) AND `network` != ?", $importer["uid"],
98 normalise_link($author["author-link"]), normalise_link($aliaslink), NETWORK_STATUSNET];
99 $r = dba::selectFirst('contact', [], $condition);
101 if (DBM::is_result($r)) {
107 $author["contact-id"] = $r["id"];
111 if (!$found && ($addr != "")) {
112 $condition = ["`uid` = ? AND `addr` = ? AND `network` != ?",
113 $importer["uid"], $addr, NETWORK_STATUSNET];
114 $r = dba::selectFirst('contact', [], $condition);
116 if (DBM::is_result($r)) {
122 $author["contact-id"] = $r["id"];
127 $avatars = $xpath->query("atom:author/atom:link[@rel='avatar']", $context);
128 foreach ($avatars as $avatar) {
131 foreach ($avatar->attributes as $attributes) {
132 if ($attributes->name == "href") {
133 $href = $attributes->textContent;
135 if ($attributes->name == "width") {
136 $width = $attributes->textContent;
140 $avatarlist[$width] = $href;
143 if (count($avatarlist) > 0) {
145 $author["author-avatar"] = Probe::fixAvatar(current($avatarlist), $author["author-link"]);
148 $displayname = $xpath->evaluate('atom:author/poco:displayName/text()', $context)->item(0)->nodeValue;
149 if ($displayname != "") {
150 $author["author-name"] = $displayname;
153 $author["owner-name"] = $author["author-name"];
154 $author["owner-link"] = $author["author-link"];
155 $author["owner-avatar"] = $author["author-avatar"];
157 // Only update the contacts if it is an OStatus contact
158 if ($r && ($r['id'] > 0) && !$onlyfetch && ($contact["network"] == NETWORK_OSTATUS)) {
160 // Update contact data
162 unset($current['name-date']);
164 // This query doesn't seem to work
165 // $value = $xpath->query("atom:link[@rel='salmon']", $context)->item(0)->nodeValue;
167 // $contact["notify"] = $value;
169 // This query doesn't seem to work as well - I hate these queries
170 // $value = $xpath->query("atom:link[@rel='self' and @type='application/atom+xml']", $context)->item(0)->nodeValue;
172 // $contact["poll"] = $value;
174 $contact['url'] = $author["author-link"];
175 $contact['nurl'] = normalise_link($contact['url']);
177 $value = $xpath->evaluate('atom:author/atom:uri/text()', $context)->item(0)->nodeValue;
179 $contact["alias"] = $value;
182 $value = $xpath->evaluate('atom:author/poco:displayName/text()', $context)->item(0)->nodeValue;
184 $contact["name"] = $value;
187 $value = $xpath->evaluate('atom:author/poco:preferredUsername/text()', $context)->item(0)->nodeValue;
189 $contact["nick"] = $value;
192 $value = $xpath->evaluate('atom:author/poco:note/text()', $context)->item(0)->nodeValue;
194 $contact["about"] = html2bbcode($value);
197 $value = $xpath->evaluate('atom:author/poco:address/poco:formatted/text()', $context)->item(0)->nodeValue;
199 $contact["location"] = $value;
202 $contact['name-date'] = DateTimeFormat::utcNow();
204 dba::update('contact', $contact, ['id' => $contact["id"]], $current);
206 if (!empty($author["author-avatar"]) && ($author["author-avatar"] != $current['avatar'])) {
207 logger("Update profile picture for contact ".$contact["id"], LOGGER_DEBUG);
208 Contact::updateAvatar($author["author-avatar"], $importer["uid"], $contact["id"]);
211 // Ensure that we are having this contact (with uid=0)
212 $cid = Contact::getIdForURL($aliaslink, 0);
215 $fields = ['url', 'nurl', 'name', 'nick', 'alias', 'about', 'location'];
216 $old_contact = dba::selectFirst('contact', $fields, ['id' => $cid]);
218 // Update it with the current values
219 $fields = ['url' => $author["author-link"], 'name' => $contact["name"],
220 'nurl' => normalise_link($author["author-link"]),
221 'nick' => $contact["nick"], 'alias' => $contact["alias"],
222 'about' => $contact["about"], 'location' => $contact["location"],
223 'success_update' => DateTimeFormat::utcNow(), 'last-update' => DateTimeFormat::utcNow()];
225 dba::update('contact', $fields, ['id' => $cid], $old_contact);
228 Contact::updateAvatar($author["author-avatar"], 0, $cid);
231 $contact["generation"] = 2;
232 $contact["hide"] = false; // OStatus contacts are never hidden
233 $contact["photo"] = $author["author-avatar"];
234 $gcid = GContact::update($contact);
236 GContact::link($gcid, $contact["uid"], $contact["id"]);
243 * @brief Fetches author data from a given XML string
245 * @param string $xml The XML
246 * @param array $importer user record of the importing user
248 * @return array Array of author related entries for the item
250 public static function salmonAuthor($xml, $importer)
256 $doc = new DOMDocument();
257 @$doc->loadXML($xml);
259 $xpath = new DOMXPath($doc);
260 $xpath->registerNamespace('atom', NAMESPACE_ATOM1);
261 $xpath->registerNamespace('thr', NAMESPACE_THREAD);
262 $xpath->registerNamespace('georss', NAMESPACE_GEORSS);
263 $xpath->registerNamespace('activity', NAMESPACE_ACTIVITY);
264 $xpath->registerNamespace('media', NAMESPACE_MEDIA);
265 $xpath->registerNamespace('poco', NAMESPACE_POCO);
266 $xpath->registerNamespace('ostatus', NAMESPACE_OSTATUS);
267 $xpath->registerNamespace('statusnet', NAMESPACE_STATUSNET);
269 $entries = $xpath->query('/atom:entry');
271 foreach ($entries as $entry) {
273 $author = self::fetchAuthor($xpath, $entry, $importer, $contact, true);
279 * @brief Read attributes from element
281 * @param object $element Element object
283 * @return array attributes
285 private static function readAttributes($element)
289 foreach ($element->attributes as $attributes) {
290 $attribute[$attributes->name] = $attributes->textContent;
297 * @brief Imports an XML string containing OStatus elements
299 * @param string $xml The XML
300 * @param array $importer user record of the importing user
301 * @param array $contact contact
302 * @param string $hub Called by reference, returns the fetched hub data
305 public static function import($xml, $importer, &$contact, &$hub)
307 self::process($xml, $importer, $contact, $hub);
311 * @brief Internal feed processing
313 * @param string $xml The XML
314 * @param array $importer user record of the importing user
315 * @param array $contact contact
316 * @param string $hub Called by reference, returns the fetched hub data
317 * @param boolean $stored Is the post fresh imported or from the database?
318 * @param boolean $initialize Is it the leading post so that data has to be initialized?
320 * @return boolean Could the XML be processed?
322 private static function process($xml, $importer, &$contact, &$hub, $stored = false, $initialize = true)
325 self::$itemlist = [];
326 self::$conv_list = [];
329 logger("Import OStatus message", LOGGER_DEBUG);
334 $doc = new DOMDocument();
335 @$doc->loadXML($xml);
337 $xpath = new DOMXPath($doc);
338 $xpath->registerNamespace('atom', NAMESPACE_ATOM1);
339 $xpath->registerNamespace('thr', NAMESPACE_THREAD);
340 $xpath->registerNamespace('georss', NAMESPACE_GEORSS);
341 $xpath->registerNamespace('activity', NAMESPACE_ACTIVITY);
342 $xpath->registerNamespace('media', NAMESPACE_MEDIA);
343 $xpath->registerNamespace('poco', NAMESPACE_POCO);
344 $xpath->registerNamespace('ostatus', NAMESPACE_OSTATUS);
345 $xpath->registerNamespace('statusnet', NAMESPACE_STATUSNET);
348 $hub_attributes = $xpath->query("/atom:feed/atom:link[@rel='hub']")->item(0)->attributes;
349 if (is_object($hub_attributes)) {
350 foreach ($hub_attributes as $hub_attribute) {
351 if ($hub_attribute->name == "href") {
352 $hub = $hub_attribute->textContent;
353 logger("Found hub ".$hub, LOGGER_DEBUG);
359 $header["uid"] = $importer["uid"];
360 $header["network"] = NETWORK_OSTATUS;
361 $header["type"] = "remote";
363 $header["origin"] = 0;
364 $header["gravity"] = GRAVITY_PARENT;
366 $first_child = $doc->firstChild->tagName;
368 if ($first_child == "feed") {
369 $entries = $xpath->query('/atom:feed/atom:entry');
371 $entries = $xpath->query('/atom:entry');
374 if ($entries->length == 1) {
375 // We reformat the XML to make it better readable
376 $doc2 = new DOMDocument();
377 $doc2->loadXML($xml);
378 $doc2->preserveWhiteSpace = false;
379 $doc2->formatOutput = true;
380 $xml2 = $doc2->saveXML();
382 $header["protocol"] = PROTOCOL_OSTATUS_SALMON;
383 $header["source"] = $xml2;
384 } elseif (!$initialize) {
388 // Fetch the first author
389 $authordata = $xpath->query('//author')->item(0);
390 $author = self::fetchAuthor($xpath, $authordata, $importer, $contact, $stored);
392 $entry = $xpath->query('/atom:entry');
394 // Reverse the order of the entries
397 foreach ($entries as $entry) {
398 $entrylist[] = $entry;
401 foreach (array_reverse($entrylist) as $entry) {
403 $authorelement = $xpath->query('/atom:entry/atom:author', $entry);
405 if ($authorelement->length == 0) {
406 $authorelement = $xpath->query('atom:author', $entry);
409 if ($authorelement->length > 0) {
410 $author = self::fetchAuthor($xpath, $entry, $importer, $contact, $stored);
413 $value = $xpath->evaluate('atom:author/poco:preferredUsername/text()', $entry)->item(0)->nodeValue;
417 $nickname = $author["author-name"];
420 $item = array_merge($header, $author);
422 $item["uri"] = $xpath->query('atom:id/text()', $entry)->item(0)->nodeValue;
424 $item["verb"] = $xpath->query('activity:verb/text()', $entry)->item(0)->nodeValue;
427 if (in_array($item["verb"], ['qvitter-delete-notice', ACTIVITY_DELETE, 'delete'])) {
428 self::deleteNotice($item);
432 if (in_array($item["verb"], [NAMESPACE_OSTATUS."/unfavorite", ACTIVITY_UNFAVORITE])) {
433 // Ignore "Unfavorite" message
434 logger("Ignore unfavorite message ".print_r($item, true), LOGGER_DEBUG);
438 // Deletions come with the same uri, so we check for duplicates after processing deletions
439 if (dba::exists('item', ['uid' => $importer["uid"], 'uri' => $item["uri"]])) {
440 logger('Post with URI '.$item["uri"].' already existed for user '.$importer["uid"].'.', LOGGER_DEBUG);
443 logger('Processing post with URI '.$item["uri"].' for user '.$importer["uid"].'.', LOGGER_DEBUG);
446 if ($item["verb"] == ACTIVITY_JOIN) {
447 // ignore "Join" messages
448 logger("Ignore join message ".print_r($item, true), LOGGER_DEBUG);
452 if ($item["verb"] == "http://mastodon.social/schema/1.0/block") {
453 // ignore mastodon "block" messages
454 logger("Ignore block message ".print_r($item, true), LOGGER_DEBUG);
458 if ($item["verb"] == ACTIVITY_FOLLOW) {
459 Contact::addRelationship($importer, $contact, $item, $nickname);
463 if ($item["verb"] == NAMESPACE_OSTATUS."/unfollow") {
464 Contact::removeFollower($importer, $contact, $item, $dummy);
468 if ($item["verb"] == ACTIVITY_FAVORITE) {
469 $orig_uri = $xpath->query("activity:object/atom:id", $entry)->item(0)->nodeValue;
470 logger("Favorite ".$orig_uri." ".print_r($item, true));
472 $item["verb"] = ACTIVITY_LIKE;
473 $item["parent-uri"] = $orig_uri;
474 $item["gravity"] = GRAVITY_LIKE;
477 // http://activitystrea.ms/schema/1.0/rsvp-yes
478 if (!in_array($item["verb"], [ACTIVITY_POST, ACTIVITY_LIKE, ACTIVITY_SHARE])) {
479 logger("Unhandled verb ".$item["verb"]." ".print_r($item, true), LOGGER_DEBUG);
482 self::processPost($xpath, $entry, $item, $importer);
484 if ($initialize && (count(self::$itemlist) > 0)) {
485 if (self::$itemlist[0]['uri'] == self::$itemlist[0]['parent-uri']) {
486 // We will import it everytime, when it is started by our contacts
487 $valid = !empty(self::$itemlist[0]['contact-id']);
489 // If not, then it depends on this setting
490 $valid = !Config::get('system', 'ostatus_full_threads');
493 // Never post a thread when the only interaction by our contact was a like
495 $verbs = [ACTIVITY_POST, ACTIVITY_SHARE];
496 foreach (self::$itemlist as $item) {
497 if (!empty($item['contact-id']) && in_array($item['verb'], $verbs)) {
503 // But we will only import complete threads
504 $valid = dba::exists('item', ['uid' => $importer["uid"], 'uri' => self::$itemlist[0]['parent-uri']]);
508 $default_contact = 0;
509 $key = count(self::$itemlist);
510 for ($key = count(self::$itemlist) - 1; $key >= 0; $key--) {
511 if (empty(self::$itemlist[$key]['contact-id'])) {
512 self::$itemlist[$key]['contact-id'] = $default_contact;
514 $default_contact = $item['contact-id'];
517 foreach (self::$itemlist as $item) {
518 $found = dba::exists('item', ['uid' => $importer["uid"], 'uri' => $item["uri"]]);
520 logger("Item with uri ".$item["uri"]." for user ".$importer["uid"]." already exists.", LOGGER_DEBUG);
521 } elseif ($item['contact-id'] < 0) {
522 logger("Item with uri ".$item["uri"]." is from a blocked contact.", LOGGER_DEBUG);
524 // We are having duplicated entries. Hopefully this solves it.
525 if (Lock::set('ostatus_process_item_insert')) {
526 $ret = Item::insert($item);
527 Lock::remove('ostatus_process_item_insert');
528 logger("Item with uri ".$item["uri"]." for user ".$importer["uid"].' stored. Return value: '.$ret);
530 $ret = Item::insert($item);
531 logger("We couldn't lock - but tried to store the item anyway. Return value is ".$ret);
536 self::$itemlist = [];
538 logger('Processing done for post with URI '.$item["uri"].' for user '.$importer["uid"].'.', LOGGER_DEBUG);
544 * @param object $item item
547 private static function deleteNotice($item)
549 $condition = ['uid' => $item['uid'], 'author-link' => $item['author-link'], 'uri' => $item['uri']];
550 $deleted = dba::selectFirst('item', ['id', 'parent-uri'], $condition);
551 if (!DBM::is_result($deleted)) {
552 logger('Item from '.$item['author-link'].' with uri '.$item['uri'].' for user '.$item['uid']." wasn't found. We don't delete it. ");
556 // Currently we don't have a central deletion function that we could use in this case
557 // The function "item_drop" doesn't work for that case
560 ['deleted' => true, 'title' => '', 'body' => '',
561 'edited' => DateTimeFormat::utcNow(), 'changed' => DateTimeFormat::utcNow()],
562 ['id' => $deleted["id"]]
565 delete_thread($deleted["id"], $deleted["parent-uri"]);
567 logger('Deleted item with uri '.$item['uri'].' for user '.$item['uid']);
571 * @brief Processes the XML for a post
573 * @param object $xpath The xpath object
574 * @param object $entry The xml entry that is processed
575 * @param array $item The item array
576 * @param array $importer user record of the importing user
579 private static function processPost($xpath, $entry, &$item, $importer)
581 $item["body"] = html2bbcode($xpath->query('atom:content/text()', $entry)->item(0)->nodeValue);
582 $item["object-type"] = $xpath->query('activity:object-type/text()', $entry)->item(0)->nodeValue;
583 if (($item["object-type"] == ACTIVITY_OBJ_BOOKMARK) || ($item["object-type"] == ACTIVITY_OBJ_EVENT)) {
584 $item["title"] = $xpath->query('atom:title/text()', $entry)->item(0)->nodeValue;
585 $item["body"] = $xpath->query('atom:summary/text()', $entry)->item(0)->nodeValue;
586 } elseif ($item["object-type"] == ACTIVITY_OBJ_QUESTION) {
587 $item["title"] = $xpath->query('atom:title/text()', $entry)->item(0)->nodeValue;
590 $item["created"] = $xpath->query('atom:published/text()', $entry)->item(0)->nodeValue;
591 $item["edited"] = $xpath->query('atom:updated/text()', $entry)->item(0)->nodeValue;
592 $conversation = $xpath->query('ostatus:conversation/text()', $entry)->item(0)->nodeValue;
593 $item['conversation-uri'] = $conversation;
595 $conv = $xpath->query('ostatus:conversation', $entry);
596 if (is_object($conv->item(0))) {
597 foreach ($conv->item(0)->attributes as $attributes) {
598 if ($attributes->name == "ref") {
599 $item['conversation-uri'] = $attributes->textContent;
601 if ($attributes->name == "href") {
602 $item['conversation-href'] = $attributes->textContent;
609 $inreplyto = $xpath->query('thr:in-reply-to', $entry);
610 if (is_object($inreplyto->item(0))) {
611 foreach ($inreplyto->item(0)->attributes as $attributes) {
612 if ($attributes->name == "ref") {
613 $item["parent-uri"] = $attributes->textContent;
615 if ($attributes->name == "href") {
616 $related = $attributes->textContent;
621 $georsspoint = $xpath->query('georss:point', $entry);
622 if (!empty($georsspoint) && ($georsspoint->length > 0)) {
623 $item["coord"] = $georsspoint->item(0)->nodeValue;
626 $categories = $xpath->query('atom:category', $entry);
628 foreach ($categories as $category) {
629 foreach ($category->attributes as $attributes) {
630 if ($attributes->name == "term") {
631 $term = $attributes->textContent;
632 if (strlen($item["tag"])) {
635 $item["tag"] .= "#[url=".System::baseUrl()."/search?tag=".$term."]".$term."[/url]";
644 $links = $xpath->query('atom:link', $entry);
646 $link_data = self::processLinks($links, $item);
647 $self = $link_data['self'];
648 $add_body = $link_data['add_body'];
653 $notice_info = $xpath->query('statusnet:notice_info', $entry);
654 if ($notice_info && ($notice_info->length > 0)) {
655 foreach ($notice_info->item(0)->attributes as $attributes) {
656 if ($attributes->name == "source") {
657 $item["app"] = strip_tags($attributes->textContent);
659 if ($attributes->name == "repeat_of") {
660 $repeat_of = $attributes->textContent;
664 // Is it a repeated post?
665 if (($repeat_of != "") || ($item["verb"] == ACTIVITY_SHARE)) {
666 $link_data = self::processRepeatedItem($xpath, $entry, $item, $importer);
667 if (!empty($link_data['add_body'])) {
668 $add_body .= $link_data['add_body'];
672 $item["body"] .= $add_body;
674 // Only add additional data when there is no picture in the post
675 if (!strstr($item["body"], '[/img]')) {
676 $item["body"] = add_page_info_to_body($item["body"]);
679 // Mastodon Content Warning
680 if (($item["verb"] == ACTIVITY_POST) && $xpath->evaluate('boolean(atom:summary)', $entry)) {
681 $clear_text = $xpath->query('atom:summary/text()', $entry)->item(0)->nodeValue;
683 $item["body"] = html2bbcode($clear_text) . '[spoiler]' . $item["body"] . '[/spoiler]';
686 if (($self != '') && empty($item['protocol'])) {
687 self::fetchSelf($self, $item);
690 if (!empty($item["conversation-href"])) {
691 self::fetchConversation($item['conversation-href'], $item['conversation-uri']);
694 if (isset($item["parent-uri"]) && ($related != '')) {
695 if (!dba::exists('item', ['uid' => $importer["uid"], 'uri' => $item['parent-uri']])) {
696 self::fetchRelated($related, $item["parent-uri"], $importer);
698 logger('Reply with URI '.$item["uri"].' already existed for user '.$importer["uid"].'.', LOGGER_DEBUG);
701 $item["type"] = 'remote-comment';
702 $item["gravity"] = GRAVITY_COMMENT;
704 $item["parent-uri"] = $item["uri"];
707 if (($item['author-link'] != '') && !empty($item['protocol'])) {
708 $item = Conversation::insert($item);
711 self::$itemlist[] = $item;
715 * @brief Fetch the conversation for posts
717 * @param string $conversation The link to the conversation
718 * @param string $conversation_uri The conversation in "uri" format
721 private static function fetchConversation($conversation, $conversation_uri)
723 // Ensure that we only store a conversation once in a process
724 if (isset(self::$conv_list[$conversation])) {
728 self::$conv_list[$conversation] = true;
730 $conversation_data = Network::curl($conversation, false, $redirects, ['accept_content' => 'application/atom+xml, text/html']);
732 if (!$conversation_data['success']) {
738 if (stristr($conversation_data['header'], 'Content-Type: application/atom+xml')) {
739 $xml = $conversation_data['body'];
743 $doc = new DOMDocument();
744 if (!@$doc->loadHTML($conversation_data['body'])) {
747 $xpath = new DOMXPath($doc);
749 $links = $xpath->query('//link');
751 foreach ($links as $link) {
752 $attribute = self::readAttributes($link);
753 if (($attribute['rel'] == 'alternate') && ($attribute['type'] == 'application/atom+xml')) {
754 $file = $attribute['href'];
758 $conversation_atom = Network::curl($attribute['href']);
760 if ($conversation_atom['success']) {
761 $xml = $conversation_atom['body'];
771 self::storeConversation($xml, $conversation, $conversation_uri);
775 * @brief Store a feed in several conversation entries
777 * @param string $xml The feed
778 * @param string $conversation conversation
779 * @param string $conversation_uri conversation uri
782 private static function storeConversation($xml, $conversation = '', $conversation_uri = '')
784 $doc = new DOMDocument();
785 @$doc->loadXML($xml);
787 $xpath = new DOMXPath($doc);
788 $xpath->registerNamespace('atom', NAMESPACE_ATOM1);
789 $xpath->registerNamespace('thr', NAMESPACE_THREAD);
790 $xpath->registerNamespace('ostatus', NAMESPACE_OSTATUS);
792 $entries = $xpath->query('/atom:feed/atom:entry');
794 // Now store the entries
795 foreach ($entries as $entry) {
796 $doc2 = new DOMDocument();
797 $doc2->preserveWhiteSpace = false;
798 $doc2->formatOutput = true;
802 $conv_data['protocol'] = PROTOCOL_SPLITTED_CONV;
803 $conv_data['network'] = NETWORK_OSTATUS;
804 $conv_data['uri'] = $xpath->query('atom:id/text()', $entry)->item(0)->nodeValue;
806 $inreplyto = $xpath->query('thr:in-reply-to', $entry);
807 if (is_object($inreplyto->item(0))) {
808 foreach ($inreplyto->item(0)->attributes as $attributes) {
809 if ($attributes->name == "ref") {
810 $conv_data['reply-to-uri'] = $attributes->textContent;
815 $conv = $xpath->query('ostatus:conversation/text()', $entry)->item(0)->nodeValue;
816 $conv_data['conversation-uri'] = $conv;
818 $conv = $xpath->query('ostatus:conversation', $entry);
819 if (is_object($conv->item(0))) {
820 foreach ($conv->item(0)->attributes as $attributes) {
821 if ($attributes->name == "ref") {
822 $conv_data['conversation-uri'] = $attributes->textContent;
824 if ($attributes->name == "href") {
825 $conv_data['conversation-href'] = $attributes->textContent;
830 if ($conversation != '') {
831 $conv_data['conversation-uri'] = $conversation;
834 if ($conversation_uri != '') {
835 $conv_data['conversation-uri'] = $conversation_uri;
838 $entry = $doc2->importNode($entry, true);
840 $doc2->appendChild($entry);
842 $conv_data['source'] = $doc2->saveXML();
844 $condition = ['item-uri' => $conv_data['uri'],'protocol' => PROTOCOL_OSTATUS_FEED];
845 if (dba::exists('conversation', $condition)) {
846 logger('Delete deprecated entry for URI '.$conv_data['uri'], LOGGER_DEBUG);
847 dba::delete('conversation', ['item-uri' => $conv_data['uri']]);
850 logger('Store conversation data for uri '.$conv_data['uri'], LOGGER_DEBUG);
851 Conversation::insert($conv_data);
856 * @brief Fetch the own post so that it can be stored later
858 * We want to store the original data for later processing.
859 * This function is meant for cases where we process a feed with multiple entries.
860 * In that case we need to fetch the single posts here.
862 * @param string $self The link to the self item
863 * @param array $item The item array
866 private static function fetchSelf($self, &$item)
868 $condition = ['`item-uri` = ? AND `protocol` IN (?, ?)', $self, PROTOCOL_DFRN, PROTOCOL_OSTATUS_SALMON];
869 if (dba::exists('conversation', $condition)) {
870 logger('Conversation '.$item['uri'].' is already stored.', LOGGER_DEBUG);
874 $self_data = Network::curl($self);
876 if (!$self_data['success']) {
880 // We reformat the XML to make it better readable
881 $doc = new DOMDocument();
882 $doc->loadXML($self_data['body']);
883 $doc->preserveWhiteSpace = false;
884 $doc->formatOutput = true;
885 $xml = $doc->saveXML();
887 $item["protocol"] = PROTOCOL_OSTATUS_SALMON;
888 $item["source"] = $xml;
890 logger('Conversation '.$item['uri'].' is now fetched.', LOGGER_DEBUG);
894 * @brief Fetch related posts and processes them
896 * @param string $related The link to the related item
897 * @param string $related_uri The related item in "uri" format
898 * @param array $importer user record of the importing user
901 private static function fetchRelated($related, $related_uri, $importer)
903 $condition = ['`item-uri` = ? AND `protocol` IN (?, ?)', $related_uri, PROTOCOL_DFRN, PROTOCOL_OSTATUS_SALMON];
904 $conversation = dba::selectFirst('conversation', ['source', 'protocol'], $condition);
905 if (DBM::is_result($conversation)) {
907 $xml = $conversation['source'];
908 if (self::process($xml, $importer, $contact, $hub, $stored, false)) {
909 logger('Got valid cached XML for URI '.$related_uri, LOGGER_DEBUG);
912 if ($conversation['protocol'] == PROTOCOL_OSTATUS_SALMON) {
913 logger('Delete invalid cached XML for URI '.$related_uri, LOGGER_DEBUG);
914 dba::delete('conversation', ['item-uri' => $related_uri]);
919 $related_data = Network::curl($related, false, $redirects, ['accept_content' => 'application/atom+xml, text/html']);
921 if (!$related_data['success']) {
927 if (stristr($related_data['header'], 'Content-Type: application/atom+xml')) {
928 logger('Directly fetched XML for URI '.$related_uri, LOGGER_DEBUG);
929 $xml = $related_data['body'];
933 $doc = new DOMDocument();
934 if (!@$doc->loadHTML($related_data['body'])) {
937 $xpath = new DOMXPath($doc);
941 $links = $xpath->query('//link');
943 foreach ($links as $link) {
944 $attribute = self::readAttributes($link);
945 if (($attribute['rel'] == 'alternate') && ($attribute['type'] == 'application/atom+xml')) {
946 $atom_file = $attribute['href'];
949 if ($atom_file != '') {
950 $related_atom = Network::curl($atom_file);
952 if ($related_atom['success']) {
953 logger('Fetched XML for URI '.$related_uri, LOGGER_DEBUG);
954 $xml = $related_atom['body'];
960 // Workaround for older GNU Social servers
961 if (($xml == '') && strstr($related, '/notice/')) {
962 $related_atom = Network::curl(str_replace('/notice/', '/api/statuses/show/', $related).'.atom');
964 if ($related_atom['success']) {
965 logger('GNU Social workaround to fetch XML for URI '.$related_uri, LOGGER_DEBUG);
966 $xml = $related_atom['body'];
970 // Even more worse workaround for GNU Social ;-)
972 $related_guess = OStatus::convertHref($related_uri);
973 $related_atom = Network::curl(str_replace('/notice/', '/api/statuses/show/', $related_guess).'.atom');
975 if ($related_atom['success']) {
976 logger('GNU Social workaround 2 to fetch XML for URI '.$related_uri, LOGGER_DEBUG);
977 $xml = $related_atom['body'];
981 // Finally we take the data that we fetched from "ostatus:conversation"
983 $condition = ['item-uri' => $related_uri, 'protocol' => PROTOCOL_SPLITTED_CONV];
984 $conversation = dba::selectFirst('conversation', ['source'], $condition);
985 if (DBM::is_result($conversation)) {
987 logger('Got cached XML from conversation for URI '.$related_uri, LOGGER_DEBUG);
988 $xml = $conversation['source'];
993 self::process($xml, $importer, $contact, $hub, $stored, false);
995 logger("XML couldn't be fetched for URI: ".$related_uri." - href: ".$related, LOGGER_DEBUG);
1001 * @brief Processes the XML for a repeated post
1003 * @param object $xpath The xpath object
1004 * @param object $entry The xml entry that is processed
1005 * @param array $item The item array
1006 * @param array $importer user record of the importing user
1008 * @return array with data from links
1010 private static function processRepeatedItem($xpath, $entry, &$item, $importer)
1012 $activityobjects = $xpath->query('activity:object', $entry)->item(0);
1014 if (!is_object($activityobjects)) {
1020 $orig_uri = $xpath->query('atom:id/text()', $activityobjects)->item(0)->nodeValue;
1022 $links = $xpath->query("atom:link", $activityobjects);
1024 $link_data = self::processLinks($links, $item);
1027 $orig_body = $xpath->query('atom:content/text()', $activityobjects)->item(0)->nodeValue;
1028 $orig_created = $xpath->query('atom:published/text()', $activityobjects)->item(0)->nodeValue;
1029 $orig_edited = $xpath->query('atom:updated/text()', $activityobjects)->item(0)->nodeValue;
1031 $orig_author = self::fetchAuthor($xpath, $activityobjects, $importer, $dummy, false);
1033 $item["author-name"] = $orig_author["author-name"];
1034 $item["author-link"] = $orig_author["author-link"];
1035 $item["author-avatar"] = $orig_author["author-avatar"];
1037 $item["body"] = html2bbcode($orig_body);
1038 $item["created"] = $orig_created;
1039 $item["edited"] = $orig_edited;
1041 $item["uri"] = $orig_uri;
1043 $item["verb"] = $xpath->query('activity:verb/text()', $activityobjects)->item(0)->nodeValue;
1045 $item["object-type"] = $xpath->query('activity:object-type/text()', $activityobjects)->item(0)->nodeValue;
1047 $inreplyto = $xpath->query('thr:in-reply-to', $activityobjects);
1048 if (is_object($inreplyto->item(0))) {
1049 foreach ($inreplyto->item(0)->attributes as $attributes) {
1050 if ($attributes->name == "ref") {
1051 $item["parent-uri"] = $attributes->textContent;
1060 * @brief Processes links in the XML
1062 * @param object $links The xml data that contain links
1063 * @param array $item The item array
1065 * @return array with data from the links
1067 private static function processLinks($links, &$item)
1069 $link_data = ['add_body' => '', 'self' => ''];
1071 foreach ($links as $link) {
1072 $attribute = self::readAttributes($link);
1074 if (($attribute['rel'] != "") && ($attribute['href'] != "")) {
1075 switch ($attribute['rel']) {
1077 $item["plink"] = $attribute['href'];
1078 if (($item["object-type"] == ACTIVITY_OBJ_QUESTION)
1079 || ($item["object-type"] == ACTIVITY_OBJ_EVENT)
1081 $item["body"] .= add_page_info($attribute['href']);
1084 case "ostatus:conversation":
1085 $link_data['conversation'] = $attribute['href'];
1086 $item['conversation-href'] = $link_data['conversation'];
1087 if (!isset($item['conversation-uri'])) {
1088 $item['conversation-uri'] = $item['conversation-href'];
1092 $filetype = strtolower(substr($attribute['type'], 0, strpos($attribute['type'], '/')));
1093 if ($filetype == 'image') {
1094 $link_data['add_body'] .= "\n[img]".$attribute['href'].'[/img]';
1096 if (strlen($item["attach"])) {
1097 $item["attach"] .= ',';
1099 if (!isset($attribute['length'])) {
1100 $attribute['length'] = "0";
1102 $item["attach"] .= '[attach]href="'.$attribute['href'].'" length="'.$attribute['length'].'" type="'.$attribute['type'].'" title="'.$attribute['title'].'"[/attach]';
1106 if ($item["object-type"] != ACTIVITY_OBJ_BOOKMARK) {
1107 if (!isset($item["parent-uri"])) {
1108 $item["parent-uri"] = $attribute['href'];
1110 $link_data['related'] = $attribute['href'];
1112 $item["body"] .= add_page_info($attribute['href']);
1116 if ($item["plink"] == '') {
1117 $item["plink"] = $attribute['href'];
1119 $link_data['self'] = $attribute['href'];
1128 * @brief Create an url out of an uri
1130 * @param string $href URI in the format "parameter1:parameter1:..."
1132 * @return string URL in the format http(s)://....
1134 public static function convertHref($href)
1136 $elements = explode(":", $href);
1138 if ((count($elements) <= 2) || ($elements[0] != "tag")) {
1142 $server = explode(",", $elements[1]);
1143 $conversation = explode("=", $elements[2]);
1145 if ((count($elements) == 4) && ($elements[2] == "post")) {
1146 return "http://".$server[0]."/notice/".$elements[3];
1149 if ((count($conversation) != 2) || ($conversation[1] =="")) {
1152 if ($elements[3] == "objectType=thread") {
1153 return "http://".$server[0]."/conversation/".$conversation[1];
1155 return "http://".$server[0]."/notice/".$conversation[1];
1161 * @brief Checks if the current post is a reshare
1163 * @param array $item The item array of thw post
1165 * @return string The guid if the post is a reshare
1167 private static function getResharedGuid($item)
1169 $body = trim($item["body"]);
1171 // Skip if it isn't a pure repeated messages
1172 // Does it start with a share?
1173 if (strpos($body, "[share") > 0) {
1177 // Does it end with a share?
1178 if (strlen($body) > (strrpos($body, "[/share]") + 8)) {
1182 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "$1", $body);
1183 // Skip if there is no shared message in there
1184 if ($body == $attributes) {
1189 preg_match("/guid='(.*?)'/ism", $attributes, $matches);
1190 if ($matches[1] != "") {
1191 $guid = $matches[1];
1194 preg_match('/guid="(.*?)"/ism', $attributes, $matches);
1195 if ($matches[1] != "") {
1196 $guid = $matches[1];
1203 * @brief Cleans the body of a post if it contains picture links
1205 * @param string $body The body
1207 * @return string The cleaned body
1209 private static function formatPicturePost($body)
1211 $siteinfo = BBCode::getAttachedData($body);
1213 if (($siteinfo["type"] == "photo")) {
1214 if (isset($siteinfo["preview"])) {
1215 $preview = $siteinfo["preview"];
1217 $preview = $siteinfo["image"];
1220 // Is it a remote picture? Then make a smaller preview here
1221 $preview = proxy_url($preview, false, PROXY_SIZE_SMALL);
1223 // Is it a local picture? Then make it smaller here
1224 $preview = str_replace(["-0.jpg", "-0.png"], ["-2.jpg", "-2.png"], $preview);
1225 $preview = str_replace(["-1.jpg", "-1.png"], ["-2.jpg", "-2.png"], $preview);
1227 if (isset($siteinfo["url"])) {
1228 $url = $siteinfo["url"];
1230 $url = $siteinfo["image"];
1233 $body = trim($siteinfo["text"])." [url]".$url."[/url]\n[img]".$preview."[/img]";
1240 * @brief Adds the header elements to the XML document
1242 * @param object $doc XML document
1243 * @param array $owner Contact data of the poster
1244 * @param string $filter The related feed filter (activity, posts or comments)
1246 * @return object header root element
1248 private static function addHeader($doc, $owner, $filter)
1252 $root = $doc->createElementNS(NAMESPACE_ATOM1, 'feed');
1253 $doc->appendChild($root);
1255 $root->setAttribute("xmlns:thr", NAMESPACE_THREAD);
1256 $root->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
1257 $root->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
1258 $root->setAttribute("xmlns:media", NAMESPACE_MEDIA);
1259 $root->setAttribute("xmlns:poco", NAMESPACE_POCO);
1260 $root->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
1261 $root->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
1262 $root->setAttribute("xmlns:mastodon", NAMESPACE_MASTODON);
1265 case 'activity': $title = L10n::t('%s\'s timeline', $owner['name']); break;
1266 case 'posts' : $title = L10n::t('%s\'s posts' , $owner['name']); break;
1267 case 'comments': $title = L10n::t('%s\'s comments', $owner['name']); break;
1270 $attributes = ["uri" => "https://friendi.ca", "version" => FRIENDICA_VERSION . "-" . DB_UPDATE_VERSION];
1271 XML::addElement($doc, $root, "generator", FRIENDICA_PLATFORM, $attributes);
1272 XML::addElement($doc, $root, "id", System::baseUrl() . "/profile/" . $owner["nick"]);
1273 XML::addElement($doc, $root, "title", $title);
1274 XML::addElement($doc, $root, "subtitle", sprintf("Updates from %s on %s", $owner["name"], $a->config["sitename"]));
1275 XML::addElement($doc, $root, "logo", $owner["photo"]);
1276 XML::addElement($doc, $root, "updated", DateTimeFormat::utcNow(DateTimeFormat::ATOM));
1278 $author = self::addAuthor($doc, $owner);
1279 $root->appendChild($author);
1281 $attributes = ["href" => $owner["url"], "rel" => "alternate", "type" => "text/html"];
1282 XML::addElement($doc, $root, "link", "", $attributes);
1284 /// @TODO We have to find out what this is
1285 /// $attributes = array("href" => System::baseUrl()."/sup",
1286 /// "rel" => "http://api.friendfeed.com/2008/03#sup",
1287 /// "type" => "application/json");
1288 /// XML::addElement($doc, $root, "link", "", $attributes);
1290 self::hublinks($doc, $root, $owner["nick"]);
1292 $attributes = ["href" => System::baseUrl() . "/salmon/" . $owner["nick"], "rel" => "salmon"];
1293 XML::addElement($doc, $root, "link", "", $attributes);
1295 $attributes = ["href" => System::baseUrl() . "/salmon/" . $owner["nick"], "rel" => "http://salmon-protocol.org/ns/salmon-replies"];
1296 XML::addElement($doc, $root, "link", "", $attributes);
1298 $attributes = ["href" => System::baseUrl() . "/salmon/" . $owner["nick"], "rel" => "http://salmon-protocol.org/ns/salmon-mention"];
1299 XML::addElement($doc, $root, "link", "", $attributes);
1301 $attributes = ["href" => System::baseUrl() . "/api/statuses/user_timeline/" . $owner["nick"] . ".atom",
1302 "rel" => "self", "type" => "application/atom+xml"];
1303 XML::addElement($doc, $root, "link", "", $attributes);
1309 * @brief Add the link to the push hubs to the XML document
1311 * @param object $doc XML document
1312 * @param object $root XML root element where the hub links are added
1313 * @param object $nick nick
1316 public static function hublinks($doc, $root, $nick)
1318 $h = System::baseUrl() . '/pubsubhubbub/'.$nick;
1319 XML::addElement($doc, $root, "link", "", ["href" => $h, "rel" => "hub"]);
1323 * @brief Adds attachement data to the XML document
1325 * @param object $doc XML document
1326 * @param object $root XML root element where the hub links are added
1327 * @param array $item Data of the item that is to be posted
1330 private static function getAttachment($doc, $root, $item)
1333 $siteinfo = BBCode::getAttachedData($item["body"]);
1335 switch ($siteinfo["type"]) {
1337 $imgdata = Image::getInfoFromURL($siteinfo["image"]);
1338 $attributes = ["rel" => "enclosure",
1339 "href" => $siteinfo["image"],
1340 "type" => $imgdata["mime"],
1341 "length" => intval($imgdata["size"])];
1342 XML::addElement($doc, $root, "link", "", $attributes);
1345 $attributes = ["rel" => "enclosure",
1346 "href" => $siteinfo["url"],
1347 "type" => "text/html; charset=UTF-8",
1349 "title" => $siteinfo["title"]];
1350 XML::addElement($doc, $root, "link", "", $attributes);
1356 if (!Config::get('system', 'ostatus_not_attach_preview') && ($siteinfo["type"] != "photo") && isset($siteinfo["image"])) {
1357 $imgdata = Image::getInfoFromURL($siteinfo["image"]);
1358 $attributes = ["rel" => "enclosure",
1359 "href" => $siteinfo["image"],
1360 "type" => $imgdata["mime"],
1361 "length" => intval($imgdata["size"])];
1363 XML::addElement($doc, $root, "link", "", $attributes);
1366 $arr = explode('[/attach],', $item['attach']);
1368 foreach ($arr as $r) {
1370 $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"|', $r, $matches);
1372 $attributes = ["rel" => "enclosure",
1373 "href" => $matches[1],
1374 "type" => $matches[3]];
1376 if (intval($matches[2])) {
1377 $attributes["length"] = intval($matches[2]);
1379 if (trim($matches[4]) != "") {
1380 $attributes["title"] = trim($matches[4]);
1382 XML::addElement($doc, $root, "link", "", $attributes);
1389 * @brief Adds the author element to the XML document
1391 * @param object $doc XML document
1392 * @param array $owner Contact data of the poster
1394 * @return object author element
1396 private static function addAuthor($doc, $owner)
1398 $r = q("SELECT `homepage`, `publish` FROM `profile` WHERE `uid` = %d AND `is-default` LIMIT 1", intval($owner["uid"]));
1399 if (DBM::is_result($r)) {
1402 $author = $doc->createElement("author");
1403 XML::addElement($doc, $author, "id", $owner["url"]);
1404 XML::addElement($doc, $author, "activity:object-type", ACTIVITY_OBJ_PERSON);
1405 XML::addElement($doc, $author, "uri", $owner["url"]);
1406 XML::addElement($doc, $author, "name", $owner["nick"]);
1407 XML::addElement($doc, $author, "email", $owner["addr"]);
1408 XML::addElement($doc, $author, "summary", bbcode($owner["about"], false, false, 7));
1410 $attributes = ["rel" => "alternate", "type" => "text/html", "href" => $owner["url"]];
1411 XML::addElement($doc, $author, "link", "", $attributes);
1415 "type" => "image/jpeg", // To-Do?
1416 "media:width" => 175,
1417 "media:height" => 175,
1418 "href" => $owner["photo"]];
1419 XML::addElement($doc, $author, "link", "", $attributes);
1421 if (isset($owner["thumb"])) {
1424 "type" => "image/jpeg", // To-Do?
1425 "media:width" => 80,
1426 "media:height" => 80,
1427 "href" => $owner["thumb"]];
1428 XML::addElement($doc, $author, "link", "", $attributes);
1431 XML::addElement($doc, $author, "poco:preferredUsername", $owner["nick"]);
1432 XML::addElement($doc, $author, "poco:displayName", $owner["name"]);
1433 XML::addElement($doc, $author, "poco:note", bbcode($owner["about"], false, false, 7));
1435 if (trim($owner["location"]) != "") {
1436 $element = $doc->createElement("poco:address");
1437 XML::addElement($doc, $element, "poco:formatted", $owner["location"]);
1438 $author->appendChild($element);
1441 if (trim($profile["homepage"]) != "") {
1442 $urls = $doc->createElement("poco:urls");
1443 XML::addElement($doc, $urls, "poco:type", "homepage");
1444 XML::addElement($doc, $urls, "poco:value", $profile["homepage"]);
1445 XML::addElement($doc, $urls, "poco:primary", "true");
1446 $author->appendChild($urls);
1449 if (count($profile)) {
1450 XML::addElement($doc, $author, "followers", "", ["url" => System::baseUrl()."/viewcontacts/".$owner["nick"]]);
1451 XML::addElement($doc, $author, "statusnet:profile_info", "", ["local_id" => $owner["uid"]]);
1454 if ($profile["publish"]) {
1455 XML::addElement($doc, $author, "mastodon:scope", "public");
1461 * @TODO Picture attachments should look like this:
1462 * <a href="https://status.pirati.ca/attachment/572819" title="https://status.pirati.ca/file/heluecht-20151202T222602-rd3u49p.gif"
1463 * class="attachment thumbnail" id="attachment-572819" rel="nofollow external">https://status.pirati.ca/attachment/572819</a>
1467 * @brief Returns the given activity if present - otherwise returns the "post" activity
1469 * @param array $item Data of the item that is to be posted
1471 * @return string activity
1473 private static function constructVerb($item)
1475 if ($item['verb']) {
1476 return $item['verb'];
1479 return ACTIVITY_POST;
1483 * @brief Returns the given object type if present - otherwise returns the "note" object type
1485 * @param array $item Data of the item that is to be posted
1487 * @return string Object type
1489 private static function constructObjecttype($item)
1491 if (in_array($item['object-type'], [ACTIVITY_OBJ_NOTE, ACTIVITY_OBJ_COMMENT]))
1492 return $item['object-type'];
1493 return ACTIVITY_OBJ_NOTE;
1497 * @brief Adds an entry element to the XML document
1499 * @param object $doc XML document
1500 * @param array $item Data of the item that is to be posted
1501 * @param array $owner Contact data of the poster
1502 * @param bool $toplevel optional default false
1504 * @return object Entry element
1506 private static function entry($doc, $item, $owner, $toplevel = false)
1508 $repeated_guid = self::getResharedGuid($item);
1509 if ($repeated_guid != "") {
1510 $xml = self::reshareEntry($doc, $item, $owner, $repeated_guid, $toplevel);
1517 if ($item["verb"] == ACTIVITY_LIKE) {
1518 return self::likeEntry($doc, $item, $owner, $toplevel);
1519 } elseif (in_array($item["verb"], [ACTIVITY_FOLLOW, NAMESPACE_OSTATUS."/unfollow"])) {
1520 return self::followEntry($doc, $item, $owner, $toplevel);
1522 return self::noteEntry($doc, $item, $owner, $toplevel);
1527 * @brief Adds a source entry to the XML document
1529 * @param object $doc XML document
1530 * @param array $contact Array of the contact that is added
1532 * @return object Source element
1534 private static function sourceEntry($doc, $contact)
1536 $source = $doc->createElement("source");
1537 XML::addElement($doc, $source, "id", $contact["poll"]);
1538 XML::addElement($doc, $source, "title", $contact["name"]);
1539 XML::addElement($doc, $source, "link", "", ["rel" => "alternate", "type" => "text/html", "href" => $contact["alias"]]);
1540 XML::addElement($doc, $source, "link", "", ["rel" => "self", "type" => "application/atom+xml", "href" => $contact["poll"]]);
1541 XML::addElement($doc, $source, "icon", $contact["photo"]);
1542 XML::addElement($doc, $source, "updated", DateTimeFormat::utc($contact["success_update"]."+00:00", DateTimeFormat::ATOM));
1548 * @brief Fetches contact data from the contact or the gcontact table
1550 * @param string $url URL of the contact
1551 * @param array $owner Contact data of the poster
1553 * @return array Contact array
1555 private static function contactEntry($url, $owner)
1558 "SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` IN (0, %d) ORDER BY `uid` DESC LIMIT 1",
1559 dbesc(normalise_link($url)),
1560 intval($owner["uid"])
1562 if (DBM::is_result($r)) {
1564 $contact["uid"] = -1;
1567 if (!DBM::is_result($r)) {
1569 "SELECT * FROM `gcontact` WHERE `nurl` = '%s' LIMIT 1",
1570 dbesc(normalise_link($url))
1572 if (DBM::is_result($r)) {
1574 $contact["uid"] = -1;
1575 $contact["success_update"] = $contact["updated"];
1579 if (!DBM::is_result($r)) {
1583 if (!isset($contact["poll"])) {
1584 $data = Probe::uri($url);
1585 $contact["poll"] = $data["poll"];
1587 if (!$contact["alias"]) {
1588 $contact["alias"] = $data["alias"];
1592 if (!isset($contact["alias"])) {
1593 $contact["alias"] = $contact["url"];
1600 * @brief Adds an entry element with reshared content
1602 * @param object $doc XML document
1603 * @param array $item Data of the item that is to be posted
1604 * @param array $owner Contact data of the poster
1605 * @param string $repeated_guid guid
1606 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1608 * @return object Entry element
1610 private static function reshareEntry($doc, $item, $owner, $repeated_guid, $toplevel)
1612 if (($item["id"] != $item["parent"]) && (normalise_link($item["author-link"]) != normalise_link($owner["url"]))) {
1613 logger("OStatus entry is from author ".$owner["url"]." - not from ".$item["author-link"].". Quitting.", LOGGER_DEBUG);
1616 $title = self::entryHeader($doc, $entry, $owner, $toplevel);
1619 "SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' AND NOT `private` AND `network` IN ('%s', '%s', '%s') LIMIT 1",
1620 intval($owner["uid"]),
1621 dbesc($repeated_guid),
1622 dbesc(NETWORK_DFRN),
1623 dbesc(NETWORK_DIASPORA),
1624 dbesc(NETWORK_OSTATUS)
1626 if (DBM::is_result($r)) {
1627 $repeated_item = $r[0];
1631 $contact = self::contactEntry($repeated_item['author-link'], $owner);
1633 $parent_item = (($item['thr-parent']) ? $item['thr-parent'] : $item['parent-uri']);
1635 $title = $owner["nick"]." repeated a notice by ".$contact["nick"];
1637 self::entryContent($doc, $entry, $item, $owner, $title, ACTIVITY_SHARE, false);
1639 $as_object = $doc->createElement("activity:object");
1641 XML::addElement($doc, $as_object, "activity:object-type", NAMESPACE_ACTIVITY_SCHEMA."activity");
1643 self::entryContent($doc, $as_object, $repeated_item, $owner, "", "", false);
1645 $author = self::addAuthor($doc, $contact);
1646 $as_object->appendChild($author);
1648 $as_object2 = $doc->createElement("activity:object");
1650 XML::addElement($doc, $as_object2, "activity:object-type", self::constructObjecttype($repeated_item));
1652 $title = sprintf("New comment by %s", $contact["nick"]);
1654 self::entryContent($doc, $as_object2, $repeated_item, $owner, $title);
1656 $as_object->appendChild($as_object2);
1658 self::entryFooter($doc, $as_object, $item, $owner, false);
1660 $source = self::sourceEntry($doc, $contact);
1662 $as_object->appendChild($source);
1664 $entry->appendChild($as_object);
1666 self::entryFooter($doc, $entry, $item, $owner);
1672 * @brief Adds an entry element with a "like"
1674 * @param object $doc XML document
1675 * @param array $item Data of the item that is to be posted
1676 * @param array $owner Contact data of the poster
1677 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1679 * @return object Entry element with "like"
1681 private static function likeEntry($doc, $item, $owner, $toplevel)
1683 if (($item["id"] != $item["parent"]) && (normalise_link($item["author-link"]) != normalise_link($owner["url"]))) {
1684 logger("OStatus entry is from author ".$owner["url"]." - not from ".$item["author-link"].". Quitting.", LOGGER_DEBUG);
1687 $title = self::entryHeader($doc, $entry, $owner, $toplevel);
1689 $verb = NAMESPACE_ACTIVITY_SCHEMA."favorite";
1690 self::entryContent($doc, $entry, $item, $owner, "Favorite", $verb, false);
1692 $as_object = $doc->createElement("activity:object");
1695 "SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d",
1696 dbesc($item["thr-parent"]),
1697 intval($item["uid"])
1699 $parent_item = (($item['thr-parent']) ? $item['thr-parent'] : $item['parent-uri']);
1701 XML::addElement($doc, $as_object, "activity:object-type", self::constructObjecttype($parent[0]));
1703 self::entryContent($doc, $as_object, $parent[0], $owner, "New entry");
1705 $entry->appendChild($as_object);
1707 self::entryFooter($doc, $entry, $item, $owner);
1713 * @brief Adds the person object element to the XML document
1715 * @param object $doc XML document
1716 * @param array $owner Contact data of the poster
1717 * @param array $contact Contact data of the target
1719 * @return object author element
1721 private static function addPersonObject($doc, $owner, $contact)
1723 $object = $doc->createElement("activity:object");
1724 XML::addElement($doc, $object, "activity:object-type", ACTIVITY_OBJ_PERSON);
1726 if ($contact['network'] == NETWORK_PHANTOM) {
1727 XML::addElement($doc, $object, "id", $contact['url']);
1731 XML::addElement($doc, $object, "id", $contact["alias"]);
1732 XML::addElement($doc, $object, "title", $contact["nick"]);
1734 $attributes = ["rel" => "alternate", "type" => "text/html", "href" => $contact["url"]];
1735 XML::addElement($doc, $object, "link", "", $attributes);
1739 "type" => "image/jpeg", // To-Do?
1740 "media:width" => 175,
1741 "media:height" => 175,
1742 "href" => $contact["photo"]];
1743 XML::addElement($doc, $object, "link", "", $attributes);
1745 XML::addElement($doc, $object, "poco:preferredUsername", $contact["nick"]);
1746 XML::addElement($doc, $object, "poco:displayName", $contact["name"]);
1748 if (trim($contact["location"]) != "") {
1749 $element = $doc->createElement("poco:address");
1750 XML::addElement($doc, $element, "poco:formatted", $contact["location"]);
1751 $object->appendChild($element);
1758 * @brief Adds a follow/unfollow entry element
1760 * @param object $doc XML document
1761 * @param array $item Data of the follow/unfollow message
1762 * @param array $owner Contact data of the poster
1763 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1765 * @return object Entry element
1767 private static function followEntry($doc, $item, $owner, $toplevel)
1769 $item["id"] = $item["parent"] = 0;
1770 $item["created"] = $item["edited"] = date("c");
1771 $item["private"] = true;
1773 $contact = Probe::uri($item['follow']);
1775 if ($contact['alias'] == '') {
1776 $contact['alias'] = $contact["url"];
1778 $item['follow'] = $contact['alias'];
1782 "SELECT `id` FROM `contact` WHERE `uid` = %d AND `nurl` = '%s'",
1783 intval($owner['uid']),
1784 dbesc(normalise_link($contact["url"]))
1787 if (DBM::is_result($r)) {
1788 $connect_id = $r[0]['id'];
1793 if ($item['verb'] == ACTIVITY_FOLLOW) {
1794 $message = L10n::t('%s is now following %s.');
1795 $title = L10n::t('following');
1796 $action = "subscription";
1798 $message = L10n::t('%s stopped following %s.');
1799 $title = L10n::t('stopped following');
1800 $action = "unfollow";
1803 $item["uri"] = $item['parent-uri'] = $item['thr-parent']
1804 = 'tag:'.get_app()->get_hostname().
1805 ','.date('Y-m-d').':'.$action.':'.$owner['uid'].
1806 ':person:'.$connect_id.':'.$item['created'];
1808 $item["body"] = sprintf($message, $owner["nick"], $contact["nick"]);
1810 self::entryHeader($doc, $entry, $owner, $toplevel);
1812 self::entryContent($doc, $entry, $item, $owner, $title);
1814 $object = self::addPersonObject($doc, $owner, $contact);
1815 $entry->appendChild($object);
1817 self::entryFooter($doc, $entry, $item, $owner);
1823 * @brief Adds a regular entry element
1825 * @param object $doc XML document
1826 * @param array $item Data of the item that is to be posted
1827 * @param array $owner Contact data of the poster
1828 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1830 * @return object Entry element
1832 private static function noteEntry($doc, $item, $owner, $toplevel)
1834 if (($item["id"] != $item["parent"]) && (normalise_link($item["author-link"]) != normalise_link($owner["url"]))) {
1835 logger("OStatus entry is from author ".$owner["url"]." - not from ".$item["author-link"].". Quitting.", LOGGER_DEBUG);
1838 $title = self::entryHeader($doc, $entry, $owner, $toplevel);
1840 XML::addElement($doc, $entry, "activity:object-type", ACTIVITY_OBJ_NOTE);
1842 self::entryContent($doc, $entry, $item, $owner, $title);
1844 self::entryFooter($doc, $entry, $item, $owner);
1850 * @brief Adds a header element to the XML document
1852 * @param object $doc XML document
1853 * @param object $entry The entry element where the elements are added
1854 * @param array $owner Contact data of the poster
1855 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1857 * @return string The title for the element
1859 private static function entryHeader($doc, &$entry, $owner, $toplevel)
1861 /// @todo Check if this title stuff is really needed (I guess not)
1863 $entry = $doc->createElement("entry");
1864 $title = sprintf("New note by %s", $owner["nick"]);
1866 $entry = $doc->createElementNS(NAMESPACE_ATOM1, "entry");
1868 $entry->setAttribute("xmlns:thr", NAMESPACE_THREAD);
1869 $entry->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
1870 $entry->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
1871 $entry->setAttribute("xmlns:media", NAMESPACE_MEDIA);
1872 $entry->setAttribute("xmlns:poco", NAMESPACE_POCO);
1873 $entry->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
1874 $entry->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
1875 $entry->setAttribute("xmlns:mastodon", NAMESPACE_MASTODON);
1877 $author = self::addAuthor($doc, $owner);
1878 $entry->appendChild($author);
1880 $title = sprintf("New comment by %s", $owner["nick"]);
1886 * @brief Adds elements to the XML document
1888 * @param object $doc XML document
1889 * @param object $entry Entry element where the content is added
1890 * @param array $item Data of the item that is to be posted
1891 * @param array $owner Contact data of the poster
1892 * @param string $title Title for the post
1893 * @param string $verb The activity verb
1894 * @param bool $complete Add the "status_net" element?
1897 private static function entryContent($doc, $entry, $item, $owner, $title, $verb = "", $complete = true)
1900 $verb = self::constructVerb($item);
1903 XML::addElement($doc, $entry, "id", $item["uri"]);
1904 XML::addElement($doc, $entry, "title", $title);
1906 $body = self::formatPicturePost($item['body']);
1908 if ($item['title'] != "") {
1909 $body = "[b]".$item['title']."[/b]\n\n".$body;
1912 $body = bbcode($body, false, false, 7);
1914 XML::addElement($doc, $entry, "content", $body, ["type" => "html"]);
1916 XML::addElement($doc, $entry, "link", "", ["rel" => "alternate", "type" => "text/html",
1917 "href" => System::baseUrl()."/display/".$item["guid"]]
1920 if ($complete && ($item["id"] > 0)) {
1921 XML::addElement($doc, $entry, "status_net", "", ["notice_id" => $item["id"]]);
1924 XML::addElement($doc, $entry, "activity:verb", $verb);
1926 XML::addElement($doc, $entry, "published", DateTimeFormat::utc($item["created"]."+00:00", DateTimeFormat::ATOM));
1927 XML::addElement($doc, $entry, "updated", DateTimeFormat::utc($item["edited"]."+00:00", DateTimeFormat::ATOM));
1931 * @brief Adds the elements at the foot of an entry to the XML document
1933 * @param object $doc XML document
1934 * @param object $entry The entry element where the elements are added
1935 * @param array $item Data of the item that is to be posted
1936 * @param array $owner Contact data of the poster
1937 * @param bool $complete default true
1940 private static function entryFooter($doc, $entry, $item, $owner, $complete = true)
1944 if (($item['parent'] != $item['id']) || ($item['parent-uri'] !== $item['uri']) || (($item['thr-parent'] !== '') && ($item['thr-parent'] !== $item['uri']))) {
1945 $parent = q("SELECT `guid`, `author-link`, `owner-link` FROM `item` WHERE `id` = %d", intval($item["parent"]));
1946 $parent_item = (($item['thr-parent']) ? $item['thr-parent'] : $item['parent-uri']);
1949 "SELECT `guid`, `author-link`, `owner-link`, `plink` FROM `item` WHERE `uid` = %d AND `uri` = '%s'",
1950 intval($owner["uid"]),
1954 $mentioned[$thrparent[0]["author-link"]] = $thrparent[0]["author-link"];
1955 $mentioned[$thrparent[0]["owner-link"]] = $thrparent[0]["owner-link"];
1956 $parent_plink = $thrparent[0]["plink"];
1958 $mentioned[$parent[0]["author-link"]] = $parent[0]["author-link"];
1959 $mentioned[$parent[0]["owner-link"]] = $parent[0]["owner-link"];
1960 $parent_plink = System::baseUrl()."/display/".$parent[0]["guid"];
1964 "ref" => $parent_item,
1965 "href" => $parent_plink];
1966 XML::addElement($doc, $entry, "thr:in-reply-to", "", $attributes);
1970 "href" => $parent_plink];
1971 XML::addElement($doc, $entry, "link", "", $attributes);
1974 if (intval($item["parent"]) > 0) {
1975 $conversation_href = System::baseUrl()."/display/".$owner["nick"]."/".$item["parent"];
1976 $conversation_uri = $conversation_href;
1978 if (isset($parent_item)) {
1979 $r = dba::fetch_first("SELECT `conversation-uri`, `conversation-href` FROM `conversation` WHERE `item-uri` = ?", $parent_item);
1980 if (DBM::is_result($r)) {
1981 if ($r['conversation-uri'] != '') {
1982 $conversation_uri = $r['conversation-uri'];
1984 if ($r['conversation-href'] != '') {
1985 $conversation_href = $r['conversation-href'];
1990 XML::addElement($doc, $entry, "link", "", ["rel" => "ostatus:conversation", "href" => $conversation_href]);
1993 "href" => $conversation_href,
1994 "local_id" => $item["parent"],
1995 "ref" => $conversation_uri];
1997 XML::addElement($doc, $entry, "ostatus:conversation", $conversation_uri, $attributes);
2000 $tags = item::getFeedTags($item);
2003 foreach ($tags as $t) {
2005 $mentioned[$t[1]] = $t[1];
2010 // Make sure that mentions are accepted (GNU Social has problems with mixing HTTP and HTTPS)
2012 foreach ($mentioned as $mention) {
2013 $newmentions[str_replace("http://", "https://", $mention)] = str_replace("http://", "https://", $mention);
2014 $newmentions[str_replace("https://", "http://", $mention)] = str_replace("https://", "http://", $mention);
2016 $mentioned = $newmentions;
2018 foreach ($mentioned as $mention) {
2020 "SELECT `forum`, `prv` FROM `contact` WHERE `uid` = %d AND `nurl` = '%s'",
2021 intval($owner["uid"]),
2022 dbesc(normalise_link($mention))
2024 if ($r[0]["forum"] || $r[0]["prv"]) {
2025 XML::addElement($doc, $entry, "link", "",
2027 "rel" => "mentioned",
2028 "ostatus:object-type" => ACTIVITY_OBJ_GROUP,
2032 XML::addElement($doc, $entry, "link", "",
2034 "rel" => "mentioned",
2035 "ostatus:object-type" => ACTIVITY_OBJ_PERSON,
2041 if (!$item["private"]) {
2042 XML::addElement($doc, $entry, "link", "", ["rel" => "ostatus:attention",
2043 "href" => "http://activityschema.org/collection/public"]);
2044 XML::addElement($doc, $entry, "link", "", ["rel" => "mentioned",
2045 "ostatus:object-type" => "http://activitystrea.ms/schema/1.0/collection",
2046 "href" => "http://activityschema.org/collection/public"]);
2047 XML::addElement($doc, $entry, "mastodon:scope", "public");
2051 foreach ($tags as $t) {
2053 XML::addElement($doc, $entry, "category", "", ["term" => $t[2]]);
2058 self::getAttachment($doc, $entry, $item);
2060 if ($complete && ($item["id"] > 0)) {
2061 $app = $item["app"];
2066 $attributes = ["local_id" => $item["id"], "source" => $app];
2068 if (isset($parent["id"])) {
2069 $attributes["repeat_of"] = $parent["id"];
2072 if ($item["coord"] != "") {
2073 XML::addElement($doc, $entry, "georss:point", $item["coord"]);
2076 XML::addElement($doc, $entry, "statusnet:notice_info", "", $attributes);
2081 * Creates the XML feed for a given nickname
2083 * Supported filters:
2084 * - activity (default): all the public posts
2085 * - posts: all the public top-level posts
2086 * - comments: all the public replies
2088 * Updates the provided last_update parameter if the result comes from the
2089 * cache or it is empty
2091 * @brief Creates the XML feed for a given nickname
2093 * @param string $owner_nick Nickname of the feed owner
2094 * @param string $last_update Date of the last update
2095 * @param integer $max_items Number of maximum items to fetch
2096 * @param string $filter Feed items filter (activity, posts or comments)
2097 * @param boolean $nocache Wether to bypass caching
2099 * @return string XML feed
2101 public static function feed($owner_nick, &$last_update, $max_items = 300, $filter = 'activity', $nocache = false)
2103 $stamp = microtime(true);
2105 $cachekey = "ostatus:feed:" . $owner_nick . ":" . $filter . ":" . $last_update;
2107 $previous_created = $last_update;
2109 $result = Cache::get($cachekey);
2110 if (!$nocache && !is_null($result)) {
2111 logger('Feed duration: ' . number_format(microtime(true) - $stamp, 3) . ' - ' . $owner_nick . ' - ' . $filter . ' - ' . $previous_created . ' (cached)', LOGGER_DEBUG);
2112 $last_update = $result['last_update'];
2113 return $result['feed'];
2116 $owner = dba::fetch_first(
2117 "SELECT `contact`.*, `user`.`nickname`, `user`.`timezone`, `user`.`page-flags`
2118 FROM `contact` INNER JOIN `user` ON `user`.`uid` = `contact`.`uid`
2119 WHERE `contact`.`self` AND `user`.`nickname` = ? LIMIT 1",
2122 if (!DBM::is_result($owner)) {
2126 if (!strlen($last_update)) {
2127 $last_update = 'now -30 days';
2130 $check_date = DateTimeFormat::utc($last_update);
2131 $authorid = Contact::getIdForURL($owner["url"], 0);
2134 if ($filter === 'posts') {
2135 $sql_extra .= ' AND `item`.`id` = `item`.`parent` ';
2138 if ($filter === 'comments') {
2139 $sql_extra .= sprintf(" AND `item`.`object-type` = '%s' ", dbesc(ACTIVITY_OBJ_COMMENT));
2143 "SELECT `item`.*, `item`.`id` AS `item_id` FROM `item` USE INDEX (`uid_contactid_created`)
2144 STRAIGHT_JOIN `thread` ON `thread`.`iid` = `item`.`parent`
2145 WHERE `item`.`uid` = %d
2146 AND `item`.`contact-id` = %d
2147 AND `item`.`author-id` = %d
2148 AND `item`.`created` > '%s'
2149 AND NOT `item`.`deleted`
2150 AND NOT `item`.`private`
2151 AND `thread`.`network` IN ('%s', '%s')
2153 ORDER BY `item`.`created` DESC LIMIT %d",
2154 intval($owner["uid"]),
2155 intval($owner["id"]),
2158 dbesc(NETWORK_OSTATUS),
2159 dbesc(NETWORK_DFRN),
2163 $doc = new DOMDocument('1.0', 'utf-8');
2164 $doc->formatOutput = true;
2166 $root = self::addHeader($doc, $owner, $filter);
2168 foreach ($items as $item) {
2169 if (Config::get('system', 'ostatus_debug')) {
2170 $item['body'] .= '🍼';
2172 $entry = self::entry($doc, $item, $owner);
2173 $root->appendChild($entry);
2175 if ($last_update < $item['created']) {
2176 $last_update = $item['created'];
2180 $feeddata = trim($doc->saveXML());
2182 $msg = ['feed' => $feeddata, 'last_update' => $last_update];
2183 Cache::set($cachekey, $msg, CACHE_QUARTER_HOUR);
2185 logger('Feed duration: ' . number_format(microtime(true) - $stamp, 3) . ' - ' . $owner_nick . ' - ' . $filter . ' - ' . $previous_created, LOGGER_DEBUG);
2191 * @brief Creates the XML for a salmon message
2193 * @param array $item Data of the item that is to be posted
2194 * @param array $owner Contact data of the poster
2196 * @return string XML for the salmon
2198 public static function salmon($item, $owner)
2200 $doc = new DOMDocument('1.0', 'utf-8');
2201 $doc->formatOutput = true;
2203 if (Config::get('system', 'ostatus_debug')) {
2204 $item['body'] .= '🐟';
2207 $entry = self::entry($doc, $item, $owner, true);
2209 $doc->appendChild($entry);
2211 return trim($doc->saveXML());