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;
607 $categories = $xpath->query('atom:category', $entry);
609 foreach ($categories as $category) {
610 foreach ($category->attributes as $attributes) {
611 if ($attributes->name == "term") {
612 $term = $attributes->textContent;
613 if (strlen($item["tag"])) {
616 $item["tag"] .= "#[url=".System::baseUrl()."/search?tag=".$term."]".$term."[/url]";
625 $links = $xpath->query('atom:link', $entry);
627 $link_data = self::processLinks($links, $item);
628 $self = $link_data['self'];
629 $add_body = $link_data['add_body'];
634 $notice_info = $xpath->query('statusnet:notice_info', $entry);
635 if ($notice_info && ($notice_info->length > 0)) {
636 foreach ($notice_info->item(0)->attributes as $attributes) {
637 if ($attributes->name == "source") {
638 $item["app"] = strip_tags($attributes->textContent);
640 if ($attributes->name == "repeat_of") {
641 $repeat_of = $attributes->textContent;
645 // Is it a repeated post?
646 if (($repeat_of != "") || ($item["verb"] == ACTIVITY_SHARE)) {
647 $link_data = self::processRepeatedItem($xpath, $entry, $item, $importer);
648 if (!empty($link_data['add_body'])) {
649 $add_body .= $link_data['add_body'];
653 $item["body"] .= $add_body;
655 // Only add additional data when there is no picture in the post
656 if (!strstr($item["body"], '[/img]')) {
657 $item["body"] = add_page_info_to_body($item["body"]);
660 // Mastodon Content Warning
661 if (($item["verb"] == ACTIVITY_POST) && $xpath->evaluate('boolean(atom:summary)', $entry)) {
662 $clear_text = $xpath->query('atom:summary/text()', $entry)->item(0)->nodeValue;
664 $item["body"] = html2bbcode($clear_text) . '[spoiler]' . $item["body"] . '[/spoiler]';
667 if (($self != '') && empty($item['protocol'])) {
668 self::fetchSelf($self, $item);
671 if (!empty($item["conversation-href"])) {
672 self::fetchConversation($item['conversation-href'], $item['conversation-uri']);
675 if (isset($item["parent-uri"]) && ($related != '')) {
676 if (!dba::exists('item', ['uid' => $importer["uid"], 'uri' => $item['parent-uri']])) {
677 self::fetchRelated($related, $item["parent-uri"], $importer);
679 logger('Reply with URI '.$item["uri"].' already existed for user '.$importer["uid"].'.', LOGGER_DEBUG);
682 $item["type"] = 'remote-comment';
683 $item["gravity"] = GRAVITY_COMMENT;
685 $item["parent-uri"] = $item["uri"];
688 if (($item['author-link'] != '') && !empty($item['protocol'])) {
689 $item = Conversation::insert($item);
692 self::$itemlist[] = $item;
696 * @brief Fetch the conversation for posts
698 * @param string $conversation The link to the conversation
699 * @param string $conversation_uri The conversation in "uri" format
702 private static function fetchConversation($conversation, $conversation_uri)
704 // Ensure that we only store a conversation once in a process
705 if (isset(self::$conv_list[$conversation])) {
709 self::$conv_list[$conversation] = true;
711 $conversation_data = Network::curl($conversation, false, $redirects, ['accept_content' => 'application/atom+xml, text/html']);
713 if (!$conversation_data['success']) {
719 if (stristr($conversation_data['header'], 'Content-Type: application/atom+xml')) {
720 $xml = $conversation_data['body'];
724 $doc = new DOMDocument();
725 if (!@$doc->loadHTML($conversation_data['body'])) {
728 $xpath = new DOMXPath($doc);
730 $links = $xpath->query('//link');
733 foreach ($links as $link) {
734 $attribute = self::readAttributes($link);
735 if (($attribute['rel'] == 'alternate') && ($attribute['type'] == 'application/atom+xml')) {
736 $file = $attribute['href'];
740 $conversation_atom = Network::curl($attribute['href']);
742 if ($conversation_atom['success']) {
743 $xml = $conversation_atom['body'];
753 self::storeConversation($xml, $conversation, $conversation_uri);
757 * @brief Store a feed in several conversation entries
759 * @param string $xml The feed
760 * @param string $conversation conversation
761 * @param string $conversation_uri conversation uri
764 private static function storeConversation($xml, $conversation = '', $conversation_uri = '')
766 $doc = new DOMDocument();
767 @$doc->loadXML($xml);
769 $xpath = new DOMXPath($doc);
770 $xpath->registerNamespace('atom', NAMESPACE_ATOM1);
771 $xpath->registerNamespace('thr', NAMESPACE_THREAD);
772 $xpath->registerNamespace('ostatus', NAMESPACE_OSTATUS);
774 $entries = $xpath->query('/atom:feed/atom:entry');
776 // Now store the entries
777 foreach ($entries as $entry) {
778 $doc2 = new DOMDocument();
779 $doc2->preserveWhiteSpace = false;
780 $doc2->formatOutput = true;
784 $conv_data['protocol'] = PROTOCOL_SPLITTED_CONV;
785 $conv_data['network'] = NETWORK_OSTATUS;
786 $conv_data['uri'] = $xpath->query('atom:id/text()', $entry)->item(0)->nodeValue;
788 $inreplyto = $xpath->query('thr:in-reply-to', $entry);
789 if (is_object($inreplyto->item(0))) {
790 foreach ($inreplyto->item(0)->attributes as $attributes) {
791 if ($attributes->name == "ref") {
792 $conv_data['reply-to-uri'] = $attributes->textContent;
797 $conv = $xpath->query('ostatus:conversation/text()', $entry)->item(0)->nodeValue;
798 $conv_data['conversation-uri'] = $conv;
800 $conv = $xpath->query('ostatus:conversation', $entry);
801 if (is_object($conv->item(0))) {
802 foreach ($conv->item(0)->attributes as $attributes) {
803 if ($attributes->name == "ref") {
804 $conv_data['conversation-uri'] = $attributes->textContent;
806 if ($attributes->name == "href") {
807 $conv_data['conversation-href'] = $attributes->textContent;
812 if ($conversation != '') {
813 $conv_data['conversation-uri'] = $conversation;
816 if ($conversation_uri != '') {
817 $conv_data['conversation-uri'] = $conversation_uri;
820 $entry = $doc2->importNode($entry, true);
822 $doc2->appendChild($entry);
824 $conv_data['source'] = $doc2->saveXML();
826 $condition = ['item-uri' => $conv_data['uri'],'protocol' => PROTOCOL_OSTATUS_FEED];
827 if (dba::exists('conversation', $condition)) {
828 logger('Delete deprecated entry for URI '.$conv_data['uri'], LOGGER_DEBUG);
829 dba::delete('conversation', ['item-uri' => $conv_data['uri']]);
832 logger('Store conversation data for uri '.$conv_data['uri'], LOGGER_DEBUG);
833 Conversation::insert($conv_data);
838 * @brief Fetch the own post so that it can be stored later
840 * We want to store the original data for later processing.
841 * This function is meant for cases where we process a feed with multiple entries.
842 * In that case we need to fetch the single posts here.
844 * @param string $self The link to the self item
845 * @param array $item The item array
848 private static function fetchSelf($self, &$item)
850 $condition = ['`item-uri` = ? AND `protocol` IN (?, ?)', $self, PROTOCOL_DFRN, PROTOCOL_OSTATUS_SALMON];
851 if (dba::exists('conversation', $condition)) {
852 logger('Conversation '.$item['uri'].' is already stored.', LOGGER_DEBUG);
856 $self_data = Network::curl($self);
858 if (!$self_data['success']) {
862 // We reformat the XML to make it better readable
863 $doc = new DOMDocument();
864 $doc->loadXML($self_data['body']);
865 $doc->preserveWhiteSpace = false;
866 $doc->formatOutput = true;
867 $xml = $doc->saveXML();
869 $item["protocol"] = PROTOCOL_OSTATUS_SALMON;
870 $item["source"] = $xml;
872 logger('Conversation '.$item['uri'].' is now fetched.', LOGGER_DEBUG);
876 * @brief Fetch related posts and processes them
878 * @param string $related The link to the related item
879 * @param string $related_uri The related item in "uri" format
880 * @param array $importer user record of the importing user
883 private static function fetchRelated($related, $related_uri, $importer)
885 $condition = ['`item-uri` = ? AND `protocol` IN (?, ?)', $related_uri, PROTOCOL_DFRN, PROTOCOL_OSTATUS_SALMON];
886 $conversation = dba::selectFirst('conversation', ['source', 'protocol'], $condition);
887 if (DBM::is_result($conversation)) {
889 $xml = $conversation['source'];
890 if (self::process($xml, $importer, $contact, $hub, $stored, false)) {
891 logger('Got valid cached XML for URI '.$related_uri, LOGGER_DEBUG);
894 if ($conversation['protocol'] == PROTOCOL_OSTATUS_SALMON) {
895 logger('Delete invalid cached XML for URI '.$related_uri, LOGGER_DEBUG);
896 dba::delete('conversation', ['item-uri' => $related_uri]);
901 $related_data = Network::curl($related, false, $redirects, ['accept_content' => 'application/atom+xml, text/html']);
903 if (!$related_data['success']) {
909 if (stristr($related_data['header'], 'Content-Type: application/atom+xml')) {
910 logger('Directly fetched XML for URI '.$related_uri, LOGGER_DEBUG);
911 $xml = $related_data['body'];
915 $doc = new DOMDocument();
916 if (!@$doc->loadHTML($related_data['body'])) {
919 $xpath = new DOMXPath($doc);
923 $links = $xpath->query('//link');
925 foreach ($links as $link) {
926 $attribute = self::readAttributes($link);
927 if (($attribute['rel'] == 'alternate') && ($attribute['type'] == 'application/atom+xml')) {
928 $atom_file = $attribute['href'];
931 if ($atom_file != '') {
932 $related_atom = Network::curl($atom_file);
934 if ($related_atom['success']) {
935 logger('Fetched XML for URI '.$related_uri, LOGGER_DEBUG);
936 $xml = $related_atom['body'];
942 // Workaround for older GNU Social servers
943 if (($xml == '') && strstr($related, '/notice/')) {
944 $related_atom = Network::curl(str_replace('/notice/', '/api/statuses/show/', $related).'.atom');
946 if ($related_atom['success']) {
947 logger('GNU Social workaround to fetch XML for URI '.$related_uri, LOGGER_DEBUG);
948 $xml = $related_atom['body'];
952 // Even more worse workaround for GNU Social ;-)
954 $related_guess = OStatus::convertHref($related_uri);
955 $related_atom = Network::curl(str_replace('/notice/', '/api/statuses/show/', $related_guess).'.atom');
957 if ($related_atom['success']) {
958 logger('GNU Social workaround 2 to fetch XML for URI '.$related_uri, LOGGER_DEBUG);
959 $xml = $related_atom['body'];
963 // Finally we take the data that we fetched from "ostatus:conversation"
965 $condition = ['item-uri' => $related_uri, 'protocol' => PROTOCOL_SPLITTED_CONV];
966 $conversation = dba::selectFirst('conversation', ['source'], $condition);
967 if (DBM::is_result($conversation)) {
969 logger('Got cached XML from conversation for URI '.$related_uri, LOGGER_DEBUG);
970 $xml = $conversation['source'];
975 self::process($xml, $importer, $contact, $hub, $stored, false);
977 logger("XML couldn't be fetched for URI: ".$related_uri." - href: ".$related, LOGGER_DEBUG);
983 * @brief Processes the XML for a repeated post
985 * @param object $xpath The xpath object
986 * @param object $entry The xml entry that is processed
987 * @param array $item The item array
988 * @param array $importer user record of the importing user
990 * @return array with data from links
992 private static function processRepeatedItem($xpath, $entry, &$item, $importer)
994 $activityobjects = $xpath->query('activity:object', $entry)->item(0);
996 if (!is_object($activityobjects)) {
1002 $orig_uri = $xpath->query('atom:id/text()', $activityobjects)->item(0)->nodeValue;
1004 $links = $xpath->query("atom:link", $activityobjects);
1006 $link_data = self::processLinks($links, $item);
1009 $orig_body = $xpath->query('atom:content/text()', $activityobjects)->item(0)->nodeValue;
1010 $orig_created = $xpath->query('atom:published/text()', $activityobjects)->item(0)->nodeValue;
1011 $orig_edited = $xpath->query('atom:updated/text()', $activityobjects)->item(0)->nodeValue;
1013 $orig_author = self::fetchAuthor($xpath, $activityobjects, $importer, $dummy, false);
1015 $item["author-name"] = $orig_author["author-name"];
1016 $item["author-link"] = $orig_author["author-link"];
1017 $item["author-avatar"] = $orig_author["author-avatar"];
1019 $item["body"] = html2bbcode($orig_body);
1020 $item["created"] = $orig_created;
1021 $item["edited"] = $orig_edited;
1023 $item["uri"] = $orig_uri;
1025 $item["verb"] = $xpath->query('activity:verb/text()', $activityobjects)->item(0)->nodeValue;
1027 $item["object-type"] = $xpath->query('activity:object-type/text()', $activityobjects)->item(0)->nodeValue;
1029 $inreplyto = $xpath->query('thr:in-reply-to', $activityobjects);
1030 if (is_object($inreplyto->item(0))) {
1031 foreach ($inreplyto->item(0)->attributes as $attributes) {
1032 if ($attributes->name == "ref") {
1033 $item["parent-uri"] = $attributes->textContent;
1042 * @brief Processes links in the XML
1044 * @param object $links The xml data that contain links
1045 * @param array $item The item array
1047 * @return array with data from the links
1049 private static function processLinks($links, &$item)
1051 $link_data = ['add_body' => '', 'self' => ''];
1053 foreach ($links as $link) {
1054 $attribute = self::readAttributes($link);
1056 if (($attribute['rel'] != "") && ($attribute['href'] != "")) {
1057 switch ($attribute['rel']) {
1059 $item["plink"] = $attribute['href'];
1060 if (($item["object-type"] == ACTIVITY_OBJ_QUESTION)
1061 || ($item["object-type"] == ACTIVITY_OBJ_EVENT)
1063 $item["body"] .= add_page_info($attribute['href']);
1066 case "ostatus:conversation":
1067 $link_data['conversation'] = $attribute['href'];
1068 $item['conversation-href'] = $link_data['conversation'];
1069 if (!isset($item['conversation-uri'])) {
1070 $item['conversation-uri'] = $item['conversation-href'];
1074 $filetype = strtolower(substr($attribute['type'], 0, strpos($attribute['type'], '/')));
1075 if ($filetype == 'image') {
1076 $link_data['add_body'] .= "\n[img]".$attribute['href'].'[/img]';
1078 if (strlen($item["attach"])) {
1079 $item["attach"] .= ',';
1081 if (!isset($attribute['length'])) {
1082 $attribute['length'] = "0";
1084 $item["attach"] .= '[attach]href="'.$attribute['href'].'" length="'.$attribute['length'].'" type="'.$attribute['type'].'" title="'.$attribute['title'].'"[/attach]';
1088 if ($item["object-type"] != ACTIVITY_OBJ_BOOKMARK) {
1089 if (!isset($item["parent-uri"])) {
1090 $item["parent-uri"] = $attribute['href'];
1092 $link_data['related'] = $attribute['href'];
1094 $item["body"] .= add_page_info($attribute['href']);
1098 if ($item["plink"] == '') {
1099 $item["plink"] = $attribute['href'];
1101 $link_data['self'] = $attribute['href'];
1110 * @brief Create an url out of an uri
1112 * @param string $href URI in the format "parameter1:parameter1:..."
1114 * @return string URL in the format http(s)://....
1116 public static function convertHref($href)
1118 $elements = explode(":", $href);
1120 if ((count($elements) <= 2) || ($elements[0] != "tag")) {
1124 $server = explode(",", $elements[1]);
1125 $conversation = explode("=", $elements[2]);
1127 if ((count($elements) == 4) && ($elements[2] == "post")) {
1128 return "http://".$server[0]."/notice/".$elements[3];
1131 if ((count($conversation) != 2) || ($conversation[1] =="")) {
1134 if ($elements[3] == "objectType=thread") {
1135 return "http://".$server[0]."/conversation/".$conversation[1];
1137 return "http://".$server[0]."/notice/".$conversation[1];
1143 * @brief Checks if the current post is a reshare
1145 * @param array $item The item array of thw post
1147 * @return string The guid if the post is a reshare
1149 private static function getResharedGuid($item)
1151 $body = trim($item["body"]);
1153 // Skip if it isn't a pure repeated messages
1154 // Does it start with a share?
1155 if (strpos($body, "[share") > 0) {
1159 // Does it end with a share?
1160 if (strlen($body) > (strrpos($body, "[/share]") + 8)) {
1164 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "$1", $body);
1165 // Skip if there is no shared message in there
1166 if ($body == $attributes) {
1171 preg_match("/guid='(.*?)'/ism", $attributes, $matches);
1172 if ($matches[1] != "") {
1173 $guid = $matches[1];
1176 preg_match('/guid="(.*?)"/ism', $attributes, $matches);
1177 if ($matches[1] != "") {
1178 $guid = $matches[1];
1185 * @brief Cleans the body of a post if it contains picture links
1187 * @param string $body The body
1189 * @return string The cleaned body
1191 private static function formatPicturePost($body)
1193 $siteinfo = BBCode::getAttachedData($body);
1195 if (($siteinfo["type"] == "photo")) {
1196 if (isset($siteinfo["preview"])) {
1197 $preview = $siteinfo["preview"];
1199 $preview = $siteinfo["image"];
1202 // Is it a remote picture? Then make a smaller preview here
1203 $preview = proxy_url($preview, false, PROXY_SIZE_SMALL);
1205 // Is it a local picture? Then make it smaller here
1206 $preview = str_replace(["-0.jpg", "-0.png"], ["-2.jpg", "-2.png"], $preview);
1207 $preview = str_replace(["-1.jpg", "-1.png"], ["-2.jpg", "-2.png"], $preview);
1209 if (isset($siteinfo["url"])) {
1210 $url = $siteinfo["url"];
1212 $url = $siteinfo["image"];
1215 $body = trim($siteinfo["text"])." [url]".$url."[/url]\n[img]".$preview."[/img]";
1222 * @brief Adds the header elements to the XML document
1224 * @param object $doc XML document
1225 * @param array $owner Contact data of the poster
1226 * @param string $filter The related feed filter (activity, posts or comments)
1228 * @return object header root element
1230 private static function addHeader($doc, $owner, $filter)
1234 $root = $doc->createElementNS(NAMESPACE_ATOM1, 'feed');
1235 $doc->appendChild($root);
1237 $root->setAttribute("xmlns:thr", NAMESPACE_THREAD);
1238 $root->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
1239 $root->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
1240 $root->setAttribute("xmlns:media", NAMESPACE_MEDIA);
1241 $root->setAttribute("xmlns:poco", NAMESPACE_POCO);
1242 $root->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
1243 $root->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
1244 $root->setAttribute("xmlns:mastodon", NAMESPACE_MASTODON);
1248 case 'activity': $title = L10n::t('%s\'s timeline', $owner['name']); break;
1249 case 'posts' : $title = L10n::t('%s\'s posts' , $owner['name']); break;
1250 case 'comments': $title = L10n::t('%s\'s comments', $owner['name']); break;
1253 $attributes = ["uri" => "https://friendi.ca", "version" => FRIENDICA_VERSION . "-" . DB_UPDATE_VERSION];
1254 XML::addElement($doc, $root, "generator", FRIENDICA_PLATFORM, $attributes);
1255 XML::addElement($doc, $root, "id", System::baseUrl() . "/profile/" . $owner["nick"]);
1256 XML::addElement($doc, $root, "title", $title);
1257 XML::addElement($doc, $root, "subtitle", sprintf("Updates from %s on %s", $owner["name"], $a->config["sitename"]));
1258 XML::addElement($doc, $root, "logo", $owner["photo"]);
1259 XML::addElement($doc, $root, "updated", DateTimeFormat::utcNow(DateTimeFormat::ATOM));
1261 $author = self::addAuthor($doc, $owner);
1262 $root->appendChild($author);
1264 $attributes = ["href" => $owner["url"], "rel" => "alternate", "type" => "text/html"];
1265 XML::addElement($doc, $root, "link", "", $attributes);
1267 /// @TODO We have to find out what this is
1268 /// $attributes = array("href" => System::baseUrl()."/sup",
1269 /// "rel" => "http://api.friendfeed.com/2008/03#sup",
1270 /// "type" => "application/json");
1271 /// XML::addElement($doc, $root, "link", "", $attributes);
1273 self::hublinks($doc, $root, $owner["nick"]);
1275 $attributes = ["href" => System::baseUrl() . "/salmon/" . $owner["nick"], "rel" => "salmon"];
1276 XML::addElement($doc, $root, "link", "", $attributes);
1278 $attributes = ["href" => System::baseUrl() . "/salmon/" . $owner["nick"], "rel" => "http://salmon-protocol.org/ns/salmon-replies"];
1279 XML::addElement($doc, $root, "link", "", $attributes);
1281 $attributes = ["href" => System::baseUrl() . "/salmon/" . $owner["nick"], "rel" => "http://salmon-protocol.org/ns/salmon-mention"];
1282 XML::addElement($doc, $root, "link", "", $attributes);
1284 $attributes = ["href" => System::baseUrl() . "/api/statuses/user_timeline/" . $owner["nick"] . ".atom",
1285 "rel" => "self", "type" => "application/atom+xml"];
1286 XML::addElement($doc, $root, "link", "", $attributes);
1292 * @brief Add the link to the push hubs to the XML document
1294 * @param object $doc XML document
1295 * @param object $root XML root element where the hub links are added
1296 * @param object $nick nick
1299 public static function hublinks($doc, $root, $nick)
1301 $h = System::baseUrl() . '/pubsubhubbub/'.$nick;
1302 XML::addElement($doc, $root, "link", "", ["href" => $h, "rel" => "hub"]);
1306 * @brief Adds attachement data to the XML document
1308 * @param object $doc XML document
1309 * @param object $root XML root element where the hub links are added
1310 * @param array $item Data of the item that is to be posted
1313 private static function getAttachment($doc, $root, $item)
1316 $siteinfo = BBCode::getAttachedData($item["body"]);
1318 switch ($siteinfo["type"]) {
1320 $imgdata = Image::getInfoFromURL($siteinfo["image"]);
1321 $attributes = ["rel" => "enclosure",
1322 "href" => $siteinfo["image"],
1323 "type" => $imgdata["mime"],
1324 "length" => intval($imgdata["size"])];
1325 XML::addElement($doc, $root, "link", "", $attributes);
1328 $attributes = ["rel" => "enclosure",
1329 "href" => $siteinfo["url"],
1330 "type" => "text/html; charset=UTF-8",
1332 "title" => $siteinfo["title"]];
1333 XML::addElement($doc, $root, "link", "", $attributes);
1339 if (!Config::get('system', 'ostatus_not_attach_preview') && ($siteinfo["type"] != "photo") && isset($siteinfo["image"])) {
1340 $imgdata = Image::getInfoFromURL($siteinfo["image"]);
1341 $attributes = ["rel" => "enclosure",
1342 "href" => $siteinfo["image"],
1343 "type" => $imgdata["mime"],
1344 "length" => intval($imgdata["size"])];
1346 XML::addElement($doc, $root, "link", "", $attributes);
1349 $arr = explode('[/attach],', $item['attach']);
1351 foreach ($arr as $r) {
1353 $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"|', $r, $matches);
1355 $attributes = ["rel" => "enclosure",
1356 "href" => $matches[1],
1357 "type" => $matches[3]];
1359 if (intval($matches[2])) {
1360 $attributes["length"] = intval($matches[2]);
1362 if (trim($matches[4]) != "") {
1363 $attributes["title"] = trim($matches[4]);
1365 XML::addElement($doc, $root, "link", "", $attributes);
1372 * @brief Adds the author element to the XML document
1374 * @param object $doc XML document
1375 * @param array $owner Contact data of the poster
1377 * @return object author element
1379 private static function addAuthor($doc, $owner)
1381 $profile = dba::selectFirst('profile', ['homepage', 'publish'], ['uid' => $owner['uid'], 'is-default' => true]);
1382 $author = $doc->createElement("author");
1383 XML::addElement($doc, $author, "id", $owner["url"]);
1384 XML::addElement($doc, $author, "activity:object-type", ACTIVITY_OBJ_PERSON);
1385 XML::addElement($doc, $author, "uri", $owner["url"]);
1386 XML::addElement($doc, $author, "name", $owner["nick"]);
1387 XML::addElement($doc, $author, "email", $owner["addr"]);
1388 XML::addElement($doc, $author, "summary", BBCode::convert($owner["about"], false, 7));
1390 $attributes = ["rel" => "alternate", "type" => "text/html", "href" => $owner["url"]];
1391 XML::addElement($doc, $author, "link", "", $attributes);
1395 "type" => "image/jpeg", // To-Do?
1396 "media:width" => 175,
1397 "media:height" => 175,
1398 "href" => $owner["photo"]];
1399 XML::addElement($doc, $author, "link", "", $attributes);
1401 if (isset($owner["thumb"])) {
1404 "type" => "image/jpeg", // To-Do?
1405 "media:width" => 80,
1406 "media:height" => 80,
1407 "href" => $owner["thumb"]];
1408 XML::addElement($doc, $author, "link", "", $attributes);
1411 XML::addElement($doc, $author, "poco:preferredUsername", $owner["nick"]);
1412 XML::addElement($doc, $author, "poco:displayName", $owner["name"]);
1413 XML::addElement($doc, $author, "poco:note", BBCode::convert($owner["about"], false, 7));
1415 if (trim($owner["location"]) != "") {
1416 $element = $doc->createElement("poco:address");
1417 XML::addElement($doc, $element, "poco:formatted", $owner["location"]);
1418 $author->appendChild($element);
1421 if (DBM::is_result($profile)) {
1422 if (trim($profile["homepage"]) != "") {
1423 $urls = $doc->createElement("poco:urls");
1424 XML::addElement($doc, $urls, "poco:type", "homepage");
1425 XML::addElement($doc, $urls, "poco:value", $profile["homepage"]);
1426 XML::addElement($doc, $urls, "poco:primary", "true");
1427 $author->appendChild($urls);
1430 XML::addElement($doc, $author, "followers", "", ["url" => System::baseUrl()."/viewcontacts/".$owner["nick"]]);
1431 XML::addElement($doc, $author, "statusnet:profile_info", "", ["local_id" => $owner["uid"]]);
1434 if ($profile["publish"]) {
1435 XML::addElement($doc, $author, "mastodon:scope", "public");
1441 * @TODO Picture attachments should look like this:
1442 * <a href="https://status.pirati.ca/attachment/572819" title="https://status.pirati.ca/file/heluecht-20151202T222602-rd3u49p.gif"
1443 * class="attachment thumbnail" id="attachment-572819" rel="nofollow external">https://status.pirati.ca/attachment/572819</a>
1447 * @brief Returns the given activity if present - otherwise returns the "post" activity
1449 * @param array $item Data of the item that is to be posted
1451 * @return string activity
1453 private static function constructVerb($item)
1455 if ($item['verb']) {
1456 return $item['verb'];
1459 return ACTIVITY_POST;
1463 * @brief Returns the given object type if present - otherwise returns the "note" object type
1465 * @param array $item Data of the item that is to be posted
1467 * @return string Object type
1469 private static function constructObjecttype($item)
1471 if (in_array($item['object-type'], [ACTIVITY_OBJ_NOTE, ACTIVITY_OBJ_COMMENT]))
1472 return $item['object-type'];
1473 return ACTIVITY_OBJ_NOTE;
1477 * @brief Adds an entry element to the XML document
1479 * @param object $doc XML document
1480 * @param array $item Data of the item that is to be posted
1481 * @param array $owner Contact data of the poster
1482 * @param bool $toplevel optional default false
1484 * @return object Entry element
1486 private static function entry($doc, $item, $owner, $toplevel = false)
1490 $repeated_guid = self::getResharedGuid($item);
1491 if ($repeated_guid != "") {
1492 $xml = self::reshareEntry($doc, $item, $owner, $repeated_guid, $toplevel);
1499 if ($item["verb"] == ACTIVITY_LIKE) {
1500 return self::likeEntry($doc, $item, $owner, $toplevel);
1501 } elseif (in_array($item["verb"], [ACTIVITY_FOLLOW, NAMESPACE_OSTATUS."/unfollow"])) {
1502 return self::followEntry($doc, $item, $owner, $toplevel);
1504 return self::noteEntry($doc, $item, $owner, $toplevel);
1509 * @brief Adds a source entry to the XML document
1511 * @param object $doc XML document
1512 * @param array $contact Array of the contact that is added
1514 * @return object Source element
1516 private static function sourceEntry($doc, $contact)
1518 $source = $doc->createElement("source");
1519 XML::addElement($doc, $source, "id", $contact["poll"]);
1520 XML::addElement($doc, $source, "title", $contact["name"]);
1521 XML::addElement($doc, $source, "link", "", ["rel" => "alternate", "type" => "text/html", "href" => $contact["alias"]]);
1522 XML::addElement($doc, $source, "link", "", ["rel" => "self", "type" => "application/atom+xml", "href" => $contact["poll"]]);
1523 XML::addElement($doc, $source, "icon", $contact["photo"]);
1524 XML::addElement($doc, $source, "updated", DateTimeFormat::utc($contact["success_update"]."+00:00", DateTimeFormat::ATOM));
1530 * @brief Fetches contact data from the contact or the gcontact table
1532 * @param string $url URL of the contact
1533 * @param array $owner Contact data of the poster
1535 * @return array Contact array
1537 private static function contactEntry($url, $owner)
1540 "SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` IN (0, %d) ORDER BY `uid` DESC LIMIT 1",
1541 dbesc(normalise_link($url)),
1542 intval($owner["uid"])
1544 if (DBM::is_result($r)) {
1546 $contact["uid"] = -1;
1549 if (!DBM::is_result($r)) {
1551 "SELECT * FROM `gcontact` WHERE `nurl` = '%s' LIMIT 1",
1552 dbesc(normalise_link($url))
1554 if (DBM::is_result($r)) {
1556 $contact["uid"] = -1;
1557 $contact["success_update"] = $contact["updated"];
1561 if (!DBM::is_result($r)) {
1565 if (!isset($contact["poll"])) {
1566 $data = Probe::uri($url);
1567 $contact["poll"] = $data["poll"];
1569 if (!$contact["alias"]) {
1570 $contact["alias"] = $data["alias"];
1574 if (!isset($contact["alias"])) {
1575 $contact["alias"] = $contact["url"];
1582 * @brief Adds an entry element with reshared content
1584 * @param object $doc XML document
1585 * @param array $item Data of the item that is to be posted
1586 * @param array $owner Contact data of the poster
1587 * @param string $repeated_guid guid
1588 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1590 * @return object Entry element
1592 private static function reshareEntry($doc, $item, $owner, $repeated_guid, $toplevel)
1594 if (($item["id"] != $item["parent"]) && (normalise_link($item["author-link"]) != normalise_link($owner["url"]))) {
1595 logger("OStatus entry is from author ".$owner["url"]." - not from ".$item["author-link"].". Quitting.", LOGGER_DEBUG);
1598 $title = self::entryHeader($doc, $entry, $owner, $toplevel);
1601 "SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' AND NOT `private` AND `network` IN ('%s', '%s', '%s') LIMIT 1",
1602 intval($owner["uid"]),
1603 dbesc($repeated_guid),
1604 dbesc(NETWORK_DFRN),
1605 dbesc(NETWORK_DIASPORA),
1606 dbesc(NETWORK_OSTATUS)
1608 if (DBM::is_result($r)) {
1609 $repeated_item = $r[0];
1613 $contact = self::contactEntry($repeated_item['author-link'], $owner);
1615 $parent_item = (($item['thr-parent']) ? $item['thr-parent'] : $item['parent-uri']);
1617 $title = $owner["nick"]." repeated a notice by ".$contact["nick"];
1619 self::entryContent($doc, $entry, $item, $owner, $title, ACTIVITY_SHARE, false);
1621 $as_object = $doc->createElement("activity:object");
1623 XML::addElement($doc, $as_object, "activity:object-type", NAMESPACE_ACTIVITY_SCHEMA."activity");
1625 self::entryContent($doc, $as_object, $repeated_item, $owner, "", "", false);
1627 $author = self::addAuthor($doc, $contact);
1628 $as_object->appendChild($author);
1630 $as_object2 = $doc->createElement("activity:object");
1632 XML::addElement($doc, $as_object2, "activity:object-type", self::constructObjecttype($repeated_item));
1634 $title = sprintf("New comment by %s", $contact["nick"]);
1636 self::entryContent($doc, $as_object2, $repeated_item, $owner, $title);
1638 $as_object->appendChild($as_object2);
1640 self::entryFooter($doc, $as_object, $item, $owner, false);
1642 $source = self::sourceEntry($doc, $contact);
1644 $as_object->appendChild($source);
1646 $entry->appendChild($as_object);
1648 self::entryFooter($doc, $entry, $item, $owner);
1654 * @brief Adds an entry element with a "like"
1656 * @param object $doc XML document
1657 * @param array $item Data of the item that is to be posted
1658 * @param array $owner Contact data of the poster
1659 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1661 * @return object Entry element with "like"
1663 private static function likeEntry($doc, $item, $owner, $toplevel)
1665 if (($item["id"] != $item["parent"]) && (normalise_link($item["author-link"]) != normalise_link($owner["url"]))) {
1666 logger("OStatus entry is from author ".$owner["url"]." - not from ".$item["author-link"].". Quitting.", LOGGER_DEBUG);
1669 $title = self::entryHeader($doc, $entry, $owner, $toplevel);
1671 $verb = NAMESPACE_ACTIVITY_SCHEMA."favorite";
1672 self::entryContent($doc, $entry, $item, $owner, "Favorite", $verb, false);
1674 $as_object = $doc->createElement("activity:object");
1677 "SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d",
1678 dbesc($item["thr-parent"]),
1679 intval($item["uid"])
1681 $parent_item = (($item['thr-parent']) ? $item['thr-parent'] : $item['parent-uri']);
1683 XML::addElement($doc, $as_object, "activity:object-type", self::constructObjecttype($parent[0]));
1685 self::entryContent($doc, $as_object, $parent[0], $owner, "New entry");
1687 $entry->appendChild($as_object);
1689 self::entryFooter($doc, $entry, $item, $owner);
1695 * @brief Adds the person object element to the XML document
1697 * @param object $doc XML document
1698 * @param array $owner Contact data of the poster
1699 * @param array $contact Contact data of the target
1701 * @return object author element
1703 private static function addPersonObject($doc, $owner, $contact)
1705 $object = $doc->createElement("activity:object");
1706 XML::addElement($doc, $object, "activity:object-type", ACTIVITY_OBJ_PERSON);
1708 if ($contact['network'] == NETWORK_PHANTOM) {
1709 XML::addElement($doc, $object, "id", $contact['url']);
1713 XML::addElement($doc, $object, "id", $contact["alias"]);
1714 XML::addElement($doc, $object, "title", $contact["nick"]);
1716 $attributes = ["rel" => "alternate", "type" => "text/html", "href" => $contact["url"]];
1717 XML::addElement($doc, $object, "link", "", $attributes);
1721 "type" => "image/jpeg", // To-Do?
1722 "media:width" => 175,
1723 "media:height" => 175,
1724 "href" => $contact["photo"]];
1725 XML::addElement($doc, $object, "link", "", $attributes);
1727 XML::addElement($doc, $object, "poco:preferredUsername", $contact["nick"]);
1728 XML::addElement($doc, $object, "poco:displayName", $contact["name"]);
1730 if (trim($contact["location"]) != "") {
1731 $element = $doc->createElement("poco:address");
1732 XML::addElement($doc, $element, "poco:formatted", $contact["location"]);
1733 $object->appendChild($element);
1740 * @brief Adds a follow/unfollow entry element
1742 * @param object $doc XML document
1743 * @param array $item Data of the follow/unfollow message
1744 * @param array $owner Contact data of the poster
1745 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1747 * @return object Entry element
1749 private static function followEntry($doc, $item, $owner, $toplevel)
1751 $item["id"] = $item["parent"] = 0;
1752 $item["created"] = $item["edited"] = date("c");
1753 $item["private"] = true;
1755 $contact = Probe::uri($item['follow']);
1757 if ($contact['alias'] == '') {
1758 $contact['alias'] = $contact["url"];
1760 $item['follow'] = $contact['alias'];
1764 "SELECT `id` FROM `contact` WHERE `uid` = %d AND `nurl` = '%s'",
1765 intval($owner['uid']),
1766 dbesc(normalise_link($contact["url"]))
1769 if (DBM::is_result($r)) {
1770 $connect_id = $r[0]['id'];
1775 if ($item['verb'] == ACTIVITY_FOLLOW) {
1776 $message = L10n::t('%s is now following %s.');
1777 $title = L10n::t('following');
1778 $action = "subscription";
1780 $message = L10n::t('%s stopped following %s.');
1781 $title = L10n::t('stopped following');
1782 $action = "unfollow";
1785 $item["uri"] = $item['parent-uri'] = $item['thr-parent']
1786 = 'tag:'.get_app()->get_hostname().
1787 ','.date('Y-m-d').':'.$action.':'.$owner['uid'].
1788 ':person:'.$connect_id.':'.$item['created'];
1790 $item["body"] = sprintf($message, $owner["nick"], $contact["nick"]);
1792 self::entryHeader($doc, $entry, $owner, $toplevel);
1794 self::entryContent($doc, $entry, $item, $owner, $title);
1796 $object = self::addPersonObject($doc, $owner, $contact);
1797 $entry->appendChild($object);
1799 self::entryFooter($doc, $entry, $item, $owner);
1805 * @brief Adds a regular entry element
1807 * @param object $doc XML document
1808 * @param array $item Data of the item that is to be posted
1809 * @param array $owner Contact data of the poster
1810 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1812 * @return object Entry element
1814 private static function noteEntry($doc, $item, $owner, $toplevel)
1816 if (($item["id"] != $item["parent"]) && (normalise_link($item["author-link"]) != normalise_link($owner["url"]))) {
1817 logger("OStatus entry is from author ".$owner["url"]." - not from ".$item["author-link"].". Quitting.", LOGGER_DEBUG);
1820 $title = self::entryHeader($doc, $entry, $owner, $toplevel);
1822 XML::addElement($doc, $entry, "activity:object-type", ACTIVITY_OBJ_NOTE);
1824 self::entryContent($doc, $entry, $item, $owner, $title);
1826 self::entryFooter($doc, $entry, $item, $owner);
1832 * @brief Adds a header element to the XML document
1834 * @param object $doc XML document
1835 * @param object $entry The entry element where the elements are added
1836 * @param array $owner Contact data of the poster
1837 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1839 * @return string The title for the element
1841 private static function entryHeader($doc, &$entry, $owner, $toplevel)
1843 /// @todo Check if this title stuff is really needed (I guess not)
1845 $entry = $doc->createElement("entry");
1846 $title = sprintf("New note by %s", $owner["nick"]);
1848 $entry = $doc->createElementNS(NAMESPACE_ATOM1, "entry");
1850 $entry->setAttribute("xmlns:thr", NAMESPACE_THREAD);
1851 $entry->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
1852 $entry->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
1853 $entry->setAttribute("xmlns:media", NAMESPACE_MEDIA);
1854 $entry->setAttribute("xmlns:poco", NAMESPACE_POCO);
1855 $entry->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
1856 $entry->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
1857 $entry->setAttribute("xmlns:mastodon", NAMESPACE_MASTODON);
1859 $author = self::addAuthor($doc, $owner);
1860 $entry->appendChild($author);
1862 $title = sprintf("New comment by %s", $owner["nick"]);
1868 * @brief Adds elements to the XML document
1870 * @param object $doc XML document
1871 * @param object $entry Entry element where the content is added
1872 * @param array $item Data of the item that is to be posted
1873 * @param array $owner Contact data of the poster
1874 * @param string $title Title for the post
1875 * @param string $verb The activity verb
1876 * @param bool $complete Add the "status_net" element?
1879 private static function entryContent($doc, $entry, $item, $owner, $title, $verb = "", $complete = true)
1882 $verb = self::constructVerb($item);
1885 XML::addElement($doc, $entry, "id", $item["uri"]);
1886 XML::addElement($doc, $entry, "title", $title);
1888 $body = self::formatPicturePost($item['body']);
1890 if ($item['title'] != "") {
1891 $body = "[b]".$item['title']."[/b]\n\n".$body;
1894 $body = BBCode::convert($body, false, 7);
1896 XML::addElement($doc, $entry, "content", $body, ["type" => "html"]);
1898 XML::addElement($doc, $entry, "link", "", ["rel" => "alternate", "type" => "text/html",
1899 "href" => System::baseUrl()."/display/".$item["guid"]]
1902 if ($complete && ($item["id"] > 0)) {
1903 XML::addElement($doc, $entry, "status_net", "", ["notice_id" => $item["id"]]);
1906 XML::addElement($doc, $entry, "activity:verb", $verb);
1908 XML::addElement($doc, $entry, "published", DateTimeFormat::utc($item["created"]."+00:00", DateTimeFormat::ATOM));
1909 XML::addElement($doc, $entry, "updated", DateTimeFormat::utc($item["edited"]."+00:00", DateTimeFormat::ATOM));
1913 * @brief Adds the elements at the foot of an entry to the XML document
1915 * @param object $doc XML document
1916 * @param object $entry The entry element where the elements are added
1917 * @param array $item Data of the item that is to be posted
1918 * @param array $owner Contact data of the poster
1919 * @param bool $complete default true
1922 private static function entryFooter($doc, $entry, $item, $owner, $complete = true)
1926 if (($item['parent'] != $item['id']) || ($item['parent-uri'] !== $item['uri']) || (($item['thr-parent'] !== '') && ($item['thr-parent'] !== $item['uri']))) {
1927 $parent = q("SELECT `guid`, `author-link`, `owner-link` FROM `item` WHERE `id` = %d", intval($item["parent"]));
1928 $parent_item = (($item['thr-parent']) ? $item['thr-parent'] : $item['parent-uri']);
1931 "SELECT `guid`, `author-link`, `owner-link`, `plink` FROM `item` WHERE `uid` = %d AND `uri` = '%s'",
1932 intval($owner["uid"]),
1936 $mentioned[$thrparent[0]["author-link"]] = $thrparent[0]["author-link"];
1937 $mentioned[$thrparent[0]["owner-link"]] = $thrparent[0]["owner-link"];
1938 $parent_plink = $thrparent[0]["plink"];
1940 $mentioned[$parent[0]["author-link"]] = $parent[0]["author-link"];
1941 $mentioned[$parent[0]["owner-link"]] = $parent[0]["owner-link"];
1942 $parent_plink = System::baseUrl()."/display/".$parent[0]["guid"];
1946 "ref" => $parent_item,
1947 "href" => $parent_plink];
1948 XML::addElement($doc, $entry, "thr:in-reply-to", "", $attributes);
1952 "href" => $parent_plink];
1953 XML::addElement($doc, $entry, "link", "", $attributes);
1956 if (intval($item["parent"]) > 0) {
1957 $conversation_href = System::baseUrl()."/display/".$owner["nick"]."/".$item["parent"];
1958 $conversation_uri = $conversation_href;
1960 if (isset($parent_item)) {
1961 $r = dba::fetch_first("SELECT `conversation-uri`, `conversation-href` FROM `conversation` WHERE `item-uri` = ?", $parent_item);
1962 if (DBM::is_result($r)) {
1963 if ($r['conversation-uri'] != '') {
1964 $conversation_uri = $r['conversation-uri'];
1966 if ($r['conversation-href'] != '') {
1967 $conversation_href = $r['conversation-href'];
1972 XML::addElement($doc, $entry, "link", "", ["rel" => "ostatus:conversation", "href" => $conversation_href]);
1975 "href" => $conversation_href,
1976 "local_id" => $item["parent"],
1977 "ref" => $conversation_uri];
1979 XML::addElement($doc, $entry, "ostatus:conversation", $conversation_uri, $attributes);
1982 $tags = item::getFeedTags($item);
1985 foreach ($tags as $t) {
1987 $mentioned[$t[1]] = $t[1];
1992 // Make sure that mentions are accepted (GNU Social has problems with mixing HTTP and HTTPS)
1994 foreach ($mentioned as $mention) {
1995 $newmentions[str_replace("http://", "https://", $mention)] = str_replace("http://", "https://", $mention);
1996 $newmentions[str_replace("https://", "http://", $mention)] = str_replace("https://", "http://", $mention);
1998 $mentioned = $newmentions;
2000 foreach ($mentioned as $mention) {
2002 "SELECT `forum`, `prv` FROM `contact` WHERE `uid` = %d AND `nurl` = '%s'",
2003 intval($owner["uid"]),
2004 dbesc(normalise_link($mention))
2006 if ($r[0]["forum"] || $r[0]["prv"]) {
2007 XML::addElement($doc, $entry, "link", "",
2009 "rel" => "mentioned",
2010 "ostatus:object-type" => ACTIVITY_OBJ_GROUP,
2014 XML::addElement($doc, $entry, "link", "",
2016 "rel" => "mentioned",
2017 "ostatus:object-type" => ACTIVITY_OBJ_PERSON,
2023 if (!$item["private"]) {
2024 XML::addElement($doc, $entry, "link", "", ["rel" => "ostatus:attention",
2025 "href" => "http://activityschema.org/collection/public"]);
2026 XML::addElement($doc, $entry, "link", "", ["rel" => "mentioned",
2027 "ostatus:object-type" => "http://activitystrea.ms/schema/1.0/collection",
2028 "href" => "http://activityschema.org/collection/public"]);
2029 XML::addElement($doc, $entry, "mastodon:scope", "public");
2033 foreach ($tags as $t) {
2035 XML::addElement($doc, $entry, "category", "", ["term" => $t[2]]);
2040 self::getAttachment($doc, $entry, $item);
2042 if ($complete && ($item["id"] > 0)) {
2043 $app = $item["app"];
2048 $attributes = ["local_id" => $item["id"], "source" => $app];
2050 if (isset($parent["id"])) {
2051 $attributes["repeat_of"] = $parent["id"];
2054 if ($item["coord"] != "") {
2055 XML::addElement($doc, $entry, "georss:point", $item["coord"]);
2058 XML::addElement($doc, $entry, "statusnet:notice_info", "", $attributes);
2063 * Creates the XML feed for a given nickname
2065 * Supported filters:
2066 * - activity (default): all the public posts
2067 * - posts: all the public top-level posts
2068 * - comments: all the public replies
2070 * Updates the provided last_update parameter if the result comes from the
2071 * cache or it is empty
2073 * @brief Creates the XML feed for a given nickname
2075 * @param string $owner_nick Nickname of the feed owner
2076 * @param string $last_update Date of the last update
2077 * @param integer $max_items Number of maximum items to fetch
2078 * @param string $filter Feed items filter (activity, posts or comments)
2079 * @param boolean $nocache Wether to bypass caching
2081 * @return string XML feed
2083 public static function feed($owner_nick, &$last_update, $max_items = 300, $filter = 'activity', $nocache = false)
2085 $stamp = microtime(true);
2087 $cachekey = "ostatus:feed:" . $owner_nick . ":" . $filter . ":" . $last_update;
2089 $previous_created = $last_update;
2091 $result = Cache::get($cachekey);
2092 if (!$nocache && !is_null($result)) {
2093 logger('Feed duration: ' . number_format(microtime(true) - $stamp, 3) . ' - ' . $owner_nick . ' - ' . $filter . ' - ' . $previous_created . ' (cached)', LOGGER_DEBUG);
2094 $last_update = $result['last_update'];
2095 return $result['feed'];
2098 $owner = dba::fetch_first(
2099 "SELECT `contact`.*, `user`.`nickname`, `user`.`timezone`, `user`.`page-flags`, `user`.`account-type`
2100 FROM `contact` INNER JOIN `user` ON `user`.`uid` = `contact`.`uid`
2101 WHERE `contact`.`self` AND `user`.`nickname` = ? LIMIT 1",
2104 if (!DBM::is_result($owner)) {
2108 if (!strlen($last_update)) {
2109 $last_update = 'now -30 days';
2112 $check_date = DateTimeFormat::utc($last_update);
2113 $authorid = Contact::getIdForURL($owner["url"], 0, true);
2116 if ($filter === 'posts') {
2117 $sql_extra .= ' AND `item`.`id` = `item`.`parent` ';
2120 if ($filter === 'comments') {
2121 $sql_extra .= sprintf(" AND `item`.`object-type` = '%s' ", dbesc(ACTIVITY_OBJ_COMMENT));
2124 if ($owner['account-type'] != ACCOUNT_TYPE_COMMUNITY) {
2125 $sql_extra .= sprintf(" AND `item`.`contact-id` = %d AND `item`.`author-id` = %d ", intval($owner["id"]), intval($authorid));
2129 "SELECT `item`.*, `item`.`id` AS `item_id` FROM `item` USE INDEX (`uid_contactid_created`)
2130 STRAIGHT_JOIN `thread` ON `thread`.`iid` = `item`.`parent`
2131 WHERE `item`.`uid` = %d
2132 AND `item`.`created` > '%s'
2133 AND NOT `item`.`deleted`
2134 AND NOT `item`.`private`
2135 AND `item`.`visible`
2137 AND `thread`.`network` IN ('%s', '%s')
2139 ORDER BY `item`.`created` DESC LIMIT %d",
2140 intval($owner["uid"]),
2142 dbesc(NETWORK_OSTATUS),
2143 dbesc(NETWORK_DFRN),
2147 $doc = new DOMDocument('1.0', 'utf-8');
2148 $doc->formatOutput = true;
2150 $root = self::addHeader($doc, $owner, $filter);
2152 foreach ($items as $item) {
2153 if (Config::get('system', 'ostatus_debug')) {
2154 $item['body'] .= '🍼';
2156 $entry = self::entry($doc, $item, $owner);
2157 $root->appendChild($entry);
2159 if ($last_update < $item['created']) {
2160 $last_update = $item['created'];
2164 $feeddata = trim($doc->saveXML());
2166 $msg = ['feed' => $feeddata, 'last_update' => $last_update];
2167 Cache::set($cachekey, $msg, CACHE_QUARTER_HOUR);
2169 logger('Feed duration: ' . number_format(microtime(true) - $stamp, 3) . ' - ' . $owner_nick . ' - ' . $filter . ' - ' . $previous_created, LOGGER_DEBUG);
2175 * @brief Creates the XML for a salmon message
2177 * @param array $item Data of the item that is to be posted
2178 * @param array $owner Contact data of the poster
2180 * @return string XML for the salmon
2182 public static function salmon($item, $owner)
2184 $doc = new DOMDocument('1.0', 'utf-8');
2185 $doc->formatOutput = true;
2187 if (Config::get('system', 'ostatus_debug')) {
2188 $item['body'] .= '🐟';
2191 $entry = self::entry($doc, $item, $owner, true);
2193 $doc->appendChild($entry);
2195 return trim($doc->saveXML());