3 * @file src/Protocol/OStatus.php
5 namespace Friendica\Protocol;
9 use Friendica\Content\Text\BBCode;
10 use Friendica\Content\Text\HTML;
11 use Friendica\Core\Cache;
12 use Friendica\Core\Config;
13 use Friendica\Core\L10n;
14 use Friendica\Core\Lock;
15 use Friendica\Core\System;
16 use Friendica\Database\DBA;
17 use Friendica\Database\DBM;
18 use Friendica\Model\Contact;
19 use Friendica\Model\Conversation;
20 use Friendica\Model\GContact;
21 use Friendica\Model\Item;
22 use Friendica\Model\User;
23 use Friendica\Network\Probe;
24 use Friendica\Object\Image;
25 use Friendica\Util\DateTimeFormat;
26 use Friendica\Util\Network;
27 use Friendica\Util\XML;
29 require_once 'include/dba.php';
30 require_once 'include/items.php';
31 require_once 'mod/share.php';
32 require_once 'include/enotify.php';
33 require_once 'include/api.php';
34 require_once 'mod/proxy.php';
37 * @brief This class contain functions for the OStatus protocol
41 private static $itemlist;
42 private static $conv_list = [];
45 * @brief Fetches author data
47 * @param object $xpath The xpath object
48 * @param object $context The xml context of the author details
49 * @param array $importer user record of the importing user
50 * @param array $contact Called by reference, will contain the fetched contact
51 * @param bool $onlyfetch Only fetch the header without updating the contact entries
53 * @return array Array of author related entries for the item
55 private static function fetchAuthor($xpath, $context, $importer, &$contact, $onlyfetch)
58 $author["author-link"] = XML::getFirstNodeValue($xpath, 'atom:author/atom:uri/text()', $context);
59 $author["author-name"] = XML::getFirstNodeValue($xpath, 'atom:author/atom:name/text()', $context);
60 $addr = XML::getFirstNodeValue($xpath, 'atom:author/atom:email/text()', $context);
62 $aliaslink = $author["author-link"];
64 $alternate_item = $xpath->query("atom:author/atom:link[@rel='alternate']", $context)->item(0);
65 if (is_object($alternate_item)) {
66 foreach ($alternate_item->attributes as $attributes) {
67 if (($attributes->name == "href") && ($attributes->textContent != "")) {
68 $author["author-link"] = $attributes->textContent;
72 $author["author-id"] = Contact::getIdForURL($author["author-link"]);
74 $author["contact-id"] = $contact["id"];
77 if ($aliaslink != '') {
78 $condition = ["`uid` = ? AND `alias` = ? AND `network` != ? AND `rel` IN (?, ?)",
79 $importer["uid"], $aliaslink, NETWORK_STATUSNET,
80 CONTACT_IS_SHARING, CONTACT_IS_FRIEND];
81 $contact = DBA::selectFirst('contact', [], $condition);
84 if (!DBM::is_result($contact) && $author["author-link"] != '') {
85 if ($aliaslink == "") {
86 $aliaslink = $author["author-link"];
89 $condition = ["`uid` = ? AND `nurl` IN (?, ?) AND `network` != ? AND `rel` IN (?, ?)",
90 $importer["uid"], normalise_link($author["author-link"]), normalise_link($aliaslink),
91 NETWORK_STATUSNET, CONTACT_IS_SHARING, CONTACT_IS_FRIEND];
92 $contact = DBA::selectFirst('contact', [], $condition);
95 if (!DBM::is_result($contact) && ($addr != '')) {
96 $condition = ["`uid` = ? AND `addr` = ? AND `network` != ? AND `rel` IN (?, ?)",
97 $importer["uid"], $addr, NETWORK_STATUSNET,
98 CONTACT_IS_SHARING, CONTACT_IS_FRIEND];
99 $contact = DBA::selectFirst('contact', [], $condition);
102 if (DBM::is_result($contact)) {
103 if ($contact['blocked']) {
106 $author["contact-id"] = $contact["id"];
110 $avatars = $xpath->query("atom:author/atom:link[@rel='avatar']", $context);
111 foreach ($avatars as $avatar) {
114 foreach ($avatar->attributes as $attributes) {
115 if ($attributes->name == "href") {
116 $href = $attributes->textContent;
118 if ($attributes->name == "width") {
119 $width = $attributes->textContent;
123 $avatarlist[$width] = $href;
126 if (count($avatarlist) > 0) {
128 $author["author-avatar"] = Probe::fixAvatar(current($avatarlist), $author["author-link"]);
131 $displayname = XML::getFirstNodeValue($xpath, 'atom:author/poco:displayName/text()', $context);
132 if ($displayname != "") {
133 $author["author-name"] = $displayname;
136 $author["owner-id"] = $author["author-id"];
138 // Only update the contacts if it is an OStatus contact
139 if (DBM::is_result($contact) && ($contact['id'] > 0) && !$onlyfetch && ($contact["network"] == NETWORK_OSTATUS)) {
141 // Update contact data
143 unset($current['name-date']);
145 // This query doesn't seem to work
146 // $value = $xpath->query("atom:link[@rel='salmon']", $context)->item(0)->nodeValue;
148 // $contact["notify"] = $value;
150 // This query doesn't seem to work as well - I hate these queries
151 // $value = $xpath->query("atom:link[@rel='self' and @type='application/atom+xml']", $context)->item(0)->nodeValue;
153 // $contact["poll"] = $value;
155 $contact['url'] = $author["author-link"];
156 $contact['nurl'] = normalise_link($contact['url']);
158 $value = XML::getFirstNodeValue($xpath, 'atom:author/atom:uri/text()', $context);
160 $contact["alias"] = $value;
163 $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:displayName/text()', $context);
165 $contact["name"] = $value;
168 $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:preferredUsername/text()', $context);
170 $contact["nick"] = $value;
173 $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:note/text()', $context);
175 $contact["about"] = HTML::toBBCode($value);
178 $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:address/poco:formatted/text()', $context);
180 $contact["location"] = $value;
183 $contact['name-date'] = DateTimeFormat::utcNow();
185 DBA::update('contact', $contact, ['id' => $contact["id"]], $current);
187 if (!empty($author["author-avatar"]) && ($author["author-avatar"] != $current['avatar'])) {
188 logger("Update profile picture for contact ".$contact["id"], LOGGER_DEBUG);
189 Contact::updateAvatar($author["author-avatar"], $importer["uid"], $contact["id"]);
192 // Ensure that we are having this contact (with uid=0)
193 $cid = Contact::getIdForURL($aliaslink, 0, true);
196 $fields = ['url', 'nurl', 'name', 'nick', 'alias', 'about', 'location'];
197 $old_contact = DBA::selectFirst('contact', $fields, ['id' => $cid]);
199 // Update it with the current values
200 $fields = ['url' => $author["author-link"], 'name' => $contact["name"],
201 'nurl' => normalise_link($author["author-link"]),
202 'nick' => $contact["nick"], 'alias' => $contact["alias"],
203 'about' => $contact["about"], 'location' => $contact["location"],
204 'success_update' => DateTimeFormat::utcNow(), 'last-update' => DateTimeFormat::utcNow()];
206 DBA::update('contact', $fields, ['id' => $cid], $old_contact);
209 if (!empty($author["author-avatar"])) {
210 Contact::updateAvatar($author["author-avatar"], 0, $cid);
214 $contact["generation"] = 2;
215 $contact["hide"] = false; // OStatus contacts are never hidden
216 if (!empty($author["author-avatar"])) {
217 $contact["photo"] = $author["author-avatar"];
219 $gcid = GContact::update($contact);
221 GContact::link($gcid, $contact["uid"], $contact["id"]);
228 * @brief Fetches author data from a given XML string
230 * @param string $xml The XML
231 * @param array $importer user record of the importing user
233 * @return array Array of author related entries for the item
235 public static function salmonAuthor($xml, $importer)
241 $doc = new DOMDocument();
242 @$doc->loadXML($xml);
244 $xpath = new DOMXPath($doc);
245 $xpath->registerNamespace('atom', NAMESPACE_ATOM1);
246 $xpath->registerNamespace('thr', NAMESPACE_THREAD);
247 $xpath->registerNamespace('georss', NAMESPACE_GEORSS);
248 $xpath->registerNamespace('activity', NAMESPACE_ACTIVITY);
249 $xpath->registerNamespace('media', NAMESPACE_MEDIA);
250 $xpath->registerNamespace('poco', NAMESPACE_POCO);
251 $xpath->registerNamespace('ostatus', NAMESPACE_OSTATUS);
252 $xpath->registerNamespace('statusnet', NAMESPACE_STATUSNET);
254 $contact = ["id" => 0];
256 // Fetch the first author
257 $authordata = $xpath->query('//author')->item(0);
258 $author = self::fetchAuthor($xpath, $authordata, $importer, $contact, true);
263 * @brief Read attributes from element
265 * @param object $element Element object
267 * @return array attributes
269 private static function readAttributes($element)
273 foreach ($element->attributes as $attributes) {
274 $attribute[$attributes->name] = $attributes->textContent;
281 * @brief Imports an XML string containing OStatus elements
283 * @param string $xml The XML
284 * @param array $importer user record of the importing user
285 * @param array $contact contact
286 * @param string $hub Called by reference, returns the fetched hub data
289 public static function import($xml, $importer, &$contact, &$hub)
291 self::process($xml, $importer, $contact, $hub);
295 * @brief Internal feed processing
297 * @param string $xml The XML
298 * @param array $importer user record of the importing user
299 * @param array $contact contact
300 * @param string $hub Called by reference, returns the fetched hub data
301 * @param boolean $stored Is the post fresh imported or from the database?
302 * @param boolean $initialize Is it the leading post so that data has to be initialized?
304 * @return boolean Could the XML be processed?
306 private static function process($xml, $importer, &$contact, &$hub, $stored = false, $initialize = true)
309 self::$itemlist = [];
310 self::$conv_list = [];
313 logger("Import OStatus message", LOGGER_DEBUG);
318 $doc = new DOMDocument();
319 @$doc->loadXML($xml);
321 $xpath = new DOMXPath($doc);
322 $xpath->registerNamespace('atom', NAMESPACE_ATOM1);
323 $xpath->registerNamespace('thr', NAMESPACE_THREAD);
324 $xpath->registerNamespace('georss', NAMESPACE_GEORSS);
325 $xpath->registerNamespace('activity', NAMESPACE_ACTIVITY);
326 $xpath->registerNamespace('media', NAMESPACE_MEDIA);
327 $xpath->registerNamespace('poco', NAMESPACE_POCO);
328 $xpath->registerNamespace('ostatus', NAMESPACE_OSTATUS);
329 $xpath->registerNamespace('statusnet', NAMESPACE_STATUSNET);
332 $hub_items = $xpath->query("/atom:feed/atom:link[@rel='hub']")->item(0);
333 if (is_object($hub_items)) {
334 $hub_attributes = $hub_items->attributes;
335 if (is_object($hub_attributes)) {
336 foreach ($hub_attributes as $hub_attribute) {
337 if ($hub_attribute->name == "href") {
338 $hub = $hub_attribute->textContent;
339 logger("Found hub ".$hub, LOGGER_DEBUG);
346 $header["uid"] = $importer["uid"];
347 $header["network"] = NETWORK_OSTATUS;
349 $header["origin"] = 0;
350 $header["gravity"] = GRAVITY_COMMENT;
352 $first_child = $doc->firstChild->tagName;
354 if ($first_child == "feed") {
355 $entries = $xpath->query('/atom:feed/atom:entry');
357 $entries = $xpath->query('/atom:entry');
360 if ($entries->length == 1) {
361 // We reformat the XML to make it better readable
362 $doc2 = new DOMDocument();
363 $doc2->loadXML($xml);
364 $doc2->preserveWhiteSpace = false;
365 $doc2->formatOutput = true;
366 $xml2 = $doc2->saveXML();
368 $header["protocol"] = PROTOCOL_OSTATUS_SALMON;
369 $header["source"] = $xml2;
370 } elseif (!$initialize) {
374 // Fetch the first author
375 $authordata = $xpath->query('//author')->item(0);
376 $author = self::fetchAuthor($xpath, $authordata, $importer, $contact, $stored);
378 $entry = $xpath->query('/atom:entry');
380 // Reverse the order of the entries
383 foreach ($entries as $entry) {
384 $entrylist[] = $entry;
387 foreach (array_reverse($entrylist) as $entry) {
389 $authorelement = $xpath->query('/atom:entry/atom:author', $entry);
391 if ($authorelement->length == 0) {
392 $authorelement = $xpath->query('atom:author', $entry);
395 if ($authorelement->length > 0) {
396 $author = self::fetchAuthor($xpath, $entry, $importer, $contact, $stored);
399 $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:preferredUsername/text()', $entry);
403 $nickname = $author["author-name"];
406 $item = array_merge($header, $author);
408 $item["uri"] = XML::getFirstNodeValue($xpath, 'atom:id/text()', $entry);
410 $item["verb"] = XML::getFirstNodeValue($xpath, 'activity:verb/text()', $entry);
413 if (in_array($item["verb"], ['qvitter-delete-notice', ACTIVITY_DELETE, 'delete'])) {
414 self::deleteNotice($item);
418 if (in_array($item["verb"], [NAMESPACE_OSTATUS."/unfavorite", ACTIVITY_UNFAVORITE])) {
419 // Ignore "Unfavorite" message
420 logger("Ignore unfavorite message ".print_r($item, true), LOGGER_DEBUG);
424 // Deletions come with the same uri, so we check for duplicates after processing deletions
425 if (Item::exists(['uid' => $importer["uid"], 'uri' => $item["uri"]])) {
426 logger('Post with URI '.$item["uri"].' already existed for user '.$importer["uid"].'.', LOGGER_DEBUG);
429 logger('Processing post with URI '.$item["uri"].' for user '.$importer["uid"].'.', LOGGER_DEBUG);
432 if ($item["verb"] == ACTIVITY_JOIN) {
433 // ignore "Join" messages
434 logger("Ignore join message ".print_r($item, true), LOGGER_DEBUG);
438 if ($item["verb"] == "http://mastodon.social/schema/1.0/block") {
439 // ignore mastodon "block" messages
440 logger("Ignore block message ".print_r($item, true), LOGGER_DEBUG);
444 if ($item["verb"] == ACTIVITY_FOLLOW) {
445 Contact::addRelationship($importer, $contact, $item, $nickname);
449 if ($item["verb"] == NAMESPACE_OSTATUS."/unfollow") {
451 Contact::removeFollower($importer, $contact, $item, $dummy);
455 if ($item["verb"] == ACTIVITY_FAVORITE) {
456 $orig_uri = $xpath->query("activity:object/atom:id", $entry)->item(0)->nodeValue;
457 logger("Favorite ".$orig_uri." ".print_r($item, true));
459 $item["verb"] = ACTIVITY_LIKE;
460 $item["parent-uri"] = $orig_uri;
461 $item["gravity"] = GRAVITY_ACTIVITY;
462 $item["object-type"] = ACTIVITY_OBJ_NOTE;
465 // http://activitystrea.ms/schema/1.0/rsvp-yes
466 if (!in_array($item["verb"], [ACTIVITY_POST, ACTIVITY_LIKE, ACTIVITY_SHARE])) {
467 logger("Unhandled verb ".$item["verb"]." ".print_r($item, true), LOGGER_DEBUG);
470 self::processPost($xpath, $entry, $item, $importer);
472 if ($initialize && (count(self::$itemlist) > 0)) {
473 if (self::$itemlist[0]['uri'] == self::$itemlist[0]['parent-uri']) {
474 // We will import it everytime, when it is started by our contacts
475 $valid = !empty(self::$itemlist[0]['contact-id']);
477 // If not, then it depends on this setting
478 $valid = !Config::get('system', 'ostatus_full_threads');
480 logger("Item with uri ".self::$itemlist[0]['uri']." will be imported due to the system settings.", LOGGER_DEBUG);
483 logger("Item with uri ".self::$itemlist[0]['uri']." belongs to a contact (".self::$itemlist[0]['contact-id']."). It will be imported.", LOGGER_DEBUG);
486 // Never post a thread when the only interaction by our contact was a like
488 $verbs = [ACTIVITY_POST, ACTIVITY_SHARE];
489 foreach (self::$itemlist as $item) {
490 if (!empty($item['contact-id']) && in_array($item['verb'], $verbs)) {
495 logger("Item with uri ".self::$itemlist[0]['uri']." will be imported since the thread contains posts or shares.", LOGGER_DEBUG);
499 // But we will only import complete threads
500 $valid = Item::exists(['uid' => $importer["uid"], 'uri' => self::$itemlist[0]['parent-uri']]);
502 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);
507 $default_contact = 0;
508 $key = count(self::$itemlist);
509 for ($key = count(self::$itemlist) - 1; $key >= 0; $key--) {
510 if (empty(self::$itemlist[$key]['contact-id'])) {
511 self::$itemlist[$key]['contact-id'] = $default_contact;
513 $default_contact = $item['contact-id'];
516 foreach (self::$itemlist as $item) {
517 $found = Item::exists(['uid' => $importer["uid"], 'uri' => $item["uri"]]);
519 logger("Item with uri ".$item["uri"]." for user ".$importer["uid"]." already exists.", LOGGER_DEBUG);
520 } elseif ($item['contact-id'] < 0) {
521 logger("Item with uri ".$item["uri"]." is from a blocked contact.", LOGGER_DEBUG);
523 // We are having duplicated entries. Hopefully this solves it.
524 if (Lock::acquire('ostatus_process_item_insert')) {
525 $ret = Item::insert($item);
526 Lock::release('ostatus_process_item_insert');
527 logger("Item with uri ".$item["uri"]." for user ".$importer["uid"].' stored. Return value: '.$ret);
529 $ret = Item::insert($item);
530 logger("We couldn't lock - but tried to store the item anyway. Return value is ".$ret);
535 self::$itemlist = [];
537 logger('Processing done for post with URI '.$item["uri"].' for user '.$importer["uid"].'.', LOGGER_DEBUG);
543 * @param object $item item
546 private static function deleteNotice($item)
548 $condition = ['uid' => $item['uid'], 'author-id' => $item['author-id'], 'uri' => $item['uri']];
549 if (!Item::exists($condition)) {
550 logger('Item from '.$item['author-link'].' with uri '.$item['uri'].' for user '.$item['uid']." wasn't found. We don't delete it.");
554 Item::delete($condition);
556 logger('Deleted item with uri '.$item['uri'].' for user '.$item['uid']);
560 * @brief Processes the XML for a post
562 * @param object $xpath The xpath object
563 * @param object $entry The xml entry that is processed
564 * @param array $item The item array
565 * @param array $importer user record of the importing user
568 private static function processPost($xpath, $entry, &$item, $importer)
570 $item["body"] = HTML::toBBCode(XML::getFirstNodeValue($xpath, 'atom:content/text()', $entry));
571 $item["object-type"] = XML::getFirstNodeValue($xpath, 'activity:object-type/text()', $entry);
572 if (($item["object-type"] == ACTIVITY_OBJ_BOOKMARK) || ($item["object-type"] == ACTIVITY_OBJ_EVENT)) {
573 $item["title"] = XML::getFirstNodeValue($xpath, 'atom:title/text()', $entry);
574 $item["body"] = XML::getFirstNodeValue($xpath, 'atom:summary/text()', $entry);
575 } elseif ($item["object-type"] == ACTIVITY_OBJ_QUESTION) {
576 $item["title"] = XML::getFirstNodeValue($xpath, 'atom:title/text()', $entry);
579 $item["created"] = XML::getFirstNodeValue($xpath, 'atom:published/text()', $entry);
580 $item["edited"] = XML::getFirstNodeValue($xpath, 'atom:updated/text()', $entry);
581 $item['conversation-uri'] = XML::getFirstNodeValue($xpath, 'ostatus:conversation/text()', $entry);
583 $conv = $xpath->query('ostatus:conversation', $entry);
584 if (is_object($conv->item(0))) {
585 foreach ($conv->item(0)->attributes as $attributes) {
586 if ($attributes->name == "ref") {
587 $item['conversation-uri'] = $attributes->textContent;
589 if ($attributes->name == "href") {
590 $item['conversation-href'] = $attributes->textContent;
597 $inreplyto = $xpath->query('thr:in-reply-to', $entry);
598 if (is_object($inreplyto->item(0))) {
599 foreach ($inreplyto->item(0)->attributes as $attributes) {
600 if ($attributes->name == "ref") {
601 $item["parent-uri"] = $attributes->textContent;
603 if ($attributes->name == "href") {
604 $related = $attributes->textContent;
609 $georsspoint = $xpath->query('georss:point', $entry);
610 if (!empty($georsspoint) && ($georsspoint->length > 0)) {
611 $item["coord"] = $georsspoint->item(0)->nodeValue;
614 $categories = $xpath->query('atom:category', $entry);
616 foreach ($categories as $category) {
617 foreach ($category->attributes as $attributes) {
618 if ($attributes->name == "term") {
619 $term = $attributes->textContent;
620 if (!empty($item["tag"])) {
626 $item["tag"] .= "#[url=".System::baseUrl()."/search?tag=".$term."]".$term."[/url]";
635 $links = $xpath->query('atom:link', $entry);
637 $link_data = self::processLinks($links, $item);
638 $self = $link_data['self'];
639 $add_body = $link_data['add_body'];
644 $notice_info = $xpath->query('statusnet:notice_info', $entry);
645 if ($notice_info && ($notice_info->length > 0)) {
646 foreach ($notice_info->item(0)->attributes as $attributes) {
647 if ($attributes->name == "source") {
648 $item["app"] = strip_tags($attributes->textContent);
650 if ($attributes->name == "repeat_of") {
651 $repeat_of = $attributes->textContent;
655 // Is it a repeated post?
656 if (($repeat_of != "") || ($item["verb"] == ACTIVITY_SHARE)) {
657 $link_data = self::processRepeatedItem($xpath, $entry, $item, $importer);
658 if (!empty($link_data['add_body'])) {
659 $add_body .= $link_data['add_body'];
663 $item["body"] .= $add_body;
665 // Only add additional data when there is no picture in the post
666 if (!strstr($item["body"], '[/img]')) {
667 $item["body"] = add_page_info_to_body($item["body"]);
670 // Mastodon Content Warning
671 if (($item["verb"] == ACTIVITY_POST) && $xpath->evaluate('boolean(atom:summary)', $entry)) {
672 $clear_text = XML::getFirstNodeValue($xpath, 'atom:summary/text()', $entry);
673 if (!empty($clear_text)) {
674 $item['content-warning'] = HTML::toBBCode($clear_text);
678 if (($self != '') && empty($item['protocol'])) {
679 self::fetchSelf($self, $item);
682 if (!empty($item["conversation-href"])) {
683 self::fetchConversation($item['conversation-href'], $item['conversation-uri']);
686 if (isset($item["parent-uri"])) {
687 if (!Item::exists(['uid' => $importer["uid"], 'uri' => $item['parent-uri']])) {
688 if ($related != '') {
689 self::fetchRelated($related, $item["parent-uri"], $importer);
692 logger('Reply with URI '.$item["uri"].' already existed for user '.$importer["uid"].'.', LOGGER_DEBUG);
695 $item["parent-uri"] = $item["uri"];
696 $item["gravity"] = GRAVITY_PARENT;
699 if (($item['author-link'] != '') && !empty($item['protocol'])) {
700 $item = Conversation::insert($item);
703 self::$itemlist[] = $item;
707 * @brief Fetch the conversation for posts
709 * @param string $conversation The link to the conversation
710 * @param string $conversation_uri The conversation in "uri" format
713 private static function fetchConversation($conversation, $conversation_uri)
715 // Ensure that we only store a conversation once in a process
716 if (isset(self::$conv_list[$conversation])) {
720 self::$conv_list[$conversation] = true;
722 $conversation_data = Network::curl($conversation, false, $redirects, ['accept_content' => 'application/atom+xml, text/html']);
724 if (!$conversation_data['success']) {
730 if (stristr($conversation_data['header'], 'Content-Type: application/atom+xml')) {
731 $xml = $conversation_data['body'];
735 $doc = new DOMDocument();
736 if (!@$doc->loadHTML($conversation_data['body'])) {
739 $xpath = new DOMXPath($doc);
741 $links = $xpath->query('//link');
744 foreach ($links as $link) {
745 $attribute = self::readAttributes($link);
746 if (($attribute['rel'] == 'alternate') && ($attribute['type'] == 'application/atom+xml')) {
747 $file = $attribute['href'];
751 $conversation_atom = Network::curl($attribute['href']);
753 if ($conversation_atom['success']) {
754 $xml = $conversation_atom['body'];
764 self::storeConversation($xml, $conversation, $conversation_uri);
768 * @brief Store a feed in several conversation entries
770 * @param string $xml The feed
771 * @param string $conversation conversation
772 * @param string $conversation_uri conversation uri
775 private static function storeConversation($xml, $conversation = '', $conversation_uri = '')
777 $doc = new DOMDocument();
778 @$doc->loadXML($xml);
780 $xpath = new DOMXPath($doc);
781 $xpath->registerNamespace('atom', NAMESPACE_ATOM1);
782 $xpath->registerNamespace('thr', NAMESPACE_THREAD);
783 $xpath->registerNamespace('ostatus', NAMESPACE_OSTATUS);
785 $entries = $xpath->query('/atom:feed/atom:entry');
787 // Now store the entries
788 foreach ($entries as $entry) {
789 $doc2 = new DOMDocument();
790 $doc2->preserveWhiteSpace = false;
791 $doc2->formatOutput = true;
795 $conv_data['protocol'] = PROTOCOL_SPLITTED_CONV;
796 $conv_data['network'] = NETWORK_OSTATUS;
797 $conv_data['uri'] = XML::getFirstNodeValue($xpath, 'atom:id/text()', $entry);
799 $inreplyto = $xpath->query('thr:in-reply-to', $entry);
800 if (is_object($inreplyto->item(0))) {
801 foreach ($inreplyto->item(0)->attributes as $attributes) {
802 if ($attributes->name == "ref") {
803 $conv_data['reply-to-uri'] = $attributes->textContent;
808 $conv_data['conversation-uri'] = XML::getFirstNodeValue($xpath, 'ostatus:conversation/text()', $entry);
810 $conv = $xpath->query('ostatus:conversation', $entry);
811 if (is_object($conv->item(0))) {
812 foreach ($conv->item(0)->attributes as $attributes) {
813 if ($attributes->name == "ref") {
814 $conv_data['conversation-uri'] = $attributes->textContent;
816 if ($attributes->name == "href") {
817 $conv_data['conversation-href'] = $attributes->textContent;
822 if ($conversation != '') {
823 $conv_data['conversation-uri'] = $conversation;
826 if ($conversation_uri != '') {
827 $conv_data['conversation-uri'] = $conversation_uri;
830 $entry = $doc2->importNode($entry, true);
832 $doc2->appendChild($entry);
834 $conv_data['source'] = $doc2->saveXML();
836 $condition = ['item-uri' => $conv_data['uri'],'protocol' => PROTOCOL_OSTATUS_FEED];
837 if (DBA::exists('conversation', $condition)) {
838 logger('Delete deprecated entry for URI '.$conv_data['uri'], LOGGER_DEBUG);
839 DBA::delete('conversation', ['item-uri' => $conv_data['uri']]);
842 logger('Store conversation data for uri '.$conv_data['uri'], LOGGER_DEBUG);
843 Conversation::insert($conv_data);
848 * @brief Fetch the own post so that it can be stored later
850 * We want to store the original data for later processing.
851 * This function is meant for cases where we process a feed with multiple entries.
852 * In that case we need to fetch the single posts here.
854 * @param string $self The link to the self item
855 * @param array $item The item array
858 private static function fetchSelf($self, &$item)
860 $condition = ['`item-uri` = ? AND `protocol` IN (?, ?)', $self, PROTOCOL_DFRN, PROTOCOL_OSTATUS_SALMON];
861 if (DBA::exists('conversation', $condition)) {
862 logger('Conversation '.$item['uri'].' is already stored.', LOGGER_DEBUG);
866 $self_data = Network::curl($self);
868 if (!$self_data['success']) {
872 // We reformat the XML to make it better readable
873 $doc = new DOMDocument();
874 $doc->loadXML($self_data['body']);
875 $doc->preserveWhiteSpace = false;
876 $doc->formatOutput = true;
877 $xml = $doc->saveXML();
879 $item["protocol"] = PROTOCOL_OSTATUS_SALMON;
880 $item["source"] = $xml;
882 logger('Conversation '.$item['uri'].' is now fetched.', LOGGER_DEBUG);
886 * @brief Fetch related posts and processes them
888 * @param string $related The link to the related item
889 * @param string $related_uri The related item in "uri" format
890 * @param array $importer user record of the importing user
893 private static function fetchRelated($related, $related_uri, $importer)
895 $condition = ['`item-uri` = ? AND `protocol` IN (?, ?)', $related_uri, PROTOCOL_DFRN, PROTOCOL_OSTATUS_SALMON];
896 $conversation = DBA::selectFirst('conversation', ['source', 'protocol'], $condition);
897 if (DBM::is_result($conversation)) {
899 $xml = $conversation['source'];
900 if (self::process($xml, $importer, $contact, $hub, $stored, false)) {
901 logger('Got valid cached XML for URI '.$related_uri, LOGGER_DEBUG);
904 if ($conversation['protocol'] == PROTOCOL_OSTATUS_SALMON) {
905 logger('Delete invalid cached XML for URI '.$related_uri, LOGGER_DEBUG);
906 DBA::delete('conversation', ['item-uri' => $related_uri]);
911 $related_data = Network::curl($related, false, $redirects, ['accept_content' => 'application/atom+xml, text/html']);
913 if (!$related_data['success']) {
919 if (stristr($related_data['header'], 'Content-Type: application/atom+xml')) {
920 logger('Directly fetched XML for URI '.$related_uri, LOGGER_DEBUG);
921 $xml = $related_data['body'];
925 $doc = new DOMDocument();
926 if (!@$doc->loadHTML($related_data['body'])) {
929 $xpath = new DOMXPath($doc);
933 $links = $xpath->query('//link');
935 foreach ($links as $link) {
936 $attribute = self::readAttributes($link);
937 if (($attribute['rel'] == 'alternate') && ($attribute['type'] == 'application/atom+xml')) {
938 $atom_file = $attribute['href'];
941 if ($atom_file != '') {
942 $related_atom = Network::curl($atom_file);
944 if ($related_atom['success']) {
945 logger('Fetched XML for URI '.$related_uri, LOGGER_DEBUG);
946 $xml = $related_atom['body'];
952 // Workaround for older GNU Social servers
953 if (($xml == '') && strstr($related, '/notice/')) {
954 $related_atom = Network::curl(str_replace('/notice/', '/api/statuses/show/', $related).'.atom');
956 if ($related_atom['success']) {
957 logger('GNU Social workaround to fetch XML for URI '.$related_uri, LOGGER_DEBUG);
958 $xml = $related_atom['body'];
962 // Even more worse workaround for GNU Social ;-)
964 $related_guess = OStatus::convertHref($related_uri);
965 $related_atom = Network::curl(str_replace('/notice/', '/api/statuses/show/', $related_guess).'.atom');
967 if ($related_atom['success']) {
968 logger('GNU Social workaround 2 to fetch XML for URI '.$related_uri, LOGGER_DEBUG);
969 $xml = $related_atom['body'];
973 // Finally we take the data that we fetched from "ostatus:conversation"
975 $condition = ['item-uri' => $related_uri, 'protocol' => PROTOCOL_SPLITTED_CONV];
976 $conversation = DBA::selectFirst('conversation', ['source'], $condition);
977 if (DBM::is_result($conversation)) {
979 logger('Got cached XML from conversation for URI '.$related_uri, LOGGER_DEBUG);
980 $xml = $conversation['source'];
985 self::process($xml, $importer, $contact, $hub, $stored, false);
987 logger("XML couldn't be fetched for URI: ".$related_uri." - href: ".$related, LOGGER_DEBUG);
993 * @brief Processes the XML for a repeated post
995 * @param object $xpath The xpath object
996 * @param object $entry The xml entry that is processed
997 * @param array $item The item array
998 * @param array $importer user record of the importing user
1000 * @return array with data from links
1002 private static function processRepeatedItem($xpath, $entry, &$item, $importer)
1004 $activityobjects = $xpath->query('activity:object', $entry)->item(0);
1006 if (!is_object($activityobjects)) {
1012 $orig_uri = XML::getFirstNodeValue($xpath, 'atom:id/text()', $activityobjects);
1014 $links = $xpath->query("atom:link", $activityobjects);
1016 $link_data = self::processLinks($links, $item);
1019 $orig_body = XML::getFirstNodeValue($xpath, 'atom:content/text()', $activityobjects);
1020 $orig_created = XML::getFirstNodeValue($xpath, 'atom:published/text()', $activityobjects);
1021 $orig_edited = XML::getFirstNodeValue($xpath, 'atom:updated/text()', $activityobjects);
1023 $orig_author = self::fetchAuthor($xpath, $activityobjects, $importer, $dummy, false);
1025 $item["author-name"] = $orig_author["author-name"];
1026 $item["author-link"] = $orig_author["author-link"];
1027 $item["author-id"] = $orig_author["author-id"];
1029 $item["body"] = HTML::toBBCode($orig_body);
1030 $item["created"] = $orig_created;
1031 $item["edited"] = $orig_edited;
1033 $item["uri"] = $orig_uri;
1035 $item["verb"] = XML::getFirstNodeValue($xpath, 'activity:verb/text()', $activityobjects);
1037 $item["object-type"] = XML::getFirstNodeValue($xpath, 'activity:object-type/text()', $activityobjects);
1039 $inreplyto = $xpath->query('thr:in-reply-to', $activityobjects);
1040 if (is_object($inreplyto->item(0))) {
1041 foreach ($inreplyto->item(0)->attributes as $attributes) {
1042 if ($attributes->name == "ref") {
1043 $item["parent-uri"] = $attributes->textContent;
1052 * @brief Processes links in the XML
1054 * @param object $links The xml data that contain links
1055 * @param array $item The item array
1057 * @return array with data from the links
1059 private static function processLinks($links, &$item)
1061 $link_data = ['add_body' => '', 'self' => ''];
1063 foreach ($links as $link) {
1064 $attribute = self::readAttributes($link);
1066 if (!empty($attribute['rel']) && !empty($attribute['href'])) {
1067 switch ($attribute['rel']) {
1069 $item["plink"] = $attribute['href'];
1070 if (($item["object-type"] == ACTIVITY_OBJ_QUESTION)
1071 || ($item["object-type"] == ACTIVITY_OBJ_EVENT)
1073 $item["body"] .= add_page_info($attribute['href']);
1076 case "ostatus:conversation":
1077 $link_data['conversation'] = $attribute['href'];
1078 $item['conversation-href'] = $link_data['conversation'];
1079 if (!isset($item['conversation-uri'])) {
1080 $item['conversation-uri'] = $item['conversation-href'];
1084 $filetype = strtolower(substr($attribute['type'], 0, strpos($attribute['type'], '/')));
1085 if ($filetype == 'image') {
1086 $link_data['add_body'] .= "\n[img]".$attribute['href'].'[/img]';
1088 if (!empty($item["attach"])) {
1089 $item["attach"] .= ',';
1091 $item["attach"] = '';
1093 if (!isset($attribute['length'])) {
1094 $attribute['length'] = "0";
1096 $item["attach"] .= '[attach]href="'.$attribute['href'].'" length="'.$attribute['length'].'" type="'.$attribute['type'].'" title="'.defaults($attribute, 'title', '').'"[/attach]';
1100 if ($item["object-type"] != ACTIVITY_OBJ_BOOKMARK) {
1101 if (!isset($item["parent-uri"])) {
1102 $item["parent-uri"] = $attribute['href'];
1104 $link_data['related'] = $attribute['href'];
1106 $item["body"] .= add_page_info($attribute['href']);
1110 if (empty($item["plink"])) {
1111 $item["plink"] = $attribute['href'];
1113 $link_data['self'] = $attribute['href'];
1122 * @brief Create an url out of an uri
1124 * @param string $href URI in the format "parameter1:parameter1:..."
1126 * @return string URL in the format http(s)://....
1128 public static function convertHref($href)
1130 $elements = explode(":", $href);
1132 if ((count($elements) <= 2) || ($elements[0] != "tag")) {
1136 $server = explode(",", $elements[1]);
1137 $conversation = explode("=", $elements[2]);
1139 if ((count($elements) == 4) && ($elements[2] == "post")) {
1140 return "http://".$server[0]."/notice/".$elements[3];
1143 if ((count($conversation) != 2) || ($conversation[1] =="")) {
1146 if ($elements[3] == "objectType=thread") {
1147 return "http://".$server[0]."/conversation/".$conversation[1];
1149 return "http://".$server[0]."/notice/".$conversation[1];
1155 * @brief Checks if the current post is a reshare
1157 * @param array $item The item array of thw post
1159 * @return string The guid if the post is a reshare
1161 private static function getResharedGuid($item)
1163 $body = trim($item["body"]);
1165 // Skip if it isn't a pure repeated messages
1166 // Does it start with a share?
1167 if (strpos($body, "[share") > 0) {
1171 // Does it end with a share?
1172 if (strlen($body) > (strrpos($body, "[/share]") + 8)) {
1176 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "$1", $body);
1177 // Skip if there is no shared message in there
1178 if ($body == $attributes) {
1183 preg_match("/guid='(.*?)'/ism", $attributes, $matches);
1184 if (!empty($matches[1])) {
1185 $guid = $matches[1];
1188 preg_match('/guid="(.*?)"/ism', $attributes, $matches);
1189 if (!empty($matches[1])) {
1190 $guid = $matches[1];
1197 * @brief Cleans the body of a post if it contains picture links
1199 * @param string $body The body
1201 * @return string The cleaned body
1203 private static function formatPicturePost($body)
1205 $siteinfo = BBCode::getAttachedData($body);
1207 if (($siteinfo["type"] == "photo")) {
1208 if (isset($siteinfo["preview"])) {
1209 $preview = $siteinfo["preview"];
1211 $preview = $siteinfo["image"];
1214 // Is it a remote picture? Then make a smaller preview here
1215 $preview = proxy_url($preview, false, PROXY_SIZE_SMALL);
1217 // Is it a local picture? Then make it smaller here
1218 $preview = str_replace(["-0.jpg", "-0.png"], ["-2.jpg", "-2.png"], $preview);
1219 $preview = str_replace(["-1.jpg", "-1.png"], ["-2.jpg", "-2.png"], $preview);
1221 if (isset($siteinfo["url"])) {
1222 $url = $siteinfo["url"];
1224 $url = $siteinfo["image"];
1227 $body = trim($siteinfo["text"])." [url]".$url."[/url]\n[img]".$preview."[/img]";
1234 * @brief Adds the header elements to the XML document
1236 * @param object $doc XML document
1237 * @param array $owner Contact data of the poster
1238 * @param string $filter The related feed filter (activity, posts or comments)
1240 * @return object header root element
1242 private static function addHeader($doc, $owner, $filter)
1246 $root = $doc->createElementNS(NAMESPACE_ATOM1, 'feed');
1247 $doc->appendChild($root);
1249 $root->setAttribute("xmlns:thr", NAMESPACE_THREAD);
1250 $root->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
1251 $root->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
1252 $root->setAttribute("xmlns:media", NAMESPACE_MEDIA);
1253 $root->setAttribute("xmlns:poco", NAMESPACE_POCO);
1254 $root->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
1255 $root->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
1256 $root->setAttribute("xmlns:mastodon", NAMESPACE_MASTODON);
1260 case 'activity': $title = L10n::t('%s\'s timeline', $owner['name']); break;
1261 case 'posts' : $title = L10n::t('%s\'s posts' , $owner['name']); break;
1262 case 'comments': $title = L10n::t('%s\'s comments', $owner['name']); break;
1265 $attributes = ["uri" => "https://friendi.ca", "version" => FRIENDICA_VERSION . "-" . DB_UPDATE_VERSION];
1266 XML::addElement($doc, $root, "generator", FRIENDICA_PLATFORM, $attributes);
1267 XML::addElement($doc, $root, "id", System::baseUrl() . "/profile/" . $owner["nick"]);
1268 XML::addElement($doc, $root, "title", $title);
1269 XML::addElement($doc, $root, "subtitle", sprintf("Updates from %s on %s", $owner["name"], Config::get('config', 'sitename')));
1270 XML::addElement($doc, $root, "logo", $owner["photo"]);
1271 XML::addElement($doc, $root, "updated", DateTimeFormat::utcNow(DateTimeFormat::ATOM));
1273 $author = self::addAuthor($doc, $owner);
1274 $root->appendChild($author);
1276 $attributes = ["href" => $owner["url"], "rel" => "alternate", "type" => "text/html"];
1277 XML::addElement($doc, $root, "link", "", $attributes);
1279 /// @TODO We have to find out what this is
1280 /// $attributes = array("href" => System::baseUrl()."/sup",
1281 /// "rel" => "http://api.friendfeed.com/2008/03#sup",
1282 /// "type" => "application/json");
1283 /// XML::addElement($doc, $root, "link", "", $attributes);
1285 self::hublinks($doc, $root, $owner["nick"]);
1287 $attributes = ["href" => System::baseUrl() . "/salmon/" . $owner["nick"], "rel" => "salmon"];
1288 XML::addElement($doc, $root, "link", "", $attributes);
1290 $attributes = ["href" => System::baseUrl() . "/salmon/" . $owner["nick"], "rel" => "http://salmon-protocol.org/ns/salmon-replies"];
1291 XML::addElement($doc, $root, "link", "", $attributes);
1293 $attributes = ["href" => System::baseUrl() . "/salmon/" . $owner["nick"], "rel" => "http://salmon-protocol.org/ns/salmon-mention"];
1294 XML::addElement($doc, $root, "link", "", $attributes);
1296 $attributes = ["href" => System::baseUrl() . "/api/statuses/user_timeline/" . $owner["nick"] . ".atom",
1297 "rel" => "self", "type" => "application/atom+xml"];
1298 XML::addElement($doc, $root, "link", "", $attributes);
1300 if ($owner['account-type'] == ACCOUNT_TYPE_COMMUNITY) {
1301 $condition = ['uid' => $owner['uid'], 'self' => false, 'pending' => false,
1302 'archive' => false, 'hidden' => false, 'blocked' => false];
1303 $members = DBA::count('contact', $condition);
1304 XML::addElement($doc, $root, "statusnet:group_info", "", ["member_count" => $members]);
1311 * @brief Add the link to the push hubs to the XML document
1313 * @param object $doc XML document
1314 * @param object $root XML root element where the hub links are added
1315 * @param object $nick nick
1318 public static function hublinks($doc, $root, $nick)
1320 $h = System::baseUrl() . '/pubsubhubbub/'.$nick;
1321 XML::addElement($doc, $root, "link", "", ["href" => $h, "rel" => "hub"]);
1325 * @brief Adds attachment data to the XML document
1327 * @param object $doc XML document
1328 * @param object $root XML root element where the hub links are added
1329 * @param array $item Data of the item that is to be posted
1332 private static function getAttachment($doc, $root, $item)
1335 $siteinfo = BBCode::getAttachedData($item["body"]);
1337 switch ($siteinfo["type"]) {
1339 $imgdata = Image::getInfoFromURL($siteinfo["image"]);
1341 $attributes = ["rel" => "enclosure",
1342 "href" => $siteinfo["image"],
1343 "type" => $imgdata["mime"],
1344 "length" => intval($imgdata["size"])];
1345 XML::addElement($doc, $root, "link", "", $attributes);
1349 $attributes = ["rel" => "enclosure",
1350 "href" => $siteinfo["url"],
1351 "type" => "text/html; charset=UTF-8",
1353 "title" => $siteinfo["title"]];
1354 XML::addElement($doc, $root, "link", "", $attributes);
1360 if (!Config::get('system', 'ostatus_not_attach_preview') && ($siteinfo["type"] != "photo") && isset($siteinfo["image"])) {
1361 $imgdata = Image::getInfoFromURL($siteinfo["image"]);
1363 $attributes = ["rel" => "enclosure",
1364 "href" => $siteinfo["image"],
1365 "type" => $imgdata["mime"],
1366 "length" => intval($imgdata["size"])];
1368 XML::addElement($doc, $root, "link", "", $attributes);
1372 $arr = explode('[/attach],', $item['attach']);
1374 foreach ($arr as $r) {
1376 $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"|', $r, $matches);
1378 $attributes = ["rel" => "enclosure",
1379 "href" => $matches[1],
1380 "type" => $matches[3]];
1382 if (intval($matches[2])) {
1383 $attributes["length"] = intval($matches[2]);
1385 if (trim($matches[4]) != "") {
1386 $attributes["title"] = trim($matches[4]);
1388 XML::addElement($doc, $root, "link", "", $attributes);
1395 * @brief Adds the author element to the XML document
1397 * @param object $doc XML document
1398 * @param array $owner Contact data of the poster
1400 * @return object author element
1402 private static function addAuthor($doc, $owner, $show_profile = true)
1404 $profile = DBA::selectFirst('profile', ['homepage', 'publish'], ['uid' => $owner['uid'], 'is-default' => true]);
1405 $author = $doc->createElement("author");
1406 XML::addElement($doc, $author, "id", $owner["url"]);
1407 if ($owner['account-type'] == ACCOUNT_TYPE_COMMUNITY) {
1408 XML::addElement($doc, $author, "activity:object-type", ACTIVITY_OBJ_GROUP);
1410 XML::addElement($doc, $author, "activity:object-type", ACTIVITY_OBJ_PERSON);
1412 XML::addElement($doc, $author, "uri", $owner["url"]);
1413 XML::addElement($doc, $author, "name", $owner["nick"]);
1414 XML::addElement($doc, $author, "email", $owner["addr"]);
1415 if ($show_profile) {
1416 XML::addElement($doc, $author, "summary", BBCode::convert($owner["about"], false, 7));
1419 $attributes = ["rel" => "alternate", "type" => "text/html", "href" => $owner["url"]];
1420 XML::addElement($doc, $author, "link", "", $attributes);
1424 "type" => "image/jpeg", // To-Do?
1425 "media:width" => 175,
1426 "media:height" => 175,
1427 "href" => $owner["photo"]];
1428 XML::addElement($doc, $author, "link", "", $attributes);
1430 if (isset($owner["thumb"])) {
1433 "type" => "image/jpeg", // To-Do?
1434 "media:width" => 80,
1435 "media:height" => 80,
1436 "href" => $owner["thumb"]];
1437 XML::addElement($doc, $author, "link", "", $attributes);
1440 XML::addElement($doc, $author, "poco:preferredUsername", $owner["nick"]);
1441 XML::addElement($doc, $author, "poco:displayName", $owner["name"]);
1442 if ($show_profile) {
1443 XML::addElement($doc, $author, "poco:note", BBCode::convert($owner["about"], false, 7));
1445 if (trim($owner["location"]) != "") {
1446 $element = $doc->createElement("poco:address");
1447 XML::addElement($doc, $element, "poco:formatted", $owner["location"]);
1448 $author->appendChild($element);
1452 if (DBM::is_result($profile) && !$show_profile) {
1453 if (trim($profile["homepage"]) != "") {
1454 $urls = $doc->createElement("poco:urls");
1455 XML::addElement($doc, $urls, "poco:type", "homepage");
1456 XML::addElement($doc, $urls, "poco:value", $profile["homepage"]);
1457 XML::addElement($doc, $urls, "poco:primary", "true");
1458 $author->appendChild($urls);
1461 XML::addElement($doc, $author, "followers", "", ["url" => System::baseUrl()."/viewcontacts/".$owner["nick"]]);
1462 XML::addElement($doc, $author, "statusnet:profile_info", "", ["local_id" => $owner["uid"]]);
1464 if ($profile["publish"]) {
1465 XML::addElement($doc, $author, "mastodon:scope", "public");
1473 * @TODO Picture attachments should look like this:
1474 * <a href="https://status.pirati.ca/attachment/572819" title="https://status.pirati.ca/file/heluecht-20151202T222602-rd3u49p.gif"
1475 * class="attachment thumbnail" id="attachment-572819" rel="nofollow external">https://status.pirati.ca/attachment/572819</a>
1479 * @brief Returns the given activity if present - otherwise returns the "post" activity
1481 * @param array $item Data of the item that is to be posted
1483 * @return string activity
1485 private static function constructVerb($item)
1487 if ($item['verb']) {
1488 return $item['verb'];
1491 return ACTIVITY_POST;
1495 * @brief Returns the given object type if present - otherwise returns the "note" object type
1497 * @param array $item Data of the item that is to be posted
1499 * @return string Object type
1501 private static function constructObjecttype($item)
1503 if (in_array($item['object-type'], [ACTIVITY_OBJ_NOTE, ACTIVITY_OBJ_COMMENT]))
1504 return $item['object-type'];
1505 return ACTIVITY_OBJ_NOTE;
1509 * @brief Adds an entry element to the XML document
1511 * @param object $doc XML document
1512 * @param array $item Data of the item that is to be posted
1513 * @param array $owner Contact data of the poster
1514 * @param bool $toplevel optional default false
1516 * @return object Entry element
1518 private static function entry($doc, $item, $owner, $toplevel = false)
1522 $repeated_guid = self::getResharedGuid($item);
1523 if ($repeated_guid != "") {
1524 $xml = self::reshareEntry($doc, $item, $owner, $repeated_guid, $toplevel);
1531 if ($item["verb"] == ACTIVITY_LIKE) {
1532 return self::likeEntry($doc, $item, $owner, $toplevel);
1533 } elseif (in_array($item["verb"], [ACTIVITY_FOLLOW, NAMESPACE_OSTATUS."/unfollow"])) {
1534 return self::followEntry($doc, $item, $owner, $toplevel);
1536 return self::noteEntry($doc, $item, $owner, $toplevel);
1541 * @brief Adds a source entry to the XML document
1543 * @param object $doc XML document
1544 * @param array $contact Array of the contact that is added
1546 * @return object Source element
1548 private static function sourceEntry($doc, $contact)
1550 $source = $doc->createElement("source");
1551 XML::addElement($doc, $source, "id", $contact["poll"]);
1552 XML::addElement($doc, $source, "title", $contact["name"]);
1553 XML::addElement($doc, $source, "link", "", ["rel" => "alternate", "type" => "text/html", "href" => $contact["alias"]]);
1554 XML::addElement($doc, $source, "link", "", ["rel" => "self", "type" => "application/atom+xml", "href" => $contact["poll"]]);
1555 XML::addElement($doc, $source, "icon", $contact["photo"]);
1556 XML::addElement($doc, $source, "updated", DateTimeFormat::utc($contact["success_update"]."+00:00", DateTimeFormat::ATOM));
1562 * @brief Fetches contact data from the contact or the gcontact table
1564 * @param string $url URL of the contact
1565 * @param array $owner Contact data of the poster
1567 * @return array Contact array
1569 private static function contactEntry($url, $owner)
1572 "SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` IN (0, %d) ORDER BY `uid` DESC LIMIT 1",
1573 dbesc(normalise_link($url)),
1574 intval($owner["uid"])
1576 if (DBM::is_result($r)) {
1578 $contact["uid"] = -1;
1581 if (!DBM::is_result($r)) {
1583 "SELECT * FROM `gcontact` WHERE `nurl` = '%s' LIMIT 1",
1584 dbesc(normalise_link($url))
1586 if (DBM::is_result($r)) {
1588 $contact["uid"] = -1;
1589 $contact["success_update"] = $contact["updated"];
1593 if (!DBM::is_result($r)) {
1597 if (!isset($contact["poll"])) {
1598 $data = Probe::uri($url);
1599 $contact["poll"] = $data["poll"];
1601 if (!$contact["alias"]) {
1602 $contact["alias"] = $data["alias"];
1606 if (!isset($contact["alias"])) {
1607 $contact["alias"] = $contact["url"];
1614 * @brief Adds an entry element with reshared content
1616 * @param object $doc XML document
1617 * @param array $item Data of the item that is to be posted
1618 * @param array $owner Contact data of the poster
1619 * @param string $repeated_guid guid
1620 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1622 * @return object Entry element
1624 private static function reshareEntry($doc, $item, $owner, $repeated_guid, $toplevel)
1626 if (($item["id"] != $item["parent"]) && (normalise_link($item["author-link"]) != normalise_link($owner["url"]))) {
1627 logger("OStatus entry is from author ".$owner["url"]." - not from ".$item["author-link"].". Quitting.", LOGGER_DEBUG);
1630 $title = self::entryHeader($doc, $entry, $owner, $item, $toplevel);
1632 $condition = ['uid' => $owner["uid"], 'guid' => $repeated_guid, 'private' => false,
1633 'network' => [NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS]];
1634 $repeated_item = Item::selectFirst([], $condition);
1635 if (!DBM::is_result($repeated_item)) {
1639 $contact = self::contactEntry($repeated_item['author-link'], $owner);
1640 $contact['account-type'] = $contact['contact-type'];
1642 $title = $owner["nick"]." repeated a notice by ".$contact["nick"];
1644 self::entryContent($doc, $entry, $item, $owner, $title, ACTIVITY_SHARE, false);
1646 $as_object = $doc->createElement("activity:object");
1648 XML::addElement($doc, $as_object, "activity:object-type", NAMESPACE_ACTIVITY_SCHEMA."activity");
1650 self::entryContent($doc, $as_object, $repeated_item, $owner, "", "", false);
1652 $author = self::addAuthor($doc, $contact, false);
1653 $as_object->appendChild($author);
1655 $as_object2 = $doc->createElement("activity:object");
1657 XML::addElement($doc, $as_object2, "activity:object-type", self::constructObjecttype($repeated_item));
1659 $title = sprintf("New comment by %s", $contact["nick"]);
1661 self::entryContent($doc, $as_object2, $repeated_item, $owner, $title);
1663 $as_object->appendChild($as_object2);
1665 self::entryFooter($doc, $as_object, $item, $owner, false);
1667 $source = self::sourceEntry($doc, $contact);
1669 $as_object->appendChild($source);
1671 $entry->appendChild($as_object);
1673 self::entryFooter($doc, $entry, $item, $owner);
1679 * @brief Adds an entry element with a "like"
1681 * @param object $doc XML document
1682 * @param array $item Data of the item that is to be posted
1683 * @param array $owner Contact data of the poster
1684 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1686 * @return object Entry element with "like"
1688 private static function likeEntry($doc, $item, $owner, $toplevel)
1690 if (($item["id"] != $item["parent"]) && (normalise_link($item["author-link"]) != normalise_link($owner["url"]))) {
1691 logger("OStatus entry is from author ".$owner["url"]." - not from ".$item["author-link"].". Quitting.", LOGGER_DEBUG);
1694 $title = self::entryHeader($doc, $entry, $owner, $item, $toplevel);
1696 $verb = NAMESPACE_ACTIVITY_SCHEMA."favorite";
1697 self::entryContent($doc, $entry, $item, $owner, "Favorite", $verb, false);
1699 $as_object = $doc->createElement("activity:object");
1701 $parent = Item::selectFirst([], ['uri' => $item["thr-parent"], 'uid' => $item["uid"]]);
1703 XML::addElement($doc, $as_object, "activity:object-type", self::constructObjecttype($parent));
1705 self::entryContent($doc, $as_object, $parent, $owner, "New entry");
1707 $entry->appendChild($as_object);
1709 self::entryFooter($doc, $entry, $item, $owner);
1715 * @brief Adds the person object element to the XML document
1717 * @param object $doc XML document
1718 * @param array $owner Contact data of the poster
1719 * @param array $contact Contact data of the target
1721 * @return object author element
1723 private static function addPersonObject($doc, $owner, $contact)
1725 $object = $doc->createElement("activity:object");
1726 XML::addElement($doc, $object, "activity:object-type", ACTIVITY_OBJ_PERSON);
1728 if ($contact['network'] == NETWORK_PHANTOM) {
1729 XML::addElement($doc, $object, "id", $contact['url']);
1733 XML::addElement($doc, $object, "id", $contact["alias"]);
1734 XML::addElement($doc, $object, "title", $contact["nick"]);
1736 $attributes = ["rel" => "alternate", "type" => "text/html", "href" => $contact["url"]];
1737 XML::addElement($doc, $object, "link", "", $attributes);
1741 "type" => "image/jpeg", // To-Do?
1742 "media:width" => 175,
1743 "media:height" => 175,
1744 "href" => $contact["photo"]];
1745 XML::addElement($doc, $object, "link", "", $attributes);
1747 XML::addElement($doc, $object, "poco:preferredUsername", $contact["nick"]);
1748 XML::addElement($doc, $object, "poco:displayName", $contact["name"]);
1750 if (trim($contact["location"]) != "") {
1751 $element = $doc->createElement("poco:address");
1752 XML::addElement($doc, $element, "poco:formatted", $contact["location"]);
1753 $object->appendChild($element);
1760 * @brief Adds a follow/unfollow entry element
1762 * @param object $doc XML document
1763 * @param array $item Data of the follow/unfollow message
1764 * @param array $owner Contact data of the poster
1765 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1767 * @return object Entry element
1769 private static function followEntry($doc, $item, $owner, $toplevel)
1771 $item["id"] = $item["parent"] = 0;
1772 $item["created"] = $item["edited"] = date("c");
1773 $item["private"] = true;
1775 $contact = Probe::uri($item['follow']);
1777 if ($contact['alias'] == '') {
1778 $contact['alias'] = $contact["url"];
1780 $item['follow'] = $contact['alias'];
1784 "SELECT `id` FROM `contact` WHERE `uid` = %d AND `nurl` = '%s'",
1785 intval($owner['uid']),
1786 dbesc(normalise_link($contact["url"]))
1789 if (DBM::is_result($r)) {
1790 $connect_id = $r[0]['id'];
1795 if ($item['verb'] == ACTIVITY_FOLLOW) {
1796 $message = L10n::t('%s is now following %s.');
1797 $title = L10n::t('following');
1798 $action = "subscription";
1800 $message = L10n::t('%s stopped following %s.');
1801 $title = L10n::t('stopped following');
1802 $action = "unfollow";
1805 $item["uri"] = $item['parent-uri'] = $item['thr-parent']
1806 = 'tag:'.get_app()->get_hostname().
1807 ','.date('Y-m-d').':'.$action.':'.$owner['uid'].
1808 ':person:'.$connect_id.':'.$item['created'];
1810 $item["body"] = sprintf($message, $owner["nick"], $contact["nick"]);
1812 self::entryHeader($doc, $entry, $owner, $item, $toplevel);
1814 self::entryContent($doc, $entry, $item, $owner, $title);
1816 $object = self::addPersonObject($doc, $owner, $contact);
1817 $entry->appendChild($object);
1819 self::entryFooter($doc, $entry, $item, $owner);
1825 * @brief Adds a regular entry element
1827 * @param object $doc XML document
1828 * @param array $item Data of the item that is to be posted
1829 * @param array $owner Contact data of the poster
1830 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1832 * @return object Entry element
1834 private static function noteEntry($doc, $item, $owner, $toplevel)
1836 if (($item["id"] != $item["parent"]) && (normalise_link($item["author-link"]) != normalise_link($owner["url"]))) {
1837 logger("OStatus entry is from author ".$owner["url"]." - not from ".$item["author-link"].". Quitting.", LOGGER_DEBUG);
1840 $title = self::entryHeader($doc, $entry, $owner, $item, $toplevel);
1842 XML::addElement($doc, $entry, "activity:object-type", ACTIVITY_OBJ_NOTE);
1844 self::entryContent($doc, $entry, $item, $owner, $title);
1846 self::entryFooter($doc, $entry, $item, $owner);
1852 * @brief Adds a header element to the XML document
1854 * @param object $doc XML document
1855 * @param object $entry The entry element where the elements are added
1856 * @param array $owner Contact data of the poster
1857 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1859 * @return string The title for the element
1861 private static function entryHeader($doc, &$entry, $owner, $item, $toplevel)
1863 /// @todo Check if this title stuff is really needed (I guess not)
1865 $entry = $doc->createElement("entry");
1866 $title = sprintf("New note by %s", $owner["nick"]);
1868 if ($owner['account-type'] == ACCOUNT_TYPE_COMMUNITY) {
1869 $contact = self::contactEntry($item['author-link'], $owner);
1870 $author = self::addAuthor($doc, $contact, false);
1871 $entry->appendChild($author);
1874 $entry = $doc->createElementNS(NAMESPACE_ATOM1, "entry");
1876 $entry->setAttribute("xmlns:thr", NAMESPACE_THREAD);
1877 $entry->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
1878 $entry->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
1879 $entry->setAttribute("xmlns:media", NAMESPACE_MEDIA);
1880 $entry->setAttribute("xmlns:poco", NAMESPACE_POCO);
1881 $entry->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
1882 $entry->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
1883 $entry->setAttribute("xmlns:mastodon", NAMESPACE_MASTODON);
1885 $author = self::addAuthor($doc, $owner);
1886 $entry->appendChild($author);
1888 $title = sprintf("New comment by %s", $owner["nick"]);
1894 * @brief Adds elements to the XML document
1896 * @param object $doc XML document
1897 * @param object $entry Entry element where the content is added
1898 * @param array $item Data of the item that is to be posted
1899 * @param array $owner Contact data of the poster
1900 * @param string $title Title for the post
1901 * @param string $verb The activity verb
1902 * @param bool $complete Add the "status_net" element?
1905 private static function entryContent($doc, $entry, $item, $owner, $title, $verb = "", $complete = true)
1908 $verb = self::constructVerb($item);
1911 XML::addElement($doc, $entry, "id", $item["uri"]);
1912 XML::addElement($doc, $entry, "title", $title);
1914 $body = self::formatPicturePost($item['body']);
1916 if ($item['title'] != "") {
1917 $body = "[b]".$item['title']."[/b]\n\n".$body;
1920 $body = BBCode::convert($body, false, 7);
1922 XML::addElement($doc, $entry, "content", $body, ["type" => "html"]);
1924 XML::addElement($doc, $entry, "link", "", ["rel" => "alternate", "type" => "text/html",
1925 "href" => System::baseUrl()."/display/".$item["guid"]]
1928 if ($complete && ($item["id"] > 0)) {
1929 XML::addElement($doc, $entry, "status_net", "", ["notice_id" => $item["id"]]);
1932 XML::addElement($doc, $entry, "activity:verb", $verb);
1934 XML::addElement($doc, $entry, "published", DateTimeFormat::utc($item["created"]."+00:00", DateTimeFormat::ATOM));
1935 XML::addElement($doc, $entry, "updated", DateTimeFormat::utc($item["edited"]."+00:00", DateTimeFormat::ATOM));
1939 * @brief Adds the elements at the foot of an entry to the XML document
1941 * @param object $doc XML document
1942 * @param object $entry The entry element where the elements are added
1943 * @param array $item Data of the item that is to be posted
1944 * @param array $owner Contact data of the poster
1945 * @param bool $complete default true
1948 private static function entryFooter($doc, $entry, array $item, array $owner, $complete = true)
1952 if (($item['parent'] != $item['id']) || ($item['parent-uri'] !== $item['uri']) || (($item['thr-parent'] !== '') && ($item['thr-parent'] !== $item['uri']))) {
1953 $parent = Item::selectFirst(['guid', 'author-link', 'owner-link'], ['id' => $item["parent"]]);
1954 $parent_item = (($item['thr-parent']) ? $item['thr-parent'] : $item['parent-uri']);
1956 $thrparent = Item::selectFirst(['guid', 'author-link', 'owner-link', 'plink'], ['uid' => $owner["uid"], 'uri' => $parent_item]);
1958 if (DBM::is_result($thrparent)) {
1959 $mentioned[$thrparent["author-link"]] = $thrparent["author-link"];
1960 $mentioned[$thrparent["owner-link"]] = $thrparent["owner-link"];
1961 $parent_plink = $thrparent["plink"];
1963 $mentioned[$parent["author-link"]] = $parent["author-link"];
1964 $mentioned[$parent["owner-link"]] = $parent["owner-link"];
1965 $parent_plink = System::baseUrl()."/display/".$parent["guid"];
1969 "ref" => $parent_item,
1970 "href" => $parent_plink];
1971 XML::addElement($doc, $entry, "thr:in-reply-to", "", $attributes);
1975 "href" => $parent_plink];
1976 XML::addElement($doc, $entry, "link", "", $attributes);
1979 if (intval($item["parent"]) > 0) {
1980 $conversation_href = System::baseUrl()."/display/".$owner["nick"]."/".$item["parent"];
1981 $conversation_uri = $conversation_href;
1983 if (isset($parent_item)) {
1984 $conversation = DBA::selectFirst('conversation', ['conversation-uri', 'conversation-href'], ['item-uri' => $parent_item]);
1985 if (DBM::is_result($conversation)) {
1986 if ($conversation['conversation-uri'] != '') {
1987 $conversation_uri = $conversation['conversation-uri'];
1989 if ($conversation['conversation-href'] != '') {
1990 $conversation_href = $conversation['conversation-href'];
1995 XML::addElement($doc, $entry, "link", "", ["rel" => "ostatus:conversation", "href" => $conversation_href]);
1998 "href" => $conversation_href,
1999 "local_id" => $item["parent"],
2000 "ref" => $conversation_uri];
2002 XML::addElement($doc, $entry, "ostatus:conversation", $conversation_uri, $attributes);
2005 $tags = item::getFeedTags($item);
2008 foreach ($tags as $t) {
2010 $mentioned[$t[1]] = $t[1];
2015 // Make sure that mentions are accepted (GNU Social has problems with mixing HTTP and HTTPS)
2017 foreach ($mentioned as $mention) {
2018 $newmentions[str_replace("http://", "https://", $mention)] = str_replace("http://", "https://", $mention);
2019 $newmentions[str_replace("https://", "http://", $mention)] = str_replace("https://", "http://", $mention);
2021 $mentioned = $newmentions;
2023 foreach ($mentioned as $mention) {
2024 $condition = ['uid' => $owner['uid'], 'nurl' => normalise_link($mention)];
2025 $contact = DBA::selectFirst('contact', ['forum', 'prv', 'self', 'contact-type'], $condition);
2026 if ($contact["forum"] || $contact["prv"] || ($owner['contact-type'] == ACCOUNT_TYPE_COMMUNITY) ||
2027 ($contact['self'] && ($owner['account-type'] == ACCOUNT_TYPE_COMMUNITY))) {
2028 XML::addElement($doc, $entry, "link", "",
2030 "rel" => "mentioned",
2031 "ostatus:object-type" => ACTIVITY_OBJ_GROUP,
2035 XML::addElement($doc, $entry, "link", "",
2037 "rel" => "mentioned",
2038 "ostatus:object-type" => ACTIVITY_OBJ_PERSON,
2044 if ($owner['account-type'] == ACCOUNT_TYPE_COMMUNITY) {
2045 XML::addElement($doc, $entry, "link", "", [
2046 "rel" => "mentioned",
2047 "ostatus:object-type" => "http://activitystrea.ms/schema/1.0/group",
2048 "href" => $owner['url']
2052 if (!$item["private"]) {
2053 XML::addElement($doc, $entry, "link", "", ["rel" => "ostatus:attention",
2054 "href" => "http://activityschema.org/collection/public"]);
2055 XML::addElement($doc, $entry, "link", "", ["rel" => "mentioned",
2056 "ostatus:object-type" => "http://activitystrea.ms/schema/1.0/collection",
2057 "href" => "http://activityschema.org/collection/public"]);
2058 XML::addElement($doc, $entry, "mastodon:scope", "public");
2062 foreach ($tags as $t) {
2064 XML::addElement($doc, $entry, "category", "", ["term" => $t[2]]);
2069 self::getAttachment($doc, $entry, $item);
2071 if ($complete && ($item["id"] > 0)) {
2072 $app = $item["app"];
2077 $attributes = ["local_id" => $item["id"], "source" => $app];
2079 if (isset($parent["id"])) {
2080 $attributes["repeat_of"] = $parent["id"];
2083 if ($item["coord"] != "") {
2084 XML::addElement($doc, $entry, "georss:point", $item["coord"]);
2087 XML::addElement($doc, $entry, "statusnet:notice_info", "", $attributes);
2092 * Creates the XML feed for a given nickname
2094 * Supported filters:
2095 * - activity (default): all the public posts
2096 * - posts: all the public top-level posts
2097 * - comments: all the public replies
2099 * Updates the provided last_update parameter if the result comes from the
2100 * cache or it is empty
2102 * @brief Creates the XML feed for a given nickname
2104 * @param string $owner_nick Nickname of the feed owner
2105 * @param string $last_update Date of the last update
2106 * @param integer $max_items Number of maximum items to fetch
2107 * @param string $filter Feed items filter (activity, posts or comments)
2108 * @param boolean $nocache Wether to bypass caching
2110 * @return string XML feed
2112 public static function feed($owner_nick, &$last_update, $max_items = 300, $filter = 'activity', $nocache = false)
2114 $stamp = microtime(true);
2116 $owner = User::getOwnerDataByNick($owner_nick);
2121 $cachekey = "ostatus:feed:" . $owner_nick . ":" . $filter . ":" . $last_update;
2123 $previous_created = $last_update;
2125 // Don't cache when the last item was posted less then 15 minutes ago (Cache duration)
2126 if ((time() - strtotime($owner['last-item'])) < 15*60) {
2127 $result = Cache::get($cachekey);
2128 if (!$nocache && !is_null($result)) {
2129 logger('Feed duration: ' . number_format(microtime(true) - $stamp, 3) . ' - ' . $owner_nick . ' - ' . $filter . ' - ' . $previous_created . ' (cached)', LOGGER_DEBUG);
2130 $last_update = $result['last_update'];
2131 return $result['feed'];
2135 if (!strlen($last_update)) {
2136 $last_update = 'now -30 days';
2139 $check_date = DateTimeFormat::utc($last_update);
2140 $authorid = Contact::getIdForURL($owner["url"], 0, true);
2142 $condition = ["`uid` = ? AND `created` > ? AND NOT `deleted`
2143 AND NOT `private` AND `visible` AND `wall` AND `parent-network` IN (?, ?)",
2144 $owner["uid"], $check_date, NETWORK_OSTATUS, NETWORK_DFRN];
2146 if ($filter === 'comments') {
2147 $condition[0] .= " AND `object-type` = ? ";
2148 $condition[] = ACTIVITY_OBJ_COMMENT;
2151 if ($owner['account-type'] != ACCOUNT_TYPE_COMMUNITY) {
2152 $condition[0] .= " AND `contact-id` = ? AND `author-id` = ?";
2153 $condition[] = $owner["id"];
2154 $condition[] = $authorid;
2157 $params = ['order' => ['created' => true], 'limit' => $max_items];
2159 if ($filter === 'posts') {
2160 $ret = Item::selectThread([], $condition, $params);
2162 $ret = Item::select([], $condition, $params);
2165 $items = Item::inArray($ret);
2167 $doc = new DOMDocument('1.0', 'utf-8');
2168 $doc->formatOutput = true;
2170 $root = self::addHeader($doc, $owner, $filter);
2172 foreach ($items as $item) {
2173 if (Config::get('system', 'ostatus_debug')) {
2174 $item['body'] .= '🍼';
2176 $entry = self::entry($doc, $item, $owner);
2177 $root->appendChild($entry);
2179 if ($last_update < $item['created']) {
2180 $last_update = $item['created'];
2184 $feeddata = trim($doc->saveXML());
2186 $msg = ['feed' => $feeddata, 'last_update' => $last_update];
2187 Cache::set($cachekey, $msg, CACHE_QUARTER_HOUR);
2189 logger('Feed duration: ' . number_format(microtime(true) - $stamp, 3) . ' - ' . $owner_nick . ' - ' . $filter . ' - ' . $previous_created, LOGGER_DEBUG);
2195 * @brief Creates the XML for a salmon message
2197 * @param array $item Data of the item that is to be posted
2198 * @param array $owner Contact data of the poster
2200 * @return string XML for the salmon
2202 public static function salmon($item, $owner)
2204 $doc = new DOMDocument('1.0', 'utf-8');
2205 $doc->formatOutput = true;
2207 if (Config::get('system', 'ostatus_debug')) {
2208 $item['body'] .= '🐟';
2211 $entry = self::entry($doc, $item, $owner, true);
2213 $doc->appendChild($entry);
2215 return trim($doc->saveXML());