3 * @file src/Protocol/OStatus.php
5 namespace Friendica\Protocol;
7 use Friendica\Content\Text\BBCode;
8 use Friendica\Core\Cache;
9 use Friendica\Core\Config;
10 use Friendica\Core\L10n;
11 use Friendica\Core\System;
12 use Friendica\Database\DBM;
13 use Friendica\Model\Contact;
14 use Friendica\Model\Conversation;
15 use Friendica\Model\GContact;
16 use Friendica\Model\Item;
17 use Friendica\Network\Probe;
18 use Friendica\Object\Image;
19 use Friendica\Util\DateTimeFormat;
20 use Friendica\Util\Lock;
21 use Friendica\Util\Network;
22 use Friendica\Util\XML;
27 require_once 'include/dba.php';
28 require_once 'include/html2bbcode.php';
29 require_once 'include/items.php';
30 require_once 'mod/share.php';
31 require_once 'include/enotify.php';
32 require_once 'include/api.php';
33 require_once 'mod/proxy.php';
36 * @brief This class contain functions for the OStatus protocol
40 private static $itemlist;
41 private static $conv_list = [];
44 * @brief Fetches author data
46 * @param object $xpath The xpath object
47 * @param object $context The xml context of the author details
48 * @param array $importer user record of the importing user
49 * @param array $contact Called by reference, will contain the fetched contact
50 * @param bool $onlyfetch Only fetch the header without updating the contact entries
52 * @return array Array of author related entries for the item
54 private static function fetchAuthor($xpath, $context, $importer, &$contact, $onlyfetch)
57 $author["author-link"] = $xpath->evaluate('atom:author/atom:uri/text()', $context)->item(0)->nodeValue;
58 $author["author-name"] = $xpath->evaluate('atom:author/atom:name/text()', $context)->item(0)->nodeValue;
59 $addr = $xpath->evaluate('atom:author/atom:email/text()', $context)->item(0)->nodeValue;
61 $aliaslink = $author["author-link"];
63 $alternate = $xpath->query("atom:author/atom:link[@rel='alternate']", $context)->item(0)->attributes;
64 if (is_object($alternate)) {
65 foreach ($alternate as $attributes) {
66 if (($attributes->name == "href") && ($attributes->textContent != "")) {
67 $author["author-link"] = $attributes->textContent;
71 $author["contact-id"] = $contact["id"];
74 if ($aliaslink != '') {
75 $condition = ["`uid` = ? AND `alias` = ? AND `network` != ? AND `rel` IN (?, ?)",
76 $importer["uid"], $aliaslink, NETWORK_STATUSNET,
77 CONTACT_IS_SHARING, CONTACT_IS_FRIEND];
78 $contact = dba::selectFirst('contact', [], $condition);
81 if (!DBM::is_result($contact) && $author["author-link"] != '') {
82 if ($aliaslink == "") {
83 $aliaslink = $author["author-link"];
86 $condition = ["`uid` = ? AND `nurl` IN (?, ?) AND `network` != ? AND `rel` IN (?, ?)",
87 $importer["uid"], normalise_link($author["author-link"]), normalise_link($aliaslink),
88 NETWORK_STATUSNET, CONTACT_IS_SHARING, CONTACT_IS_FRIEND];
89 $contact = dba::selectFirst('contact', [], $condition);
92 if (!DBM::is_result($contact) && ($addr != '')) {
93 $condition = ["`uid` = ? AND `addr` = ? AND `network` != ? AND `rel` IN (?, ?)",
94 $importer["uid"], $addr, NETWORK_STATUSNET,
95 CONTACT_IS_SHARING, CONTACT_IS_FRIEND];
96 $contact = dba::selectFirst('contact', [], $condition);
99 if (DBM::is_result($contact)) {
100 if ($contact['blocked']) {
103 $author["contact-id"] = $contact["id"];
107 $avatars = $xpath->query("atom:author/atom:link[@rel='avatar']", $context);
108 foreach ($avatars as $avatar) {
111 foreach ($avatar->attributes as $attributes) {
112 if ($attributes->name == "href") {
113 $href = $attributes->textContent;
115 if ($attributes->name == "width") {
116 $width = $attributes->textContent;
120 $avatarlist[$width] = $href;
123 if (count($avatarlist) > 0) {
125 $author["author-avatar"] = Probe::fixAvatar(current($avatarlist), $author["author-link"]);
128 $displayname = $xpath->evaluate('atom:author/poco:displayName/text()', $context)->item(0)->nodeValue;
129 if ($displayname != "") {
130 $author["author-name"] = $displayname;
133 $author["owner-name"] = $author["author-name"];
134 $author["owner-link"] = $author["author-link"];
135 $author["owner-avatar"] = $author["author-avatar"];
137 // Only update the contacts if it is an OStatus contact
138 if (DBM::is_result($contact) && ($contact['id'] > 0) && !$onlyfetch && ($contact["network"] == NETWORK_OSTATUS)) {
140 // Update contact data
142 unset($current['name-date']);
144 // This query doesn't seem to work
145 // $value = $xpath->query("atom:link[@rel='salmon']", $context)->item(0)->nodeValue;
147 // $contact["notify"] = $value;
149 // This query doesn't seem to work as well - I hate these queries
150 // $value = $xpath->query("atom:link[@rel='self' and @type='application/atom+xml']", $context)->item(0)->nodeValue;
152 // $contact["poll"] = $value;
154 $contact['url'] = $author["author-link"];
155 $contact['nurl'] = normalise_link($contact['url']);
157 $value = $xpath->evaluate('atom:author/atom:uri/text()', $context)->item(0)->nodeValue;
159 $contact["alias"] = $value;
162 $value = $xpath->evaluate('atom:author/poco:displayName/text()', $context)->item(0)->nodeValue;
164 $contact["name"] = $value;
167 $value = $xpath->evaluate('atom:author/poco:preferredUsername/text()', $context)->item(0)->nodeValue;
169 $contact["nick"] = $value;
172 $value = $xpath->evaluate('atom:author/poco:note/text()', $context)->item(0)->nodeValue;
174 $contact["about"] = html2bbcode($value);
177 $value = $xpath->evaluate('atom:author/poco:address/poco:formatted/text()', $context)->item(0)->nodeValue;
179 $contact["location"] = $value;
182 $contact['name-date'] = DateTimeFormat::utcNow();
184 dba::update('contact', $contact, ['id' => $contact["id"]], $current);
186 if (!empty($author["author-avatar"]) && ($author["author-avatar"] != $current['avatar'])) {
187 logger("Update profile picture for contact ".$contact["id"], LOGGER_DEBUG);
188 Contact::updateAvatar($author["author-avatar"], $importer["uid"], $contact["id"]);
191 // Ensure that we are having this contact (with uid=0)
192 $cid = Contact::getIdForURL($aliaslink, 0, true);
195 $fields = ['url', 'nurl', 'name', 'nick', 'alias', 'about', 'location'];
196 $old_contact = dba::selectFirst('contact', $fields, ['id' => $cid]);
198 // Update it with the current values
199 $fields = ['url' => $author["author-link"], 'name' => $contact["name"],
200 'nurl' => normalise_link($author["author-link"]),
201 'nick' => $contact["nick"], 'alias' => $contact["alias"],
202 'about' => $contact["about"], 'location' => $contact["location"],
203 'success_update' => DateTimeFormat::utcNow(), 'last-update' => DateTimeFormat::utcNow()];
205 dba::update('contact', $fields, ['id' => $cid], $old_contact);
208 Contact::updateAvatar($author["author-avatar"], 0, $cid);
211 $contact["generation"] = 2;
212 $contact["hide"] = false; // OStatus contacts are never hidden
213 $contact["photo"] = $author["author-avatar"];
214 $gcid = GContact::update($contact);
216 GContact::link($gcid, $contact["uid"], $contact["id"]);
223 * @brief Fetches author data from a given XML string
225 * @param string $xml The XML
226 * @param array $importer user record of the importing user
228 * @return array Array of author related entries for the item
230 public static function salmonAuthor($xml, $importer)
236 $doc = new DOMDocument();
237 @$doc->loadXML($xml);
239 $xpath = new DOMXPath($doc);
240 $xpath->registerNamespace('atom', NAMESPACE_ATOM1);
241 $xpath->registerNamespace('thr', NAMESPACE_THREAD);
242 $xpath->registerNamespace('georss', NAMESPACE_GEORSS);
243 $xpath->registerNamespace('activity', NAMESPACE_ACTIVITY);
244 $xpath->registerNamespace('media', NAMESPACE_MEDIA);
245 $xpath->registerNamespace('poco', NAMESPACE_POCO);
246 $xpath->registerNamespace('ostatus', NAMESPACE_OSTATUS);
247 $xpath->registerNamespace('statusnet', NAMESPACE_STATUSNET);
249 $contact = ["id" => 0];
251 // Fetch the first author
252 $authordata = $xpath->query('//author')->item(0);
253 $author = self::fetchAuthor($xpath, $authordata, $importer, $contact, true);
258 * @brief Read attributes from element
260 * @param object $element Element object
262 * @return array attributes
264 private static function readAttributes($element)
268 foreach ($element->attributes as $attributes) {
269 $attribute[$attributes->name] = $attributes->textContent;
276 * @brief Imports an XML string containing OStatus elements
278 * @param string $xml The XML
279 * @param array $importer user record of the importing user
280 * @param array $contact contact
281 * @param string $hub Called by reference, returns the fetched hub data
284 public static function import($xml, $importer, &$contact, &$hub)
286 self::process($xml, $importer, $contact, $hub);
290 * @brief Internal feed processing
292 * @param string $xml The XML
293 * @param array $importer user record of the importing user
294 * @param array $contact contact
295 * @param string $hub Called by reference, returns the fetched hub data
296 * @param boolean $stored Is the post fresh imported or from the database?
297 * @param boolean $initialize Is it the leading post so that data has to be initialized?
299 * @return boolean Could the XML be processed?
301 private static function process($xml, $importer, &$contact, &$hub, $stored = false, $initialize = true)
304 self::$itemlist = [];
305 self::$conv_list = [];
308 logger("Import OStatus message", LOGGER_DEBUG);
313 $doc = new DOMDocument();
314 @$doc->loadXML($xml);
316 $xpath = new DOMXPath($doc);
317 $xpath->registerNamespace('atom', NAMESPACE_ATOM1);
318 $xpath->registerNamespace('thr', NAMESPACE_THREAD);
319 $xpath->registerNamespace('georss', NAMESPACE_GEORSS);
320 $xpath->registerNamespace('activity', NAMESPACE_ACTIVITY);
321 $xpath->registerNamespace('media', NAMESPACE_MEDIA);
322 $xpath->registerNamespace('poco', NAMESPACE_POCO);
323 $xpath->registerNamespace('ostatus', NAMESPACE_OSTATUS);
324 $xpath->registerNamespace('statusnet', NAMESPACE_STATUSNET);
327 $hub_attributes = $xpath->query("/atom:feed/atom:link[@rel='hub']")->item(0)->attributes;
328 if (is_object($hub_attributes)) {
329 foreach ($hub_attributes as $hub_attribute) {
330 if ($hub_attribute->name == "href") {
331 $hub = $hub_attribute->textContent;
332 logger("Found hub ".$hub, LOGGER_DEBUG);
338 $header["uid"] = $importer["uid"];
339 $header["network"] = NETWORK_OSTATUS;
340 $header["type"] = "remote";
342 $header["origin"] = 0;
343 $header["gravity"] = GRAVITY_PARENT;
345 $first_child = $doc->firstChild->tagName;
347 if ($first_child == "feed") {
348 $entries = $xpath->query('/atom:feed/atom:entry');
350 $entries = $xpath->query('/atom:entry');
353 if ($entries->length == 1) {
354 // We reformat the XML to make it better readable
355 $doc2 = new DOMDocument();
356 $doc2->loadXML($xml);
357 $doc2->preserveWhiteSpace = false;
358 $doc2->formatOutput = true;
359 $xml2 = $doc2->saveXML();
361 $header["protocol"] = PROTOCOL_OSTATUS_SALMON;
362 $header["source"] = $xml2;
363 } elseif (!$initialize) {
367 // Fetch the first author
368 $authordata = $xpath->query('//author')->item(0);
369 $author = self::fetchAuthor($xpath, $authordata, $importer, $contact, $stored);
371 $entry = $xpath->query('/atom:entry');
373 // Reverse the order of the entries
376 foreach ($entries as $entry) {
377 $entrylist[] = $entry;
380 foreach (array_reverse($entrylist) as $entry) {
382 $authorelement = $xpath->query('/atom:entry/atom:author', $entry);
384 if ($authorelement->length == 0) {
385 $authorelement = $xpath->query('atom:author', $entry);
388 if ($authorelement->length > 0) {
389 $author = self::fetchAuthor($xpath, $entry, $importer, $contact, $stored);
392 $value = $xpath->evaluate('atom:author/poco:preferredUsername/text()', $entry)->item(0)->nodeValue;
396 $nickname = $author["author-name"];
399 $item = array_merge($header, $author);
401 $item["uri"] = $xpath->query('atom:id/text()', $entry)->item(0)->nodeValue;
403 $item["verb"] = $xpath->query('activity:verb/text()', $entry)->item(0)->nodeValue;
406 if (in_array($item["verb"], ['qvitter-delete-notice', ACTIVITY_DELETE, 'delete'])) {
407 self::deleteNotice($item);
411 if (in_array($item["verb"], [NAMESPACE_OSTATUS."/unfavorite", ACTIVITY_UNFAVORITE])) {
412 // Ignore "Unfavorite" message
413 logger("Ignore unfavorite message ".print_r($item, true), LOGGER_DEBUG);
417 // Deletions come with the same uri, so we check for duplicates after processing deletions
418 if (dba::exists('item', ['uid' => $importer["uid"], 'uri' => $item["uri"]])) {
419 logger('Post with URI '.$item["uri"].' already existed for user '.$importer["uid"].'.', LOGGER_DEBUG);
422 logger('Processing post with URI '.$item["uri"].' for user '.$importer["uid"].'.', LOGGER_DEBUG);
425 if ($item["verb"] == ACTIVITY_JOIN) {
426 // ignore "Join" messages
427 logger("Ignore join message ".print_r($item, true), LOGGER_DEBUG);
431 if ($item["verb"] == "http://mastodon.social/schema/1.0/block") {
432 // ignore mastodon "block" messages
433 logger("Ignore block message ".print_r($item, true), LOGGER_DEBUG);
437 if ($item["verb"] == ACTIVITY_FOLLOW) {
438 Contact::addRelationship($importer, $contact, $item, $nickname);
442 if ($item["verb"] == NAMESPACE_OSTATUS."/unfollow") {
443 Contact::removeFollower($importer, $contact, $item, $dummy);
447 if ($item["verb"] == ACTIVITY_FAVORITE) {
448 $orig_uri = $xpath->query("activity:object/atom:id", $entry)->item(0)->nodeValue;
449 logger("Favorite ".$orig_uri." ".print_r($item, true));
451 $item["verb"] = ACTIVITY_LIKE;
452 $item["parent-uri"] = $orig_uri;
453 $item["gravity"] = GRAVITY_LIKE;
456 // http://activitystrea.ms/schema/1.0/rsvp-yes
457 if (!in_array($item["verb"], [ACTIVITY_POST, ACTIVITY_LIKE, ACTIVITY_SHARE])) {
458 logger("Unhandled verb ".$item["verb"]." ".print_r($item, true), LOGGER_DEBUG);
461 self::processPost($xpath, $entry, $item, $importer);
463 if ($initialize && (count(self::$itemlist) > 0)) {
464 if (self::$itemlist[0]['uri'] == self::$itemlist[0]['parent-uri']) {
465 // We will import it everytime, when it is started by our contacts
466 $valid = !empty(self::$itemlist[0]['contact-id']);
468 // If not, then it depends on this setting
469 $valid = !Config::get('system', 'ostatus_full_threads');
471 logger("Item with uri ".self::$itemlist[0]['uri']." will be imported due to the system settings.", LOGGER_DEBUG);
474 logger("Item with uri ".self::$itemlist[0]['uri']." belongs to a contact (".self::$itemlist[0]['contact-id']."). It will be imported.", LOGGER_DEBUG);
477 // Never post a thread when the only interaction by our contact was a like
479 $verbs = [ACTIVITY_POST, ACTIVITY_SHARE];
480 foreach (self::$itemlist as $item) {
481 if (!empty($item['contact-id']) && in_array($item['verb'], $verbs)) {
486 logger("Item with uri ".self::$itemlist[0]['uri']." will be imported since the thread contains posts or shares.", LOGGER_DEBUG);
490 // But we will only import complete threads
491 $valid = dba::exists('item', ['uid' => $importer["uid"], 'uri' => self::$itemlist[0]['parent-uri']]);
493 logger("Item with uri ".self::$itemlist[0]["uri"]." belongs to parent ".self::$itemlist[0]['parent-uri']." of user ".$importer["uid"].". It will be imported.", LOGGER_DEBUG);
498 $default_contact = 0;
499 $key = count(self::$itemlist);
500 for ($key = count(self::$itemlist) - 1; $key >= 0; $key--) {
501 if (empty(self::$itemlist[$key]['contact-id'])) {
502 self::$itemlist[$key]['contact-id'] = $default_contact;
504 $default_contact = $item['contact-id'];
507 foreach (self::$itemlist as $item) {
508 $found = dba::exists('item', ['uid' => $importer["uid"], 'uri' => $item["uri"]]);
510 logger("Item with uri ".$item["uri"]." for user ".$importer["uid"]." already exists.", LOGGER_DEBUG);
511 } elseif ($item['contact-id'] < 0) {
512 logger("Item with uri ".$item["uri"]." is from a blocked contact.", LOGGER_DEBUG);
514 // We are having duplicated entries. Hopefully this solves it.
515 if (Lock::set('ostatus_process_item_insert')) {
516 $ret = Item::insert($item);
517 Lock::remove('ostatus_process_item_insert');
518 logger("Item with uri ".$item["uri"]." for user ".$importer["uid"].' stored. Return value: '.$ret);
520 $ret = Item::insert($item);
521 logger("We couldn't lock - but tried to store the item anyway. Return value is ".$ret);
526 self::$itemlist = [];
528 logger('Processing done for post with URI '.$item["uri"].' for user '.$importer["uid"].'.', LOGGER_DEBUG);
534 * @param object $item item
537 private static function deleteNotice($item)
539 $condition = ['uid' => $item['uid'], 'author-link' => $item['author-link'], 'uri' => $item['uri']];
540 $deleted = dba::selectFirst('item', ['id', 'parent-uri'], $condition);
541 if (!DBM::is_result($deleted)) {
542 logger('Item from '.$item['author-link'].' with uri '.$item['uri'].' for user '.$item['uid']." wasn't found. We don't delete it. ");
546 Item::deleteById($deleted["id"]);
548 logger('Deleted item with uri '.$item['uri'].' for user '.$item['uid']);
552 * @brief Processes the XML for a post
554 * @param object $xpath The xpath object
555 * @param object $entry The xml entry that is processed
556 * @param array $item The item array
557 * @param array $importer user record of the importing user
560 private static function processPost($xpath, $entry, &$item, $importer)
562 $item["body"] = html2bbcode($xpath->query('atom:content/text()', $entry)->item(0)->nodeValue);
563 $item["object-type"] = $xpath->query('activity:object-type/text()', $entry)->item(0)->nodeValue;
564 if (($item["object-type"] == ACTIVITY_OBJ_BOOKMARK) || ($item["object-type"] == ACTIVITY_OBJ_EVENT)) {
565 $item["title"] = $xpath->query('atom:title/text()', $entry)->item(0)->nodeValue;
566 $item["body"] = $xpath->query('atom:summary/text()', $entry)->item(0)->nodeValue;
567 } elseif ($item["object-type"] == ACTIVITY_OBJ_QUESTION) {
568 $item["title"] = $xpath->query('atom:title/text()', $entry)->item(0)->nodeValue;
571 $item["created"] = $xpath->query('atom:published/text()', $entry)->item(0)->nodeValue;
572 $item["edited"] = $xpath->query('atom:updated/text()', $entry)->item(0)->nodeValue;
573 $conversation = $xpath->query('ostatus:conversation/text()', $entry)->item(0)->nodeValue;
574 $item['conversation-uri'] = $conversation;
576 $conv = $xpath->query('ostatus:conversation', $entry);
577 if (is_object($conv->item(0))) {
578 foreach ($conv->item(0)->attributes as $attributes) {
579 if ($attributes->name == "ref") {
580 $item['conversation-uri'] = $attributes->textContent;
582 if ($attributes->name == "href") {
583 $item['conversation-href'] = $attributes->textContent;
590 $inreplyto = $xpath->query('thr:in-reply-to', $entry);
591 if (is_object($inreplyto->item(0))) {
592 foreach ($inreplyto->item(0)->attributes as $attributes) {
593 if ($attributes->name == "ref") {
594 $item["parent-uri"] = $attributes->textContent;
596 if ($attributes->name == "href") {
597 $related = $attributes->textContent;
602 $georsspoint = $xpath->query('georss:point', $entry);
603 if (!empty($georsspoint) && ($georsspoint->length > 0)) {
604 $item["coord"] = $georsspoint->item(0)->nodeValue;
610 $links = $xpath->query('atom:link', $entry);
612 $link_data = self::processLinks($links, $item);
613 $self = $link_data['self'];
614 $add_body = $link_data['add_body'];
619 $notice_info = $xpath->query('statusnet:notice_info', $entry);
620 if ($notice_info && ($notice_info->length > 0)) {
621 foreach ($notice_info->item(0)->attributes as $attributes) {
622 if ($attributes->name == "source") {
623 $item["app"] = strip_tags($attributes->textContent);
625 if ($attributes->name == "repeat_of") {
626 $repeat_of = $attributes->textContent;
630 // Is it a repeated post?
631 if (($repeat_of != "") || ($item["verb"] == ACTIVITY_SHARE)) {
632 $link_data = self::processRepeatedItem($xpath, $entry, $item, $importer);
633 if (!empty($link_data['add_body'])) {
634 $add_body .= $link_data['add_body'];
638 $item["body"] .= $add_body;
640 // Only add additional data when there is no picture in the post
641 if (!strstr($item["body"], '[/img]')) {
642 $item["body"] = add_page_info_to_body($item["body"]);
645 // Mastodon Content Warning
646 $content_warning = false;
647 if (($item["verb"] == ACTIVITY_POST) && $xpath->evaluate('boolean(atom:summary)', $entry)) {
648 $clear_text = $xpath->query('atom:summary/text()', $entry)->item(0)->nodeValue;
649 if (!empty($clear_text)) {
650 $item["body"] = html2bbcode($clear_text) . '[spoiler]' . $item["body"] . '[/spoiler]';
651 $content_warning = true;
655 if (($self != '') && empty($item['protocol'])) {
656 self::fetchSelf($self, $item);
659 if (!empty($item["conversation-href"])) {
660 self::fetchConversation($item['conversation-href'], $item['conversation-uri']);
663 if (isset($item["parent-uri"]) && ($related != '')) {
664 if (!dba::exists('item', ['uid' => $importer["uid"], 'uri' => $item['parent-uri']])) {
665 self::fetchRelated($related, $item["parent-uri"], $importer);
667 logger('Reply with URI '.$item["uri"].' already existed for user '.$importer["uid"].'.', LOGGER_DEBUG);
670 $item["type"] = 'remote-comment';
671 $item["gravity"] = GRAVITY_COMMENT;
673 $item["parent-uri"] = $item["uri"];
676 $categories = $xpath->query('atom:category', $entry);
678 foreach ($categories as $category) {
679 foreach ($category->attributes as $attributes) {
680 if ($attributes->name == "term") {
681 $term = $attributes->textContent;
682 // don't add nsfw with content warning
683 // Background: "nsfw" is set automatically by Mastodon and superfluous
684 if (!$content_warning || ($term != 'nsfw')) {
685 if (strlen($item["tag"])) {
688 $item["tag"] .= "#[url=".System::baseUrl()."/search?tag=".$term."]".$term."[/url]";
695 if (($item['author-link'] != '') && !empty($item['protocol'])) {
696 $item = Conversation::insert($item);
699 self::$itemlist[] = $item;
703 * @brief Fetch the conversation for posts
705 * @param string $conversation The link to the conversation
706 * @param string $conversation_uri The conversation in "uri" format
709 private static function fetchConversation($conversation, $conversation_uri)
711 // Ensure that we only store a conversation once in a process
712 if (isset(self::$conv_list[$conversation])) {
716 self::$conv_list[$conversation] = true;
718 $conversation_data = Network::curl($conversation, false, $redirects, ['accept_content' => 'application/atom+xml, text/html']);
720 if (!$conversation_data['success']) {
726 if (stristr($conversation_data['header'], 'Content-Type: application/atom+xml')) {
727 $xml = $conversation_data['body'];
731 $doc = new DOMDocument();
732 if (!@$doc->loadHTML($conversation_data['body'])) {
735 $xpath = new DOMXPath($doc);
737 $links = $xpath->query('//link');
740 foreach ($links as $link) {
741 $attribute = self::readAttributes($link);
742 if (($attribute['rel'] == 'alternate') && ($attribute['type'] == 'application/atom+xml')) {
743 $file = $attribute['href'];
747 $conversation_atom = Network::curl($attribute['href']);
749 if ($conversation_atom['success']) {
750 $xml = $conversation_atom['body'];
760 self::storeConversation($xml, $conversation, $conversation_uri);
764 * @brief Store a feed in several conversation entries
766 * @param string $xml The feed
767 * @param string $conversation conversation
768 * @param string $conversation_uri conversation uri
771 private static function storeConversation($xml, $conversation = '', $conversation_uri = '')
773 $doc = new DOMDocument();
774 @$doc->loadXML($xml);
776 $xpath = new DOMXPath($doc);
777 $xpath->registerNamespace('atom', NAMESPACE_ATOM1);
778 $xpath->registerNamespace('thr', NAMESPACE_THREAD);
779 $xpath->registerNamespace('ostatus', NAMESPACE_OSTATUS);
781 $entries = $xpath->query('/atom:feed/atom:entry');
783 // Now store the entries
784 foreach ($entries as $entry) {
785 $doc2 = new DOMDocument();
786 $doc2->preserveWhiteSpace = false;
787 $doc2->formatOutput = true;
791 $conv_data['protocol'] = PROTOCOL_SPLITTED_CONV;
792 $conv_data['network'] = NETWORK_OSTATUS;
793 $conv_data['uri'] = $xpath->query('atom:id/text()', $entry)->item(0)->nodeValue;
795 $inreplyto = $xpath->query('thr:in-reply-to', $entry);
796 if (is_object($inreplyto->item(0))) {
797 foreach ($inreplyto->item(0)->attributes as $attributes) {
798 if ($attributes->name == "ref") {
799 $conv_data['reply-to-uri'] = $attributes->textContent;
804 $conv = $xpath->query('ostatus:conversation/text()', $entry)->item(0)->nodeValue;
805 $conv_data['conversation-uri'] = $conv;
807 $conv = $xpath->query('ostatus:conversation', $entry);
808 if (is_object($conv->item(0))) {
809 foreach ($conv->item(0)->attributes as $attributes) {
810 if ($attributes->name == "ref") {
811 $conv_data['conversation-uri'] = $attributes->textContent;
813 if ($attributes->name == "href") {
814 $conv_data['conversation-href'] = $attributes->textContent;
819 if ($conversation != '') {
820 $conv_data['conversation-uri'] = $conversation;
823 if ($conversation_uri != '') {
824 $conv_data['conversation-uri'] = $conversation_uri;
827 $entry = $doc2->importNode($entry, true);
829 $doc2->appendChild($entry);
831 $conv_data['source'] = $doc2->saveXML();
833 $condition = ['item-uri' => $conv_data['uri'],'protocol' => PROTOCOL_OSTATUS_FEED];
834 if (dba::exists('conversation', $condition)) {
835 logger('Delete deprecated entry for URI '.$conv_data['uri'], LOGGER_DEBUG);
836 dba::delete('conversation', ['item-uri' => $conv_data['uri']]);
839 logger('Store conversation data for uri '.$conv_data['uri'], LOGGER_DEBUG);
840 Conversation::insert($conv_data);
845 * @brief Fetch the own post so that it can be stored later
847 * We want to store the original data for later processing.
848 * This function is meant for cases where we process a feed with multiple entries.
849 * In that case we need to fetch the single posts here.
851 * @param string $self The link to the self item
852 * @param array $item The item array
855 private static function fetchSelf($self, &$item)
857 $condition = ['`item-uri` = ? AND `protocol` IN (?, ?)', $self, PROTOCOL_DFRN, PROTOCOL_OSTATUS_SALMON];
858 if (dba::exists('conversation', $condition)) {
859 logger('Conversation '.$item['uri'].' is already stored.', LOGGER_DEBUG);
863 $self_data = Network::curl($self);
865 if (!$self_data['success']) {
869 // We reformat the XML to make it better readable
870 $doc = new DOMDocument();
871 $doc->loadXML($self_data['body']);
872 $doc->preserveWhiteSpace = false;
873 $doc->formatOutput = true;
874 $xml = $doc->saveXML();
876 $item["protocol"] = PROTOCOL_OSTATUS_SALMON;
877 $item["source"] = $xml;
879 logger('Conversation '.$item['uri'].' is now fetched.', LOGGER_DEBUG);
883 * @brief Fetch related posts and processes them
885 * @param string $related The link to the related item
886 * @param string $related_uri The related item in "uri" format
887 * @param array $importer user record of the importing user
890 private static function fetchRelated($related, $related_uri, $importer)
892 $condition = ['`item-uri` = ? AND `protocol` IN (?, ?)', $related_uri, PROTOCOL_DFRN, PROTOCOL_OSTATUS_SALMON];
893 $conversation = dba::selectFirst('conversation', ['source', 'protocol'], $condition);
894 if (DBM::is_result($conversation)) {
896 $xml = $conversation['source'];
897 if (self::process($xml, $importer, $contact, $hub, $stored, false)) {
898 logger('Got valid cached XML for URI '.$related_uri, LOGGER_DEBUG);
901 if ($conversation['protocol'] == PROTOCOL_OSTATUS_SALMON) {
902 logger('Delete invalid cached XML for URI '.$related_uri, LOGGER_DEBUG);
903 dba::delete('conversation', ['item-uri' => $related_uri]);
908 $related_data = Network::curl($related, false, $redirects, ['accept_content' => 'application/atom+xml, text/html']);
910 if (!$related_data['success']) {
916 if (stristr($related_data['header'], 'Content-Type: application/atom+xml')) {
917 logger('Directly fetched XML for URI '.$related_uri, LOGGER_DEBUG);
918 $xml = $related_data['body'];
922 $doc = new DOMDocument();
923 if (!@$doc->loadHTML($related_data['body'])) {
926 $xpath = new DOMXPath($doc);
930 $links = $xpath->query('//link');
932 foreach ($links as $link) {
933 $attribute = self::readAttributes($link);
934 if (($attribute['rel'] == 'alternate') && ($attribute['type'] == 'application/atom+xml')) {
935 $atom_file = $attribute['href'];
938 if ($atom_file != '') {
939 $related_atom = Network::curl($atom_file);
941 if ($related_atom['success']) {
942 logger('Fetched XML for URI '.$related_uri, LOGGER_DEBUG);
943 $xml = $related_atom['body'];
949 // Workaround for older GNU Social servers
950 if (($xml == '') && strstr($related, '/notice/')) {
951 $related_atom = Network::curl(str_replace('/notice/', '/api/statuses/show/', $related).'.atom');
953 if ($related_atom['success']) {
954 logger('GNU Social workaround to fetch XML for URI '.$related_uri, LOGGER_DEBUG);
955 $xml = $related_atom['body'];
959 // Even more worse workaround for GNU Social ;-)
961 $related_guess = OStatus::convertHref($related_uri);
962 $related_atom = Network::curl(str_replace('/notice/', '/api/statuses/show/', $related_guess).'.atom');
964 if ($related_atom['success']) {
965 logger('GNU Social workaround 2 to fetch XML for URI '.$related_uri, LOGGER_DEBUG);
966 $xml = $related_atom['body'];
970 // Finally we take the data that we fetched from "ostatus:conversation"
972 $condition = ['item-uri' => $related_uri, 'protocol' => PROTOCOL_SPLITTED_CONV];
973 $conversation = dba::selectFirst('conversation', ['source'], $condition);
974 if (DBM::is_result($conversation)) {
976 logger('Got cached XML from conversation for URI '.$related_uri, LOGGER_DEBUG);
977 $xml = $conversation['source'];
982 self::process($xml, $importer, $contact, $hub, $stored, false);
984 logger("XML couldn't be fetched for URI: ".$related_uri." - href: ".$related, LOGGER_DEBUG);
990 * @brief Processes the XML for a repeated post
992 * @param object $xpath The xpath object
993 * @param object $entry The xml entry that is processed
994 * @param array $item The item array
995 * @param array $importer user record of the importing user
997 * @return array with data from links
999 private static function processRepeatedItem($xpath, $entry, &$item, $importer)
1001 $activityobjects = $xpath->query('activity:object', $entry)->item(0);
1003 if (!is_object($activityobjects)) {
1009 $orig_uri = $xpath->query('atom:id/text()', $activityobjects)->item(0)->nodeValue;
1011 $links = $xpath->query("atom:link", $activityobjects);
1013 $link_data = self::processLinks($links, $item);
1016 $orig_body = $xpath->query('atom:content/text()', $activityobjects)->item(0)->nodeValue;
1017 $orig_created = $xpath->query('atom:published/text()', $activityobjects)->item(0)->nodeValue;
1018 $orig_edited = $xpath->query('atom:updated/text()', $activityobjects)->item(0)->nodeValue;
1020 $orig_author = self::fetchAuthor($xpath, $activityobjects, $importer, $dummy, false);
1022 $item["author-name"] = $orig_author["author-name"];
1023 $item["author-link"] = $orig_author["author-link"];
1024 $item["author-avatar"] = $orig_author["author-avatar"];
1026 $item["body"] = html2bbcode($orig_body);
1027 $item["created"] = $orig_created;
1028 $item["edited"] = $orig_edited;
1030 $item["uri"] = $orig_uri;
1032 $item["verb"] = $xpath->query('activity:verb/text()', $activityobjects)->item(0)->nodeValue;
1034 $item["object-type"] = $xpath->query('activity:object-type/text()', $activityobjects)->item(0)->nodeValue;
1036 $inreplyto = $xpath->query('thr:in-reply-to', $activityobjects);
1037 if (is_object($inreplyto->item(0))) {
1038 foreach ($inreplyto->item(0)->attributes as $attributes) {
1039 if ($attributes->name == "ref") {
1040 $item["parent-uri"] = $attributes->textContent;
1049 * @brief Processes links in the XML
1051 * @param object $links The xml data that contain links
1052 * @param array $item The item array
1054 * @return array with data from the links
1056 private static function processLinks($links, &$item)
1058 $link_data = ['add_body' => '', 'self' => ''];
1060 foreach ($links as $link) {
1061 $attribute = self::readAttributes($link);
1063 if (($attribute['rel'] != "") && ($attribute['href'] != "")) {
1064 switch ($attribute['rel']) {
1066 $item["plink"] = $attribute['href'];
1067 if (($item["object-type"] == ACTIVITY_OBJ_QUESTION)
1068 || ($item["object-type"] == ACTIVITY_OBJ_EVENT)
1070 $item["body"] .= add_page_info($attribute['href']);
1073 case "ostatus:conversation":
1074 $link_data['conversation'] = $attribute['href'];
1075 $item['conversation-href'] = $link_data['conversation'];
1076 if (!isset($item['conversation-uri'])) {
1077 $item['conversation-uri'] = $item['conversation-href'];
1081 $filetype = strtolower(substr($attribute['type'], 0, strpos($attribute['type'], '/')));
1082 if ($filetype == 'image') {
1083 $link_data['add_body'] .= "\n[img]".$attribute['href'].'[/img]';
1085 if (strlen($item["attach"])) {
1086 $item["attach"] .= ',';
1088 if (!isset($attribute['length'])) {
1089 $attribute['length'] = "0";
1091 $item["attach"] .= '[attach]href="'.$attribute['href'].'" length="'.$attribute['length'].'" type="'.$attribute['type'].'" title="'.$attribute['title'].'"[/attach]';
1095 if ($item["object-type"] != ACTIVITY_OBJ_BOOKMARK) {
1096 if (!isset($item["parent-uri"])) {
1097 $item["parent-uri"] = $attribute['href'];
1099 $link_data['related'] = $attribute['href'];
1101 $item["body"] .= add_page_info($attribute['href']);
1105 if ($item["plink"] == '') {
1106 $item["plink"] = $attribute['href'];
1108 $link_data['self'] = $attribute['href'];
1117 * @brief Create an url out of an uri
1119 * @param string $href URI in the format "parameter1:parameter1:..."
1121 * @return string URL in the format http(s)://....
1123 public static function convertHref($href)
1125 $elements = explode(":", $href);
1127 if ((count($elements) <= 2) || ($elements[0] != "tag")) {
1131 $server = explode(",", $elements[1]);
1132 $conversation = explode("=", $elements[2]);
1134 if ((count($elements) == 4) && ($elements[2] == "post")) {
1135 return "http://".$server[0]."/notice/".$elements[3];
1138 if ((count($conversation) != 2) || ($conversation[1] =="")) {
1141 if ($elements[3] == "objectType=thread") {
1142 return "http://".$server[0]."/conversation/".$conversation[1];
1144 return "http://".$server[0]."/notice/".$conversation[1];
1150 * @brief Checks if the current post is a reshare
1152 * @param array $item The item array of thw post
1154 * @return string The guid if the post is a reshare
1156 private static function getResharedGuid($item)
1158 $body = trim($item["body"]);
1160 // Skip if it isn't a pure repeated messages
1161 // Does it start with a share?
1162 if (strpos($body, "[share") > 0) {
1166 // Does it end with a share?
1167 if (strlen($body) > (strrpos($body, "[/share]") + 8)) {
1171 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "$1", $body);
1172 // Skip if there is no shared message in there
1173 if ($body == $attributes) {
1178 preg_match("/guid='(.*?)'/ism", $attributes, $matches);
1179 if ($matches[1] != "") {
1180 $guid = $matches[1];
1183 preg_match('/guid="(.*?)"/ism', $attributes, $matches);
1184 if ($matches[1] != "") {
1185 $guid = $matches[1];
1192 * @brief Cleans the body of a post if it contains picture links
1194 * @param string $body The body
1196 * @return string The cleaned body
1198 private static function formatPicturePost($body)
1200 $siteinfo = BBCode::getAttachedData($body);
1202 if (($siteinfo["type"] == "photo")) {
1203 if (isset($siteinfo["preview"])) {
1204 $preview = $siteinfo["preview"];
1206 $preview = $siteinfo["image"];
1209 // Is it a remote picture? Then make a smaller preview here
1210 $preview = proxy_url($preview, false, PROXY_SIZE_SMALL);
1212 // Is it a local picture? Then make it smaller here
1213 $preview = str_replace(["-0.jpg", "-0.png"], ["-2.jpg", "-2.png"], $preview);
1214 $preview = str_replace(["-1.jpg", "-1.png"], ["-2.jpg", "-2.png"], $preview);
1216 if (isset($siteinfo["url"])) {
1217 $url = $siteinfo["url"];
1219 $url = $siteinfo["image"];
1222 $body = trim($siteinfo["text"])." [url]".$url."[/url]\n[img]".$preview."[/img]";
1229 * @brief Adds the header elements to the XML document
1231 * @param object $doc XML document
1232 * @param array $owner Contact data of the poster
1233 * @param string $filter The related feed filter (activity, posts or comments)
1235 * @return object header root element
1237 private static function addHeader($doc, $owner, $filter)
1241 $root = $doc->createElementNS(NAMESPACE_ATOM1, 'feed');
1242 $doc->appendChild($root);
1244 $root->setAttribute("xmlns:thr", NAMESPACE_THREAD);
1245 $root->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
1246 $root->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
1247 $root->setAttribute("xmlns:media", NAMESPACE_MEDIA);
1248 $root->setAttribute("xmlns:poco", NAMESPACE_POCO);
1249 $root->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
1250 $root->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
1251 $root->setAttribute("xmlns:mastodon", NAMESPACE_MASTODON);
1255 case 'activity': $title = L10n::t('%s\'s timeline', $owner['name']); break;
1256 case 'posts' : $title = L10n::t('%s\'s posts' , $owner['name']); break;
1257 case 'comments': $title = L10n::t('%s\'s comments', $owner['name']); break;
1260 $attributes = ["uri" => "https://friendi.ca", "version" => FRIENDICA_VERSION . "-" . DB_UPDATE_VERSION];
1261 XML::addElement($doc, $root, "generator", FRIENDICA_PLATFORM, $attributes);
1262 XML::addElement($doc, $root, "id", System::baseUrl() . "/profile/" . $owner["nick"]);
1263 XML::addElement($doc, $root, "title", $title);
1264 XML::addElement($doc, $root, "subtitle", sprintf("Updates from %s on %s", $owner["name"], $a->config["sitename"]));
1265 XML::addElement($doc, $root, "logo", $owner["photo"]);
1266 XML::addElement($doc, $root, "updated", DateTimeFormat::utcNow(DateTimeFormat::ATOM));
1268 $author = self::addAuthor($doc, $owner);
1269 $root->appendChild($author);
1271 $attributes = ["href" => $owner["url"], "rel" => "alternate", "type" => "text/html"];
1272 XML::addElement($doc, $root, "link", "", $attributes);
1274 /// @TODO We have to find out what this is
1275 /// $attributes = array("href" => System::baseUrl()."/sup",
1276 /// "rel" => "http://api.friendfeed.com/2008/03#sup",
1277 /// "type" => "application/json");
1278 /// XML::addElement($doc, $root, "link", "", $attributes);
1280 self::hublinks($doc, $root, $owner["nick"]);
1282 $attributes = ["href" => System::baseUrl() . "/salmon/" . $owner["nick"], "rel" => "salmon"];
1283 XML::addElement($doc, $root, "link", "", $attributes);
1285 $attributes = ["href" => System::baseUrl() . "/salmon/" . $owner["nick"], "rel" => "http://salmon-protocol.org/ns/salmon-replies"];
1286 XML::addElement($doc, $root, "link", "", $attributes);
1288 $attributes = ["href" => System::baseUrl() . "/salmon/" . $owner["nick"], "rel" => "http://salmon-protocol.org/ns/salmon-mention"];
1289 XML::addElement($doc, $root, "link", "", $attributes);
1291 $attributes = ["href" => System::baseUrl() . "/api/statuses/user_timeline/" . $owner["nick"] . ".atom",
1292 "rel" => "self", "type" => "application/atom+xml"];
1293 XML::addElement($doc, $root, "link", "", $attributes);
1299 * @brief Add the link to the push hubs to the XML document
1301 * @param object $doc XML document
1302 * @param object $root XML root element where the hub links are added
1303 * @param object $nick nick
1306 public static function hublinks($doc, $root, $nick)
1308 $h = System::baseUrl() . '/pubsubhubbub/'.$nick;
1309 XML::addElement($doc, $root, "link", "", ["href" => $h, "rel" => "hub"]);
1313 * @brief Adds attachement data to the XML document
1315 * @param object $doc XML document
1316 * @param object $root XML root element where the hub links are added
1317 * @param array $item Data of the item that is to be posted
1320 private static function getAttachment($doc, $root, $item)
1323 $siteinfo = BBCode::getAttachedData($item["body"]);
1325 switch ($siteinfo["type"]) {
1327 $imgdata = Image::getInfoFromURL($siteinfo["image"]);
1328 $attributes = ["rel" => "enclosure",
1329 "href" => $siteinfo["image"],
1330 "type" => $imgdata["mime"],
1331 "length" => intval($imgdata["size"])];
1332 XML::addElement($doc, $root, "link", "", $attributes);
1335 $attributes = ["rel" => "enclosure",
1336 "href" => $siteinfo["url"],
1337 "type" => "text/html; charset=UTF-8",
1339 "title" => $siteinfo["title"]];
1340 XML::addElement($doc, $root, "link", "", $attributes);
1346 if (!Config::get('system', 'ostatus_not_attach_preview') && ($siteinfo["type"] != "photo") && isset($siteinfo["image"])) {
1347 $imgdata = Image::getInfoFromURL($siteinfo["image"]);
1348 $attributes = ["rel" => "enclosure",
1349 "href" => $siteinfo["image"],
1350 "type" => $imgdata["mime"],
1351 "length" => intval($imgdata["size"])];
1353 XML::addElement($doc, $root, "link", "", $attributes);
1356 $arr = explode('[/attach],', $item['attach']);
1358 foreach ($arr as $r) {
1360 $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"|', $r, $matches);
1362 $attributes = ["rel" => "enclosure",
1363 "href" => $matches[1],
1364 "type" => $matches[3]];
1366 if (intval($matches[2])) {
1367 $attributes["length"] = intval($matches[2]);
1369 if (trim($matches[4]) != "") {
1370 $attributes["title"] = trim($matches[4]);
1372 XML::addElement($doc, $root, "link", "", $attributes);
1379 * @brief Adds the author element to the XML document
1381 * @param object $doc XML document
1382 * @param array $owner Contact data of the poster
1384 * @return object author element
1386 private static function addAuthor($doc, $owner)
1388 $profile = dba::selectFirst('profile', ['homepage', 'publish'], ['uid' => $owner['uid'], 'is-default' => true]);
1389 $author = $doc->createElement("author");
1390 XML::addElement($doc, $author, "id", $owner["url"]);
1391 XML::addElement($doc, $author, "activity:object-type", ACTIVITY_OBJ_PERSON);
1392 XML::addElement($doc, $author, "uri", $owner["url"]);
1393 XML::addElement($doc, $author, "name", $owner["nick"]);
1394 XML::addElement($doc, $author, "email", $owner["addr"]);
1395 XML::addElement($doc, $author, "summary", BBCode::convert($owner["about"], false, 7));
1397 $attributes = ["rel" => "alternate", "type" => "text/html", "href" => $owner["url"]];
1398 XML::addElement($doc, $author, "link", "", $attributes);
1402 "type" => "image/jpeg", // To-Do?
1403 "media:width" => 175,
1404 "media:height" => 175,
1405 "href" => $owner["photo"]];
1406 XML::addElement($doc, $author, "link", "", $attributes);
1408 if (isset($owner["thumb"])) {
1411 "type" => "image/jpeg", // To-Do?
1412 "media:width" => 80,
1413 "media:height" => 80,
1414 "href" => $owner["thumb"]];
1415 XML::addElement($doc, $author, "link", "", $attributes);
1418 XML::addElement($doc, $author, "poco:preferredUsername", $owner["nick"]);
1419 XML::addElement($doc, $author, "poco:displayName", $owner["name"]);
1420 XML::addElement($doc, $author, "poco:note", BBCode::convert($owner["about"], false, 7));
1422 if (trim($owner["location"]) != "") {
1423 $element = $doc->createElement("poco:address");
1424 XML::addElement($doc, $element, "poco:formatted", $owner["location"]);
1425 $author->appendChild($element);
1428 if (DBM::is_result($profile)) {
1429 if (trim($profile["homepage"]) != "") {
1430 $urls = $doc->createElement("poco:urls");
1431 XML::addElement($doc, $urls, "poco:type", "homepage");
1432 XML::addElement($doc, $urls, "poco:value", $profile["homepage"]);
1433 XML::addElement($doc, $urls, "poco:primary", "true");
1434 $author->appendChild($urls);
1437 XML::addElement($doc, $author, "followers", "", ["url" => System::baseUrl()."/viewcontacts/".$owner["nick"]]);
1438 XML::addElement($doc, $author, "statusnet:profile_info", "", ["local_id" => $owner["uid"]]);
1441 if ($profile["publish"]) {
1442 XML::addElement($doc, $author, "mastodon:scope", "public");
1448 * @TODO Picture attachments should look like this:
1449 * <a href="https://status.pirati.ca/attachment/572819" title="https://status.pirati.ca/file/heluecht-20151202T222602-rd3u49p.gif"
1450 * class="attachment thumbnail" id="attachment-572819" rel="nofollow external">https://status.pirati.ca/attachment/572819</a>
1454 * @brief Returns the given activity if present - otherwise returns the "post" activity
1456 * @param array $item Data of the item that is to be posted
1458 * @return string activity
1460 private static function constructVerb($item)
1462 if ($item['verb']) {
1463 return $item['verb'];
1466 return ACTIVITY_POST;
1470 * @brief Returns the given object type if present - otherwise returns the "note" object type
1472 * @param array $item Data of the item that is to be posted
1474 * @return string Object type
1476 private static function constructObjecttype($item)
1478 if (in_array($item['object-type'], [ACTIVITY_OBJ_NOTE, ACTIVITY_OBJ_COMMENT]))
1479 return $item['object-type'];
1480 return ACTIVITY_OBJ_NOTE;
1484 * @brief Adds an entry element to the XML document
1486 * @param object $doc XML document
1487 * @param array $item Data of the item that is to be posted
1488 * @param array $owner Contact data of the poster
1489 * @param bool $toplevel optional default false
1491 * @return object Entry element
1493 private static function entry($doc, $item, $owner, $toplevel = false)
1497 $repeated_guid = self::getResharedGuid($item);
1498 if ($repeated_guid != "") {
1499 $xml = self::reshareEntry($doc, $item, $owner, $repeated_guid, $toplevel);
1506 if ($item["verb"] == ACTIVITY_LIKE) {
1507 return self::likeEntry($doc, $item, $owner, $toplevel);
1508 } elseif (in_array($item["verb"], [ACTIVITY_FOLLOW, NAMESPACE_OSTATUS."/unfollow"])) {
1509 return self::followEntry($doc, $item, $owner, $toplevel);
1511 return self::noteEntry($doc, $item, $owner, $toplevel);
1516 * @brief Adds a source entry to the XML document
1518 * @param object $doc XML document
1519 * @param array $contact Array of the contact that is added
1521 * @return object Source element
1523 private static function sourceEntry($doc, $contact)
1525 $source = $doc->createElement("source");
1526 XML::addElement($doc, $source, "id", $contact["poll"]);
1527 XML::addElement($doc, $source, "title", $contact["name"]);
1528 XML::addElement($doc, $source, "link", "", ["rel" => "alternate", "type" => "text/html", "href" => $contact["alias"]]);
1529 XML::addElement($doc, $source, "link", "", ["rel" => "self", "type" => "application/atom+xml", "href" => $contact["poll"]]);
1530 XML::addElement($doc, $source, "icon", $contact["photo"]);
1531 XML::addElement($doc, $source, "updated", DateTimeFormat::utc($contact["success_update"]."+00:00", DateTimeFormat::ATOM));
1537 * @brief Fetches contact data from the contact or the gcontact table
1539 * @param string $url URL of the contact
1540 * @param array $owner Contact data of the poster
1542 * @return array Contact array
1544 private static function contactEntry($url, $owner)
1547 "SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` IN (0, %d) ORDER BY `uid` DESC LIMIT 1",
1548 dbesc(normalise_link($url)),
1549 intval($owner["uid"])
1551 if (DBM::is_result($r)) {
1553 $contact["uid"] = -1;
1556 if (!DBM::is_result($r)) {
1558 "SELECT * FROM `gcontact` WHERE `nurl` = '%s' LIMIT 1",
1559 dbesc(normalise_link($url))
1561 if (DBM::is_result($r)) {
1563 $contact["uid"] = -1;
1564 $contact["success_update"] = $contact["updated"];
1568 if (!DBM::is_result($r)) {
1572 if (!isset($contact["poll"])) {
1573 $data = Probe::uri($url);
1574 $contact["poll"] = $data["poll"];
1576 if (!$contact["alias"]) {
1577 $contact["alias"] = $data["alias"];
1581 if (!isset($contact["alias"])) {
1582 $contact["alias"] = $contact["url"];
1589 * @brief Adds an entry element with reshared content
1591 * @param object $doc XML document
1592 * @param array $item Data of the item that is to be posted
1593 * @param array $owner Contact data of the poster
1594 * @param string $repeated_guid guid
1595 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1597 * @return object Entry element
1599 private static function reshareEntry($doc, $item, $owner, $repeated_guid, $toplevel)
1601 if (($item["id"] != $item["parent"]) && (normalise_link($item["author-link"]) != normalise_link($owner["url"]))) {
1602 logger("OStatus entry is from author ".$owner["url"]." - not from ".$item["author-link"].". Quitting.", LOGGER_DEBUG);
1605 $title = self::entryHeader($doc, $entry, $owner, $toplevel);
1608 "SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' AND NOT `private` AND `network` IN ('%s', '%s', '%s') LIMIT 1",
1609 intval($owner["uid"]),
1610 dbesc($repeated_guid),
1611 dbesc(NETWORK_DFRN),
1612 dbesc(NETWORK_DIASPORA),
1613 dbesc(NETWORK_OSTATUS)
1615 if (DBM::is_result($r)) {
1616 $repeated_item = $r[0];
1620 $contact = self::contactEntry($repeated_item['author-link'], $owner);
1622 $parent_item = (($item['thr-parent']) ? $item['thr-parent'] : $item['parent-uri']);
1624 $title = $owner["nick"]." repeated a notice by ".$contact["nick"];
1626 self::entryContent($doc, $entry, $item, $owner, $title, ACTIVITY_SHARE, false);
1628 $as_object = $doc->createElement("activity:object");
1630 XML::addElement($doc, $as_object, "activity:object-type", NAMESPACE_ACTIVITY_SCHEMA."activity");
1632 self::entryContent($doc, $as_object, $repeated_item, $owner, "", "", false);
1634 $author = self::addAuthor($doc, $contact);
1635 $as_object->appendChild($author);
1637 $as_object2 = $doc->createElement("activity:object");
1639 XML::addElement($doc, $as_object2, "activity:object-type", self::constructObjecttype($repeated_item));
1641 $title = sprintf("New comment by %s", $contact["nick"]);
1643 self::entryContent($doc, $as_object2, $repeated_item, $owner, $title);
1645 $as_object->appendChild($as_object2);
1647 self::entryFooter($doc, $as_object, $item, $owner, false);
1649 $source = self::sourceEntry($doc, $contact);
1651 $as_object->appendChild($source);
1653 $entry->appendChild($as_object);
1655 self::entryFooter($doc, $entry, $item, $owner);
1661 * @brief Adds an entry element with a "like"
1663 * @param object $doc XML document
1664 * @param array $item Data of the item that is to be posted
1665 * @param array $owner Contact data of the poster
1666 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1668 * @return object Entry element with "like"
1670 private static function likeEntry($doc, $item, $owner, $toplevel)
1672 if (($item["id"] != $item["parent"]) && (normalise_link($item["author-link"]) != normalise_link($owner["url"]))) {
1673 logger("OStatus entry is from author ".$owner["url"]." - not from ".$item["author-link"].". Quitting.", LOGGER_DEBUG);
1676 $title = self::entryHeader($doc, $entry, $owner, $toplevel);
1678 $verb = NAMESPACE_ACTIVITY_SCHEMA."favorite";
1679 self::entryContent($doc, $entry, $item, $owner, "Favorite", $verb, false);
1681 $as_object = $doc->createElement("activity:object");
1684 "SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d",
1685 dbesc($item["thr-parent"]),
1686 intval($item["uid"])
1688 $parent_item = (($item['thr-parent']) ? $item['thr-parent'] : $item['parent-uri']);
1690 XML::addElement($doc, $as_object, "activity:object-type", self::constructObjecttype($parent[0]));
1692 self::entryContent($doc, $as_object, $parent[0], $owner, "New entry");
1694 $entry->appendChild($as_object);
1696 self::entryFooter($doc, $entry, $item, $owner);
1702 * @brief Adds the person object element to the XML document
1704 * @param object $doc XML document
1705 * @param array $owner Contact data of the poster
1706 * @param array $contact Contact data of the target
1708 * @return object author element
1710 private static function addPersonObject($doc, $owner, $contact)
1712 $object = $doc->createElement("activity:object");
1713 XML::addElement($doc, $object, "activity:object-type", ACTIVITY_OBJ_PERSON);
1715 if ($contact['network'] == NETWORK_PHANTOM) {
1716 XML::addElement($doc, $object, "id", $contact['url']);
1720 XML::addElement($doc, $object, "id", $contact["alias"]);
1721 XML::addElement($doc, $object, "title", $contact["nick"]);
1723 $attributes = ["rel" => "alternate", "type" => "text/html", "href" => $contact["url"]];
1724 XML::addElement($doc, $object, "link", "", $attributes);
1728 "type" => "image/jpeg", // To-Do?
1729 "media:width" => 175,
1730 "media:height" => 175,
1731 "href" => $contact["photo"]];
1732 XML::addElement($doc, $object, "link", "", $attributes);
1734 XML::addElement($doc, $object, "poco:preferredUsername", $contact["nick"]);
1735 XML::addElement($doc, $object, "poco:displayName", $contact["name"]);
1737 if (trim($contact["location"]) != "") {
1738 $element = $doc->createElement("poco:address");
1739 XML::addElement($doc, $element, "poco:formatted", $contact["location"]);
1740 $object->appendChild($element);
1747 * @brief Adds a follow/unfollow entry element
1749 * @param object $doc XML document
1750 * @param array $item Data of the follow/unfollow message
1751 * @param array $owner Contact data of the poster
1752 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1754 * @return object Entry element
1756 private static function followEntry($doc, $item, $owner, $toplevel)
1758 $item["id"] = $item["parent"] = 0;
1759 $item["created"] = $item["edited"] = date("c");
1760 $item["private"] = true;
1762 $contact = Probe::uri($item['follow']);
1764 if ($contact['alias'] == '') {
1765 $contact['alias'] = $contact["url"];
1767 $item['follow'] = $contact['alias'];
1771 "SELECT `id` FROM `contact` WHERE `uid` = %d AND `nurl` = '%s'",
1772 intval($owner['uid']),
1773 dbesc(normalise_link($contact["url"]))
1776 if (DBM::is_result($r)) {
1777 $connect_id = $r[0]['id'];
1782 if ($item['verb'] == ACTIVITY_FOLLOW) {
1783 $message = L10n::t('%s is now following %s.');
1784 $title = L10n::t('following');
1785 $action = "subscription";
1787 $message = L10n::t('%s stopped following %s.');
1788 $title = L10n::t('stopped following');
1789 $action = "unfollow";
1792 $item["uri"] = $item['parent-uri'] = $item['thr-parent']
1793 = 'tag:'.get_app()->get_hostname().
1794 ','.date('Y-m-d').':'.$action.':'.$owner['uid'].
1795 ':person:'.$connect_id.':'.$item['created'];
1797 $item["body"] = sprintf($message, $owner["nick"], $contact["nick"]);
1799 self::entryHeader($doc, $entry, $owner, $toplevel);
1801 self::entryContent($doc, $entry, $item, $owner, $title);
1803 $object = self::addPersonObject($doc, $owner, $contact);
1804 $entry->appendChild($object);
1806 self::entryFooter($doc, $entry, $item, $owner);
1812 * @brief Adds a regular entry element
1814 * @param object $doc XML document
1815 * @param array $item Data of the item that is to be posted
1816 * @param array $owner Contact data of the poster
1817 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1819 * @return object Entry element
1821 private static function noteEntry($doc, $item, $owner, $toplevel)
1823 if (($item["id"] != $item["parent"]) && (normalise_link($item["author-link"]) != normalise_link($owner["url"]))) {
1824 logger("OStatus entry is from author ".$owner["url"]." - not from ".$item["author-link"].". Quitting.", LOGGER_DEBUG);
1827 $title = self::entryHeader($doc, $entry, $owner, $toplevel);
1829 XML::addElement($doc, $entry, "activity:object-type", ACTIVITY_OBJ_NOTE);
1831 self::entryContent($doc, $entry, $item, $owner, $title);
1833 self::entryFooter($doc, $entry, $item, $owner);
1839 * @brief Adds a header element to the XML document
1841 * @param object $doc XML document
1842 * @param object $entry The entry element where the elements are added
1843 * @param array $owner Contact data of the poster
1844 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1846 * @return string The title for the element
1848 private static function entryHeader($doc, &$entry, $owner, $toplevel)
1850 /// @todo Check if this title stuff is really needed (I guess not)
1852 $entry = $doc->createElement("entry");
1853 $title = sprintf("New note by %s", $owner["nick"]);
1855 $entry = $doc->createElementNS(NAMESPACE_ATOM1, "entry");
1857 $entry->setAttribute("xmlns:thr", NAMESPACE_THREAD);
1858 $entry->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
1859 $entry->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
1860 $entry->setAttribute("xmlns:media", NAMESPACE_MEDIA);
1861 $entry->setAttribute("xmlns:poco", NAMESPACE_POCO);
1862 $entry->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
1863 $entry->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
1864 $entry->setAttribute("xmlns:mastodon", NAMESPACE_MASTODON);
1866 $author = self::addAuthor($doc, $owner);
1867 $entry->appendChild($author);
1869 $title = sprintf("New comment by %s", $owner["nick"]);
1875 * @brief Adds elements to the XML document
1877 * @param object $doc XML document
1878 * @param object $entry Entry element where the content is added
1879 * @param array $item Data of the item that is to be posted
1880 * @param array $owner Contact data of the poster
1881 * @param string $title Title for the post
1882 * @param string $verb The activity verb
1883 * @param bool $complete Add the "status_net" element?
1886 private static function entryContent($doc, $entry, $item, $owner, $title, $verb = "", $complete = true)
1889 $verb = self::constructVerb($item);
1892 XML::addElement($doc, $entry, "id", $item["uri"]);
1893 XML::addElement($doc, $entry, "title", $title);
1895 $body = self::formatPicturePost($item['body']);
1897 if ($item['title'] != "") {
1898 $body = "[b]".$item['title']."[/b]\n\n".$body;
1901 $body = BBCode::convert($body, false, 7);
1903 XML::addElement($doc, $entry, "content", $body, ["type" => "html"]);
1905 XML::addElement($doc, $entry, "link", "", ["rel" => "alternate", "type" => "text/html",
1906 "href" => System::baseUrl()."/display/".$item["guid"]]
1909 if ($complete && ($item["id"] > 0)) {
1910 XML::addElement($doc, $entry, "status_net", "", ["notice_id" => $item["id"]]);
1913 XML::addElement($doc, $entry, "activity:verb", $verb);
1915 XML::addElement($doc, $entry, "published", DateTimeFormat::utc($item["created"]."+00:00", DateTimeFormat::ATOM));
1916 XML::addElement($doc, $entry, "updated", DateTimeFormat::utc($item["edited"]."+00:00", DateTimeFormat::ATOM));
1920 * @brief Adds the elements at the foot of an entry to the XML document
1922 * @param object $doc XML document
1923 * @param object $entry The entry element where the elements are added
1924 * @param array $item Data of the item that is to be posted
1925 * @param array $owner Contact data of the poster
1926 * @param bool $complete default true
1929 private static function entryFooter($doc, $entry, $item, $owner, $complete = true)
1933 if (($item['parent'] != $item['id']) || ($item['parent-uri'] !== $item['uri']) || (($item['thr-parent'] !== '') && ($item['thr-parent'] !== $item['uri']))) {
1934 $parent = q("SELECT `guid`, `author-link`, `owner-link` FROM `item` WHERE `id` = %d", intval($item["parent"]));
1935 $parent_item = (($item['thr-parent']) ? $item['thr-parent'] : $item['parent-uri']);
1938 "SELECT `guid`, `author-link`, `owner-link`, `plink` FROM `item` WHERE `uid` = %d AND `uri` = '%s'",
1939 intval($owner["uid"]),
1943 $mentioned[$thrparent[0]["author-link"]] = $thrparent[0]["author-link"];
1944 $mentioned[$thrparent[0]["owner-link"]] = $thrparent[0]["owner-link"];
1945 $parent_plink = $thrparent[0]["plink"];
1947 $mentioned[$parent[0]["author-link"]] = $parent[0]["author-link"];
1948 $mentioned[$parent[0]["owner-link"]] = $parent[0]["owner-link"];
1949 $parent_plink = System::baseUrl()."/display/".$parent[0]["guid"];
1953 "ref" => $parent_item,
1954 "href" => $parent_plink];
1955 XML::addElement($doc, $entry, "thr:in-reply-to", "", $attributes);
1959 "href" => $parent_plink];
1960 XML::addElement($doc, $entry, "link", "", $attributes);
1963 if (intval($item["parent"]) > 0) {
1964 $conversation_href = System::baseUrl()."/display/".$owner["nick"]."/".$item["parent"];
1965 $conversation_uri = $conversation_href;
1967 if (isset($parent_item)) {
1968 $r = dba::fetch_first("SELECT `conversation-uri`, `conversation-href` FROM `conversation` WHERE `item-uri` = ?", $parent_item);
1969 if (DBM::is_result($r)) {
1970 if ($r['conversation-uri'] != '') {
1971 $conversation_uri = $r['conversation-uri'];
1973 if ($r['conversation-href'] != '') {
1974 $conversation_href = $r['conversation-href'];
1979 XML::addElement($doc, $entry, "link", "", ["rel" => "ostatus:conversation", "href" => $conversation_href]);
1982 "href" => $conversation_href,
1983 "local_id" => $item["parent"],
1984 "ref" => $conversation_uri];
1986 XML::addElement($doc, $entry, "ostatus:conversation", $conversation_uri, $attributes);
1989 $tags = item::getFeedTags($item);
1992 foreach ($tags as $t) {
1994 $mentioned[$t[1]] = $t[1];
1999 // Make sure that mentions are accepted (GNU Social has problems with mixing HTTP and HTTPS)
2001 foreach ($mentioned as $mention) {
2002 $newmentions[str_replace("http://", "https://", $mention)] = str_replace("http://", "https://", $mention);
2003 $newmentions[str_replace("https://", "http://", $mention)] = str_replace("https://", "http://", $mention);
2005 $mentioned = $newmentions;
2007 foreach ($mentioned as $mention) {
2009 "SELECT `forum`, `prv` FROM `contact` WHERE `uid` = %d AND `nurl` = '%s'",
2010 intval($owner["uid"]),
2011 dbesc(normalise_link($mention))
2013 if ($r[0]["forum"] || $r[0]["prv"]) {
2014 XML::addElement($doc, $entry, "link", "",
2016 "rel" => "mentioned",
2017 "ostatus:object-type" => ACTIVITY_OBJ_GROUP,
2021 XML::addElement($doc, $entry, "link", "",
2023 "rel" => "mentioned",
2024 "ostatus:object-type" => ACTIVITY_OBJ_PERSON,
2030 if (!$item["private"]) {
2031 XML::addElement($doc, $entry, "link", "", ["rel" => "ostatus:attention",
2032 "href" => "http://activityschema.org/collection/public"]);
2033 XML::addElement($doc, $entry, "link", "", ["rel" => "mentioned",
2034 "ostatus:object-type" => "http://activitystrea.ms/schema/1.0/collection",
2035 "href" => "http://activityschema.org/collection/public"]);
2036 XML::addElement($doc, $entry, "mastodon:scope", "public");
2040 foreach ($tags as $t) {
2042 XML::addElement($doc, $entry, "category", "", ["term" => $t[2]]);
2047 self::getAttachment($doc, $entry, $item);
2049 if ($complete && ($item["id"] > 0)) {
2050 $app = $item["app"];
2055 $attributes = ["local_id" => $item["id"], "source" => $app];
2057 if (isset($parent["id"])) {
2058 $attributes["repeat_of"] = $parent["id"];
2061 if ($item["coord"] != "") {
2062 XML::addElement($doc, $entry, "georss:point", $item["coord"]);
2065 XML::addElement($doc, $entry, "statusnet:notice_info", "", $attributes);
2070 * Creates the XML feed for a given nickname
2072 * Supported filters:
2073 * - activity (default): all the public posts
2074 * - posts: all the public top-level posts
2075 * - comments: all the public replies
2077 * Updates the provided last_update parameter if the result comes from the
2078 * cache or it is empty
2080 * @brief Creates the XML feed for a given nickname
2082 * @param string $owner_nick Nickname of the feed owner
2083 * @param string $last_update Date of the last update
2084 * @param integer $max_items Number of maximum items to fetch
2085 * @param string $filter Feed items filter (activity, posts or comments)
2086 * @param boolean $nocache Wether to bypass caching
2088 * @return string XML feed
2090 public static function feed($owner_nick, &$last_update, $max_items = 300, $filter = 'activity', $nocache = false)
2092 $stamp = microtime(true);
2094 $cachekey = "ostatus:feed:" . $owner_nick . ":" . $filter . ":" . $last_update;
2096 $previous_created = $last_update;
2098 $result = Cache::get($cachekey);
2099 if (!$nocache && !is_null($result)) {
2100 logger('Feed duration: ' . number_format(microtime(true) - $stamp, 3) . ' - ' . $owner_nick . ' - ' . $filter . ' - ' . $previous_created . ' (cached)', LOGGER_DEBUG);
2101 $last_update = $result['last_update'];
2102 return $result['feed'];
2105 $owner = dba::fetch_first(
2106 "SELECT `contact`.*, `user`.`nickname`, `user`.`timezone`, `user`.`page-flags`, `user`.`account-type`
2107 FROM `contact` INNER JOIN `user` ON `user`.`uid` = `contact`.`uid`
2108 WHERE `contact`.`self` AND `user`.`nickname` = ? LIMIT 1",
2111 if (!DBM::is_result($owner)) {
2115 if (!strlen($last_update)) {
2116 $last_update = 'now -30 days';
2119 $check_date = DateTimeFormat::utc($last_update);
2120 $authorid = Contact::getIdForURL($owner["url"], 0, true);
2123 if ($filter === 'posts') {
2124 $sql_extra .= ' AND `item`.`id` = `item`.`parent` ';
2127 if ($filter === 'comments') {
2128 $sql_extra .= sprintf(" AND `item`.`object-type` = '%s' ", dbesc(ACTIVITY_OBJ_COMMENT));
2131 if ($owner['account-type'] != ACCOUNT_TYPE_COMMUNITY) {
2132 $sql_extra .= sprintf(" AND `item`.`contact-id` = %d AND `item`.`author-id` = %d ", intval($owner["id"]), intval($authorid));
2136 "SELECT `item`.*, `item`.`id` AS `item_id` FROM `item` USE INDEX (`uid_contactid_created`)
2137 STRAIGHT_JOIN `thread` ON `thread`.`iid` = `item`.`parent`
2138 WHERE `item`.`uid` = %d
2139 AND `item`.`created` > '%s'
2140 AND NOT `item`.`deleted`
2141 AND NOT `item`.`private`
2142 AND `item`.`visible`
2144 AND `thread`.`network` IN ('%s', '%s')
2146 ORDER BY `item`.`created` DESC LIMIT %d",
2147 intval($owner["uid"]),
2149 dbesc(NETWORK_OSTATUS),
2150 dbesc(NETWORK_DFRN),
2154 $doc = new DOMDocument('1.0', 'utf-8');
2155 $doc->formatOutput = true;
2157 $root = self::addHeader($doc, $owner, $filter);
2159 foreach ($items as $item) {
2160 if (Config::get('system', 'ostatus_debug')) {
2161 $item['body'] .= '🍼';
2163 $entry = self::entry($doc, $item, $owner);
2164 $root->appendChild($entry);
2166 if ($last_update < $item['created']) {
2167 $last_update = $item['created'];
2171 $feeddata = trim($doc->saveXML());
2173 $msg = ['feed' => $feeddata, 'last_update' => $last_update];
2174 Cache::set($cachekey, $msg, CACHE_QUARTER_HOUR);
2176 logger('Feed duration: ' . number_format(microtime(true) - $stamp, 3) . ' - ' . $owner_nick . ' - ' . $filter . ' - ' . $previous_created, LOGGER_DEBUG);
2182 * @brief Creates the XML for a salmon message
2184 * @param array $item Data of the item that is to be posted
2185 * @param array $owner Contact data of the poster
2187 * @return string XML for the salmon
2189 public static function salmon($item, $owner)
2191 $doc = new DOMDocument('1.0', 'utf-8');
2192 $doc->formatOutput = true;
2194 if (Config::get('system', 'ostatus_debug')) {
2195 $item['body'] .= '🐟';
2198 $entry = self::entry($doc, $item, $owner, true);
2200 $doc->appendChild($entry);
2202 return trim($doc->saveXML());