3 * @file src/Protocol/OStatus.php
5 namespace Friendica\Protocol;
10 use Friendica\Content\Text\BBCode;
11 use Friendica\Content\Text\HTML;
12 use Friendica\Core\Cache;
13 use Friendica\Core\Config;
14 use Friendica\Core\L10n;
15 use Friendica\Core\Lock;
16 use Friendica\Core\System;
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"] = $xpath->evaluate('atom:author/atom:uri/text()', $context)->item(0)->nodeValue;
59 $author["author-name"] = $xpath->evaluate('atom:author/atom:name/text()', $context)->item(0)->nodeValue;
60 $addr = $xpath->evaluate('atom:author/atom:email/text()', $context)->item(0)->nodeValue;
62 $aliaslink = $author["author-link"];
64 $alternate = $xpath->query("atom:author/atom:link[@rel='alternate']", $context)->item(0)->attributes;
65 if (is_object($alternate)) {
66 foreach ($alternate as $attributes) {
67 if (($attributes->name == "href") && ($attributes->textContent != "")) {
68 $author["author-link"] = $attributes->textContent;
72 $author["contact-id"] = $contact["id"];
75 if ($aliaslink != '') {
76 $condition = ["`uid` = ? AND `alias` = ? AND `network` != ? AND `rel` IN (?, ?)",
77 $importer["uid"], $aliaslink, NETWORK_STATUSNET,
78 CONTACT_IS_SHARING, CONTACT_IS_FRIEND];
79 $contact = dba::selectFirst('contact', [], $condition);
82 if (!DBM::is_result($contact) && $author["author-link"] != '') {
83 if ($aliaslink == "") {
84 $aliaslink = $author["author-link"];
87 $condition = ["`uid` = ? AND `nurl` IN (?, ?) AND `network` != ? AND `rel` IN (?, ?)",
88 $importer["uid"], normalise_link($author["author-link"]), normalise_link($aliaslink),
89 NETWORK_STATUSNET, CONTACT_IS_SHARING, CONTACT_IS_FRIEND];
90 $contact = dba::selectFirst('contact', [], $condition);
93 if (!DBM::is_result($contact) && ($addr != '')) {
94 $condition = ["`uid` = ? AND `addr` = ? AND `network` != ? AND `rel` IN (?, ?)",
95 $importer["uid"], $addr, NETWORK_STATUSNET,
96 CONTACT_IS_SHARING, CONTACT_IS_FRIEND];
97 $contact = dba::selectFirst('contact', [], $condition);
100 if (DBM::is_result($contact)) {
101 if ($contact['blocked']) {
104 $author["contact-id"] = $contact["id"];
108 $avatars = $xpath->query("atom:author/atom:link[@rel='avatar']", $context);
109 foreach ($avatars as $avatar) {
112 foreach ($avatar->attributes as $attributes) {
113 if ($attributes->name == "href") {
114 $href = $attributes->textContent;
116 if ($attributes->name == "width") {
117 $width = $attributes->textContent;
121 $avatarlist[$width] = $href;
124 if (count($avatarlist) > 0) {
126 $author["author-avatar"] = Probe::fixAvatar(current($avatarlist), $author["author-link"]);
129 $displayname = $xpath->evaluate('atom:author/poco:displayName/text()', $context)->item(0)->nodeValue;
130 if ($displayname != "") {
131 $author["author-name"] = $displayname;
134 $author["owner-name"] = $author["author-name"];
135 $author["owner-link"] = $author["author-link"];
136 $author["owner-avatar"] = $author["author-avatar"];
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 = $xpath->evaluate('atom:author/atom:uri/text()', $context)->item(0)->nodeValue;
160 $contact["alias"] = $value;
163 $value = $xpath->evaluate('atom:author/poco:displayName/text()', $context)->item(0)->nodeValue;
165 $contact["name"] = $value;
168 $value = $xpath->evaluate('atom:author/poco:preferredUsername/text()', $context)->item(0)->nodeValue;
170 $contact["nick"] = $value;
173 $value = $xpath->evaluate('atom:author/poco:note/text()', $context)->item(0)->nodeValue;
175 $contact["about"] = HTML::toBBCode($value);
178 $value = $xpath->evaluate('atom:author/poco:address/poco:formatted/text()', $context)->item(0)->nodeValue;
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 Contact::updateAvatar($author["author-avatar"], 0, $cid);
212 $contact["generation"] = 2;
213 $contact["hide"] = false; // OStatus contacts are never hidden
214 $contact["photo"] = $author["author-avatar"];
215 $gcid = GContact::update($contact);
217 GContact::link($gcid, $contact["uid"], $contact["id"]);
224 * @brief Fetches author data from a given XML string
226 * @param string $xml The XML
227 * @param array $importer user record of the importing user
229 * @return array Array of author related entries for the item
231 public static function salmonAuthor($xml, $importer)
237 $doc = new DOMDocument();
238 @$doc->loadXML($xml);
240 $xpath = new DOMXPath($doc);
241 $xpath->registerNamespace('atom', NAMESPACE_ATOM1);
242 $xpath->registerNamespace('thr', NAMESPACE_THREAD);
243 $xpath->registerNamespace('georss', NAMESPACE_GEORSS);
244 $xpath->registerNamespace('activity', NAMESPACE_ACTIVITY);
245 $xpath->registerNamespace('media', NAMESPACE_MEDIA);
246 $xpath->registerNamespace('poco', NAMESPACE_POCO);
247 $xpath->registerNamespace('ostatus', NAMESPACE_OSTATUS);
248 $xpath->registerNamespace('statusnet', NAMESPACE_STATUSNET);
250 $contact = ["id" => 0];
252 // Fetch the first author
253 $authordata = $xpath->query('//author')->item(0);
254 $author = self::fetchAuthor($xpath, $authordata, $importer, $contact, true);
259 * @brief Read attributes from element
261 * @param object $element Element object
263 * @return array attributes
265 private static function readAttributes($element)
269 foreach ($element->attributes as $attributes) {
270 $attribute[$attributes->name] = $attributes->textContent;
277 * @brief Imports an XML string containing OStatus elements
279 * @param string $xml The XML
280 * @param array $importer user record of the importing user
281 * @param array $contact contact
282 * @param string $hub Called by reference, returns the fetched hub data
285 public static function import($xml, $importer, &$contact, &$hub)
287 self::process($xml, $importer, $contact, $hub);
291 * @brief Internal feed processing
293 * @param string $xml The XML
294 * @param array $importer user record of the importing user
295 * @param array $contact contact
296 * @param string $hub Called by reference, returns the fetched hub data
297 * @param boolean $stored Is the post fresh imported or from the database?
298 * @param boolean $initialize Is it the leading post so that data has to be initialized?
300 * @return boolean Could the XML be processed?
302 private static function process($xml, $importer, &$contact, &$hub, $stored = false, $initialize = true)
305 self::$itemlist = [];
306 self::$conv_list = [];
309 logger("Import OStatus message", LOGGER_DEBUG);
314 $doc = new DOMDocument();
315 @$doc->loadXML($xml);
317 $xpath = new DOMXPath($doc);
318 $xpath->registerNamespace('atom', NAMESPACE_ATOM1);
319 $xpath->registerNamespace('thr', NAMESPACE_THREAD);
320 $xpath->registerNamespace('georss', NAMESPACE_GEORSS);
321 $xpath->registerNamespace('activity', NAMESPACE_ACTIVITY);
322 $xpath->registerNamespace('media', NAMESPACE_MEDIA);
323 $xpath->registerNamespace('poco', NAMESPACE_POCO);
324 $xpath->registerNamespace('ostatus', NAMESPACE_OSTATUS);
325 $xpath->registerNamespace('statusnet', NAMESPACE_STATUSNET);
328 $hub_attributes = $xpath->query("/atom:feed/atom:link[@rel='hub']")->item(0)->attributes;
329 if (is_object($hub_attributes)) {
330 foreach ($hub_attributes as $hub_attribute) {
331 if ($hub_attribute->name == "href") {
332 $hub = $hub_attribute->textContent;
333 logger("Found hub ".$hub, LOGGER_DEBUG);
339 $header["uid"] = $importer["uid"];
340 $header["network"] = NETWORK_OSTATUS;
341 $header["type"] = "remote-comment";
343 $header["origin"] = 0;
344 $header["gravity"] = GRAVITY_COMMENT;
346 $first_child = $doc->firstChild->tagName;
348 if ($first_child == "feed") {
349 $entries = $xpath->query('/atom:feed/atom:entry');
351 $entries = $xpath->query('/atom:entry');
354 if ($entries->length == 1) {
355 // We reformat the XML to make it better readable
356 $doc2 = new DOMDocument();
357 $doc2->loadXML($xml);
358 $doc2->preserveWhiteSpace = false;
359 $doc2->formatOutput = true;
360 $xml2 = $doc2->saveXML();
362 $header["protocol"] = PROTOCOL_OSTATUS_SALMON;
363 $header["source"] = $xml2;
364 } elseif (!$initialize) {
368 // Fetch the first author
369 $authordata = $xpath->query('//author')->item(0);
370 $author = self::fetchAuthor($xpath, $authordata, $importer, $contact, $stored);
372 $entry = $xpath->query('/atom:entry');
374 // Reverse the order of the entries
377 foreach ($entries as $entry) {
378 $entrylist[] = $entry;
381 foreach (array_reverse($entrylist) as $entry) {
383 $authorelement = $xpath->query('/atom:entry/atom:author', $entry);
385 if ($authorelement->length == 0) {
386 $authorelement = $xpath->query('atom:author', $entry);
389 if ($authorelement->length > 0) {
390 $author = self::fetchAuthor($xpath, $entry, $importer, $contact, $stored);
393 $value = $xpath->evaluate('atom:author/poco:preferredUsername/text()', $entry)->item(0)->nodeValue;
397 $nickname = $author["author-name"];
400 $item = array_merge($header, $author);
402 $item["uri"] = $xpath->query('atom:id/text()', $entry)->item(0)->nodeValue;
404 $item["verb"] = $xpath->query('activity:verb/text()', $entry)->item(0)->nodeValue;
407 if (in_array($item["verb"], ['qvitter-delete-notice', ACTIVITY_DELETE, 'delete'])) {
408 self::deleteNotice($item);
412 if (in_array($item["verb"], [NAMESPACE_OSTATUS."/unfavorite", ACTIVITY_UNFAVORITE])) {
413 // Ignore "Unfavorite" message
414 logger("Ignore unfavorite message ".print_r($item, true), LOGGER_DEBUG);
418 // Deletions come with the same uri, so we check for duplicates after processing deletions
419 if (Item::exists(['uid' => $importer["uid"], 'uri' => $item["uri"]])) {
420 logger('Post with URI '.$item["uri"].' already existed for user '.$importer["uid"].'.', LOGGER_DEBUG);
423 logger('Processing post with URI '.$item["uri"].' for user '.$importer["uid"].'.', LOGGER_DEBUG);
426 if ($item["verb"] == ACTIVITY_JOIN) {
427 // ignore "Join" messages
428 logger("Ignore join message ".print_r($item, true), LOGGER_DEBUG);
432 if ($item["verb"] == "http://mastodon.social/schema/1.0/block") {
433 // ignore mastodon "block" messages
434 logger("Ignore block message ".print_r($item, true), LOGGER_DEBUG);
438 if ($item["verb"] == ACTIVITY_FOLLOW) {
439 Contact::addRelationship($importer, $contact, $item, $nickname);
443 if ($item["verb"] == NAMESPACE_OSTATUS."/unfollow") {
444 Contact::removeFollower($importer, $contact, $item, $dummy);
448 if ($item["verb"] == ACTIVITY_FAVORITE) {
449 $orig_uri = $xpath->query("activity:object/atom:id", $entry)->item(0)->nodeValue;
450 logger("Favorite ".$orig_uri." ".print_r($item, true));
452 $item["type"] = "activity";
453 $item["verb"] = ACTIVITY_LIKE;
454 $item["parent-uri"] = $orig_uri;
455 $item["gravity"] = GRAVITY_ACTIVITY;
456 $item["object-type"] = ACTIVITY_OBJ_NOTE;
459 // http://activitystrea.ms/schema/1.0/rsvp-yes
460 if (!in_array($item["verb"], [ACTIVITY_POST, ACTIVITY_LIKE, ACTIVITY_SHARE])) {
461 logger("Unhandled verb ".$item["verb"]." ".print_r($item, true), LOGGER_DEBUG);
464 self::processPost($xpath, $entry, $item, $importer);
466 if ($initialize && (count(self::$itemlist) > 0)) {
467 if (self::$itemlist[0]['uri'] == self::$itemlist[0]['parent-uri']) {
468 // We will import it everytime, when it is started by our contacts
469 $valid = !empty(self::$itemlist[0]['contact-id']);
471 // If not, then it depends on this setting
472 $valid = !Config::get('system', 'ostatus_full_threads');
474 logger("Item with uri ".self::$itemlist[0]['uri']." will be imported due to the system settings.", LOGGER_DEBUG);
477 logger("Item with uri ".self::$itemlist[0]['uri']." belongs to a contact (".self::$itemlist[0]['contact-id']."). It will be imported.", LOGGER_DEBUG);
480 // Never post a thread when the only interaction by our contact was a like
482 $verbs = [ACTIVITY_POST, ACTIVITY_SHARE];
483 foreach (self::$itemlist as $item) {
484 if (!empty($item['contact-id']) && in_array($item['verb'], $verbs)) {
489 logger("Item with uri ".self::$itemlist[0]['uri']." will be imported since the thread contains posts or shares.", LOGGER_DEBUG);
493 // But we will only import complete threads
494 $valid = Item::exists(['uid' => $importer["uid"], 'uri' => self::$itemlist[0]['parent-uri']]);
496 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);
501 $default_contact = 0;
502 $key = count(self::$itemlist);
503 for ($key = count(self::$itemlist) - 1; $key >= 0; $key--) {
504 if (empty(self::$itemlist[$key]['contact-id'])) {
505 self::$itemlist[$key]['contact-id'] = $default_contact;
507 $default_contact = $item['contact-id'];
510 foreach (self::$itemlist as $item) {
511 $found = Item::exists(['uid' => $importer["uid"], 'uri' => $item["uri"]]);
513 logger("Item with uri ".$item["uri"]." for user ".$importer["uid"]." already exists.", LOGGER_DEBUG);
514 } elseif ($item['contact-id'] < 0) {
515 logger("Item with uri ".$item["uri"]." is from a blocked contact.", LOGGER_DEBUG);
517 // We are having duplicated entries. Hopefully this solves it.
518 if (Lock::acquire('ostatus_process_item_insert')) {
519 $ret = Item::insert($item);
520 Lock::release('ostatus_process_item_insert');
521 logger("Item with uri ".$item["uri"]." for user ".$importer["uid"].' stored. Return value: '.$ret);
523 $ret = Item::insert($item);
524 logger("We couldn't lock - but tried to store the item anyway. Return value is ".$ret);
529 self::$itemlist = [];
531 logger('Processing done for post with URI '.$item["uri"].' for user '.$importer["uid"].'.', LOGGER_DEBUG);
537 * @param object $item item
540 private static function deleteNotice($item)
542 $condition = ['uid' => $item['uid'], 'author-id' => $item['author-id'], 'uri' => $item['uri']];
543 if (!Item::exists($condition)) {
544 logger('Item from '.$item['author-link'].' with uri '.$item['uri'].' for user '.$item['uid']." wasn't found. We don't delete it.");
548 Item::delete($condition);
550 logger('Deleted item with uri '.$item['uri'].' for user '.$item['uid']);
554 * @brief Processes the XML for a post
556 * @param object $xpath The xpath object
557 * @param object $entry The xml entry that is processed
558 * @param array $item The item array
559 * @param array $importer user record of the importing user
562 private static function processPost($xpath, $entry, &$item, $importer)
564 $item["body"] = HTML::toBBCode($xpath->query('atom:content/text()', $entry)->item(0)->nodeValue);
565 $item["object-type"] = $xpath->query('activity:object-type/text()', $entry)->item(0)->nodeValue;
566 if (($item["object-type"] == ACTIVITY_OBJ_BOOKMARK) || ($item["object-type"] == ACTIVITY_OBJ_EVENT)) {
567 $item["title"] = $xpath->query('atom:title/text()', $entry)->item(0)->nodeValue;
568 $item["body"] = $xpath->query('atom:summary/text()', $entry)->item(0)->nodeValue;
569 } elseif ($item["object-type"] == ACTIVITY_OBJ_QUESTION) {
570 $item["title"] = $xpath->query('atom:title/text()', $entry)->item(0)->nodeValue;
573 $item["created"] = $xpath->query('atom:published/text()', $entry)->item(0)->nodeValue;
574 $item["edited"] = $xpath->query('atom:updated/text()', $entry)->item(0)->nodeValue;
575 $conversation = $xpath->query('ostatus:conversation/text()', $entry)->item(0)->nodeValue;
576 $item['conversation-uri'] = $conversation;
578 $conv = $xpath->query('ostatus:conversation', $entry);
579 if (is_object($conv->item(0))) {
580 foreach ($conv->item(0)->attributes as $attributes) {
581 if ($attributes->name == "ref") {
582 $item['conversation-uri'] = $attributes->textContent;
584 if ($attributes->name == "href") {
585 $item['conversation-href'] = $attributes->textContent;
592 $inreplyto = $xpath->query('thr:in-reply-to', $entry);
593 if (is_object($inreplyto->item(0))) {
594 foreach ($inreplyto->item(0)->attributes as $attributes) {
595 if ($attributes->name == "ref") {
596 $item["parent-uri"] = $attributes->textContent;
598 if ($attributes->name == "href") {
599 $related = $attributes->textContent;
604 $georsspoint = $xpath->query('georss:point', $entry);
605 if (!empty($georsspoint) && ($georsspoint->length > 0)) {
606 $item["coord"] = $georsspoint->item(0)->nodeValue;
609 $categories = $xpath->query('atom:category', $entry);
611 foreach ($categories as $category) {
612 foreach ($category->attributes as $attributes) {
613 if ($attributes->name == "term") {
614 $term = $attributes->textContent;
615 if (strlen($item["tag"])) {
618 $item["tag"] .= "#[url=".System::baseUrl()."/search?tag=".$term."]".$term."[/url]";
627 $links = $xpath->query('atom:link', $entry);
629 $link_data = self::processLinks($links, $item);
630 $self = $link_data['self'];
631 $add_body = $link_data['add_body'];
636 $notice_info = $xpath->query('statusnet:notice_info', $entry);
637 if ($notice_info && ($notice_info->length > 0)) {
638 foreach ($notice_info->item(0)->attributes as $attributes) {
639 if ($attributes->name == "source") {
640 $item["app"] = strip_tags($attributes->textContent);
642 if ($attributes->name == "repeat_of") {
643 $repeat_of = $attributes->textContent;
647 // Is it a repeated post?
648 if (($repeat_of != "") || ($item["verb"] == ACTIVITY_SHARE)) {
649 $link_data = self::processRepeatedItem($xpath, $entry, $item, $importer);
650 if (!empty($link_data['add_body'])) {
651 $add_body .= $link_data['add_body'];
655 $item["body"] .= $add_body;
657 // Only add additional data when there is no picture in the post
658 if (!strstr($item["body"], '[/img]')) {
659 $item["body"] = add_page_info_to_body($item["body"]);
662 // Mastodon Content Warning
663 if (($item["verb"] == ACTIVITY_POST) && $xpath->evaluate('boolean(atom:summary)', $entry)) {
664 $clear_text = $xpath->query('atom:summary/text()', $entry)->item(0)->nodeValue;
665 if (!empty($clear_text)) {
666 $item['content-warning'] = HTML::toBBCode($clear_text);
670 if (($self != '') && empty($item['protocol'])) {
671 self::fetchSelf($self, $item);
674 if (!empty($item["conversation-href"])) {
675 self::fetchConversation($item['conversation-href'], $item['conversation-uri']);
678 if (isset($item["parent-uri"])) {
679 if (!Item::exists(['uid' => $importer["uid"], 'uri' => $item['parent-uri']])) {
680 if ($related != '') {
681 self::fetchRelated($related, $item["parent-uri"], $importer);
684 logger('Reply with URI '.$item["uri"].' already existed for user '.$importer["uid"].'.', LOGGER_DEBUG);
687 $item["parent-uri"] = $item["uri"];
688 $item["gravity"] = GRAVITY_PARENT;
689 $item["type"] = "remote";
692 if (($item['author-link'] != '') && !empty($item['protocol'])) {
693 $item = Conversation::insert($item);
696 self::$itemlist[] = $item;
700 * @brief Fetch the conversation for posts
702 * @param string $conversation The link to the conversation
703 * @param string $conversation_uri The conversation in "uri" format
706 private static function fetchConversation($conversation, $conversation_uri)
708 // Ensure that we only store a conversation once in a process
709 if (isset(self::$conv_list[$conversation])) {
713 self::$conv_list[$conversation] = true;
715 $conversation_data = Network::curl($conversation, false, $redirects, ['accept_content' => 'application/atom+xml, text/html']);
717 if (!$conversation_data['success']) {
723 if (stristr($conversation_data['header'], 'Content-Type: application/atom+xml')) {
724 $xml = $conversation_data['body'];
728 $doc = new DOMDocument();
729 if (!@$doc->loadHTML($conversation_data['body'])) {
732 $xpath = new DOMXPath($doc);
734 $links = $xpath->query('//link');
737 foreach ($links as $link) {
738 $attribute = self::readAttributes($link);
739 if (($attribute['rel'] == 'alternate') && ($attribute['type'] == 'application/atom+xml')) {
740 $file = $attribute['href'];
744 $conversation_atom = Network::curl($attribute['href']);
746 if ($conversation_atom['success']) {
747 $xml = $conversation_atom['body'];
757 self::storeConversation($xml, $conversation, $conversation_uri);
761 * @brief Store a feed in several conversation entries
763 * @param string $xml The feed
764 * @param string $conversation conversation
765 * @param string $conversation_uri conversation uri
768 private static function storeConversation($xml, $conversation = '', $conversation_uri = '')
770 $doc = new DOMDocument();
771 @$doc->loadXML($xml);
773 $xpath = new DOMXPath($doc);
774 $xpath->registerNamespace('atom', NAMESPACE_ATOM1);
775 $xpath->registerNamespace('thr', NAMESPACE_THREAD);
776 $xpath->registerNamespace('ostatus', NAMESPACE_OSTATUS);
778 $entries = $xpath->query('/atom:feed/atom:entry');
780 // Now store the entries
781 foreach ($entries as $entry) {
782 $doc2 = new DOMDocument();
783 $doc2->preserveWhiteSpace = false;
784 $doc2->formatOutput = true;
788 $conv_data['protocol'] = PROTOCOL_SPLITTED_CONV;
789 $conv_data['network'] = NETWORK_OSTATUS;
790 $conv_data['uri'] = $xpath->query('atom:id/text()', $entry)->item(0)->nodeValue;
792 $inreplyto = $xpath->query('thr:in-reply-to', $entry);
793 if (is_object($inreplyto->item(0))) {
794 foreach ($inreplyto->item(0)->attributes as $attributes) {
795 if ($attributes->name == "ref") {
796 $conv_data['reply-to-uri'] = $attributes->textContent;
801 $conv = $xpath->query('ostatus:conversation/text()', $entry)->item(0)->nodeValue;
802 $conv_data['conversation-uri'] = $conv;
804 $conv = $xpath->query('ostatus:conversation', $entry);
805 if (is_object($conv->item(0))) {
806 foreach ($conv->item(0)->attributes as $attributes) {
807 if ($attributes->name == "ref") {
808 $conv_data['conversation-uri'] = $attributes->textContent;
810 if ($attributes->name == "href") {
811 $conv_data['conversation-href'] = $attributes->textContent;
816 if ($conversation != '') {
817 $conv_data['conversation-uri'] = $conversation;
820 if ($conversation_uri != '') {
821 $conv_data['conversation-uri'] = $conversation_uri;
824 $entry = $doc2->importNode($entry, true);
826 $doc2->appendChild($entry);
828 $conv_data['source'] = $doc2->saveXML();
830 $condition = ['item-uri' => $conv_data['uri'],'protocol' => PROTOCOL_OSTATUS_FEED];
831 if (dba::exists('conversation', $condition)) {
832 logger('Delete deprecated entry for URI '.$conv_data['uri'], LOGGER_DEBUG);
833 dba::delete('conversation', ['item-uri' => $conv_data['uri']]);
836 logger('Store conversation data for uri '.$conv_data['uri'], LOGGER_DEBUG);
837 Conversation::insert($conv_data);
842 * @brief Fetch the own post so that it can be stored later
844 * We want to store the original data for later processing.
845 * This function is meant for cases where we process a feed with multiple entries.
846 * In that case we need to fetch the single posts here.
848 * @param string $self The link to the self item
849 * @param array $item The item array
852 private static function fetchSelf($self, &$item)
854 $condition = ['`item-uri` = ? AND `protocol` IN (?, ?)', $self, PROTOCOL_DFRN, PROTOCOL_OSTATUS_SALMON];
855 if (dba::exists('conversation', $condition)) {
856 logger('Conversation '.$item['uri'].' is already stored.', LOGGER_DEBUG);
860 $self_data = Network::curl($self);
862 if (!$self_data['success']) {
866 // We reformat the XML to make it better readable
867 $doc = new DOMDocument();
868 $doc->loadXML($self_data['body']);
869 $doc->preserveWhiteSpace = false;
870 $doc->formatOutput = true;
871 $xml = $doc->saveXML();
873 $item["protocol"] = PROTOCOL_OSTATUS_SALMON;
874 $item["source"] = $xml;
876 logger('Conversation '.$item['uri'].' is now fetched.', LOGGER_DEBUG);
880 * @brief Fetch related posts and processes them
882 * @param string $related The link to the related item
883 * @param string $related_uri The related item in "uri" format
884 * @param array $importer user record of the importing user
887 private static function fetchRelated($related, $related_uri, $importer)
889 $condition = ['`item-uri` = ? AND `protocol` IN (?, ?)', $related_uri, PROTOCOL_DFRN, PROTOCOL_OSTATUS_SALMON];
890 $conversation = dba::selectFirst('conversation', ['source', 'protocol'], $condition);
891 if (DBM::is_result($conversation)) {
893 $xml = $conversation['source'];
894 if (self::process($xml, $importer, $contact, $hub, $stored, false)) {
895 logger('Got valid cached XML for URI '.$related_uri, LOGGER_DEBUG);
898 if ($conversation['protocol'] == PROTOCOL_OSTATUS_SALMON) {
899 logger('Delete invalid cached XML for URI '.$related_uri, LOGGER_DEBUG);
900 dba::delete('conversation', ['item-uri' => $related_uri]);
905 $related_data = Network::curl($related, false, $redirects, ['accept_content' => 'application/atom+xml, text/html']);
907 if (!$related_data['success']) {
913 if (stristr($related_data['header'], 'Content-Type: application/atom+xml')) {
914 logger('Directly fetched XML for URI '.$related_uri, LOGGER_DEBUG);
915 $xml = $related_data['body'];
919 $doc = new DOMDocument();
920 if (!@$doc->loadHTML($related_data['body'])) {
923 $xpath = new DOMXPath($doc);
927 $links = $xpath->query('//link');
929 foreach ($links as $link) {
930 $attribute = self::readAttributes($link);
931 if (($attribute['rel'] == 'alternate') && ($attribute['type'] == 'application/atom+xml')) {
932 $atom_file = $attribute['href'];
935 if ($atom_file != '') {
936 $related_atom = Network::curl($atom_file);
938 if ($related_atom['success']) {
939 logger('Fetched XML for URI '.$related_uri, LOGGER_DEBUG);
940 $xml = $related_atom['body'];
946 // Workaround for older GNU Social servers
947 if (($xml == '') && strstr($related, '/notice/')) {
948 $related_atom = Network::curl(str_replace('/notice/', '/api/statuses/show/', $related).'.atom');
950 if ($related_atom['success']) {
951 logger('GNU Social workaround to fetch XML for URI '.$related_uri, LOGGER_DEBUG);
952 $xml = $related_atom['body'];
956 // Even more worse workaround for GNU Social ;-)
958 $related_guess = OStatus::convertHref($related_uri);
959 $related_atom = Network::curl(str_replace('/notice/', '/api/statuses/show/', $related_guess).'.atom');
961 if ($related_atom['success']) {
962 logger('GNU Social workaround 2 to fetch XML for URI '.$related_uri, LOGGER_DEBUG);
963 $xml = $related_atom['body'];
967 // Finally we take the data that we fetched from "ostatus:conversation"
969 $condition = ['item-uri' => $related_uri, 'protocol' => PROTOCOL_SPLITTED_CONV];
970 $conversation = dba::selectFirst('conversation', ['source'], $condition);
971 if (DBM::is_result($conversation)) {
973 logger('Got cached XML from conversation for URI '.$related_uri, LOGGER_DEBUG);
974 $xml = $conversation['source'];
979 self::process($xml, $importer, $contact, $hub, $stored, false);
981 logger("XML couldn't be fetched for URI: ".$related_uri." - href: ".$related, LOGGER_DEBUG);
987 * @brief Processes the XML for a repeated post
989 * @param object $xpath The xpath object
990 * @param object $entry The xml entry that is processed
991 * @param array $item The item array
992 * @param array $importer user record of the importing user
994 * @return array with data from links
996 private static function processRepeatedItem($xpath, $entry, &$item, $importer)
998 $activityobjects = $xpath->query('activity:object', $entry)->item(0);
1000 if (!is_object($activityobjects)) {
1006 $orig_uri = $xpath->query('atom:id/text()', $activityobjects)->item(0)->nodeValue;
1008 $links = $xpath->query("atom:link", $activityobjects);
1010 $link_data = self::processLinks($links, $item);
1013 $orig_body = $xpath->query('atom:content/text()', $activityobjects)->item(0)->nodeValue;
1014 $orig_created = $xpath->query('atom:published/text()', $activityobjects)->item(0)->nodeValue;
1015 $orig_edited = $xpath->query('atom:updated/text()', $activityobjects)->item(0)->nodeValue;
1017 $orig_author = self::fetchAuthor($xpath, $activityobjects, $importer, $dummy, false);
1019 $item["author-name"] = $orig_author["author-name"];
1020 $item["author-link"] = $orig_author["author-link"];
1021 $item["author-avatar"] = $orig_author["author-avatar"];
1023 $item["body"] = HTML::toBBCode($orig_body);
1024 $item["created"] = $orig_created;
1025 $item["edited"] = $orig_edited;
1027 $item["uri"] = $orig_uri;
1029 $item["verb"] = $xpath->query('activity:verb/text()', $activityobjects)->item(0)->nodeValue;
1031 $item["object-type"] = $xpath->query('activity:object-type/text()', $activityobjects)->item(0)->nodeValue;
1033 $inreplyto = $xpath->query('thr:in-reply-to', $activityobjects);
1034 if (is_object($inreplyto->item(0))) {
1035 foreach ($inreplyto->item(0)->attributes as $attributes) {
1036 if ($attributes->name == "ref") {
1037 $item["parent-uri"] = $attributes->textContent;
1046 * @brief Processes links in the XML
1048 * @param object $links The xml data that contain links
1049 * @param array $item The item array
1051 * @return array with data from the links
1053 private static function processLinks($links, &$item)
1055 $link_data = ['add_body' => '', 'self' => ''];
1057 foreach ($links as $link) {
1058 $attribute = self::readAttributes($link);
1060 if (($attribute['rel'] != "") && ($attribute['href'] != "")) {
1061 switch ($attribute['rel']) {
1063 $item["plink"] = $attribute['href'];
1064 if (($item["object-type"] == ACTIVITY_OBJ_QUESTION)
1065 || ($item["object-type"] == ACTIVITY_OBJ_EVENT)
1067 $item["body"] .= add_page_info($attribute['href']);
1070 case "ostatus:conversation":
1071 $link_data['conversation'] = $attribute['href'];
1072 $item['conversation-href'] = $link_data['conversation'];
1073 if (!isset($item['conversation-uri'])) {
1074 $item['conversation-uri'] = $item['conversation-href'];
1078 $filetype = strtolower(substr($attribute['type'], 0, strpos($attribute['type'], '/')));
1079 if ($filetype == 'image') {
1080 $link_data['add_body'] .= "\n[img]".$attribute['href'].'[/img]';
1082 if (strlen($item["attach"])) {
1083 $item["attach"] .= ',';
1085 if (!isset($attribute['length'])) {
1086 $attribute['length'] = "0";
1088 $item["attach"] .= '[attach]href="'.$attribute['href'].'" length="'.$attribute['length'].'" type="'.$attribute['type'].'" title="'.$attribute['title'].'"[/attach]';
1092 if ($item["object-type"] != ACTIVITY_OBJ_BOOKMARK) {
1093 if (!isset($item["parent-uri"])) {
1094 $item["parent-uri"] = $attribute['href'];
1096 $link_data['related'] = $attribute['href'];
1098 $item["body"] .= add_page_info($attribute['href']);
1102 if ($item["plink"] == '') {
1103 $item["plink"] = $attribute['href'];
1105 $link_data['self'] = $attribute['href'];
1114 * @brief Create an url out of an uri
1116 * @param string $href URI in the format "parameter1:parameter1:..."
1118 * @return string URL in the format http(s)://....
1120 public static function convertHref($href)
1122 $elements = explode(":", $href);
1124 if ((count($elements) <= 2) || ($elements[0] != "tag")) {
1128 $server = explode(",", $elements[1]);
1129 $conversation = explode("=", $elements[2]);
1131 if ((count($elements) == 4) && ($elements[2] == "post")) {
1132 return "http://".$server[0]."/notice/".$elements[3];
1135 if ((count($conversation) != 2) || ($conversation[1] =="")) {
1138 if ($elements[3] == "objectType=thread") {
1139 return "http://".$server[0]."/conversation/".$conversation[1];
1141 return "http://".$server[0]."/notice/".$conversation[1];
1147 * @brief Checks if the current post is a reshare
1149 * @param array $item The item array of thw post
1151 * @return string The guid if the post is a reshare
1153 private static function getResharedGuid($item)
1155 $body = trim($item["body"]);
1157 // Skip if it isn't a pure repeated messages
1158 // Does it start with a share?
1159 if (strpos($body, "[share") > 0) {
1163 // Does it end with a share?
1164 if (strlen($body) > (strrpos($body, "[/share]") + 8)) {
1168 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "$1", $body);
1169 // Skip if there is no shared message in there
1170 if ($body == $attributes) {
1175 preg_match("/guid='(.*?)'/ism", $attributes, $matches);
1176 if (!empty($matches[1])) {
1177 $guid = $matches[1];
1180 preg_match('/guid="(.*?)"/ism', $attributes, $matches);
1181 if (!empty($matches[1])) {
1182 $guid = $matches[1];
1189 * @brief Cleans the body of a post if it contains picture links
1191 * @param string $body The body
1193 * @return string The cleaned body
1195 private static function formatPicturePost($body)
1197 $siteinfo = BBCode::getAttachedData($body);
1199 if (($siteinfo["type"] == "photo")) {
1200 if (isset($siteinfo["preview"])) {
1201 $preview = $siteinfo["preview"];
1203 $preview = $siteinfo["image"];
1206 // Is it a remote picture? Then make a smaller preview here
1207 $preview = proxy_url($preview, false, PROXY_SIZE_SMALL);
1209 // Is it a local picture? Then make it smaller here
1210 $preview = str_replace(["-0.jpg", "-0.png"], ["-2.jpg", "-2.png"], $preview);
1211 $preview = str_replace(["-1.jpg", "-1.png"], ["-2.jpg", "-2.png"], $preview);
1213 if (isset($siteinfo["url"])) {
1214 $url = $siteinfo["url"];
1216 $url = $siteinfo["image"];
1219 $body = trim($siteinfo["text"])." [url]".$url."[/url]\n[img]".$preview."[/img]";
1226 * @brief Adds the header elements to the XML document
1228 * @param object $doc XML document
1229 * @param array $owner Contact data of the poster
1230 * @param string $filter The related feed filter (activity, posts or comments)
1232 * @return object header root element
1234 private static function addHeader($doc, $owner, $filter)
1238 $root = $doc->createElementNS(NAMESPACE_ATOM1, 'feed');
1239 $doc->appendChild($root);
1241 $root->setAttribute("xmlns:thr", NAMESPACE_THREAD);
1242 $root->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
1243 $root->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
1244 $root->setAttribute("xmlns:media", NAMESPACE_MEDIA);
1245 $root->setAttribute("xmlns:poco", NAMESPACE_POCO);
1246 $root->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
1247 $root->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
1248 $root->setAttribute("xmlns:mastodon", NAMESPACE_MASTODON);
1252 case 'activity': $title = L10n::t('%s\'s timeline', $owner['name']); break;
1253 case 'posts' : $title = L10n::t('%s\'s posts' , $owner['name']); break;
1254 case 'comments': $title = L10n::t('%s\'s comments', $owner['name']); break;
1257 $attributes = ["uri" => "https://friendi.ca", "version" => FRIENDICA_VERSION . "-" . DB_UPDATE_VERSION];
1258 XML::addElement($doc, $root, "generator", FRIENDICA_PLATFORM, $attributes);
1259 XML::addElement($doc, $root, "id", System::baseUrl() . "/profile/" . $owner["nick"]);
1260 XML::addElement($doc, $root, "title", $title);
1261 XML::addElement($doc, $root, "subtitle", sprintf("Updates from %s on %s", $owner["name"], $a->config["sitename"]));
1262 XML::addElement($doc, $root, "logo", $owner["photo"]);
1263 XML::addElement($doc, $root, "updated", DateTimeFormat::utcNow(DateTimeFormat::ATOM));
1265 $author = self::addAuthor($doc, $owner);
1266 $root->appendChild($author);
1268 $attributes = ["href" => $owner["url"], "rel" => "alternate", "type" => "text/html"];
1269 XML::addElement($doc, $root, "link", "", $attributes);
1271 /// @TODO We have to find out what this is
1272 /// $attributes = array("href" => System::baseUrl()."/sup",
1273 /// "rel" => "http://api.friendfeed.com/2008/03#sup",
1274 /// "type" => "application/json");
1275 /// XML::addElement($doc, $root, "link", "", $attributes);
1277 self::hublinks($doc, $root, $owner["nick"]);
1279 $attributes = ["href" => System::baseUrl() . "/salmon/" . $owner["nick"], "rel" => "salmon"];
1280 XML::addElement($doc, $root, "link", "", $attributes);
1282 $attributes = ["href" => System::baseUrl() . "/salmon/" . $owner["nick"], "rel" => "http://salmon-protocol.org/ns/salmon-replies"];
1283 XML::addElement($doc, $root, "link", "", $attributes);
1285 $attributes = ["href" => System::baseUrl() . "/salmon/" . $owner["nick"], "rel" => "http://salmon-protocol.org/ns/salmon-mention"];
1286 XML::addElement($doc, $root, "link", "", $attributes);
1288 $attributes = ["href" => System::baseUrl() . "/api/statuses/user_timeline/" . $owner["nick"] . ".atom",
1289 "rel" => "self", "type" => "application/atom+xml"];
1290 XML::addElement($doc, $root, "link", "", $attributes);
1292 if ($owner['account-type'] == ACCOUNT_TYPE_COMMUNITY) {
1293 $condition = ['uid' => $owner['uid'], 'self' => false, 'pending' => false,
1294 'archive' => false, 'hidden' => false, 'blocked' => false];
1295 $members = dba::count('contact', $condition);
1296 XML::addElement($doc, $root, "statusnet:group_info", "", ["member_count" => $members]);
1303 * @brief Add the link to the push hubs to the XML document
1305 * @param object $doc XML document
1306 * @param object $root XML root element where the hub links are added
1307 * @param object $nick nick
1310 public static function hublinks($doc, $root, $nick)
1312 $h = System::baseUrl() . '/pubsubhubbub/'.$nick;
1313 XML::addElement($doc, $root, "link", "", ["href" => $h, "rel" => "hub"]);
1317 * @brief Adds attachment data to the XML document
1319 * @param object $doc XML document
1320 * @param object $root XML root element where the hub links are added
1321 * @param array $item Data of the item that is to be posted
1324 private static function getAttachment($doc, $root, $item)
1327 $siteinfo = BBCode::getAttachedData($item["body"]);
1329 switch ($siteinfo["type"]) {
1331 $imgdata = Image::getInfoFromURL($siteinfo["image"]);
1333 $attributes = ["rel" => "enclosure",
1334 "href" => $siteinfo["image"],
1335 "type" => $imgdata["mime"],
1336 "length" => intval($imgdata["size"])];
1337 XML::addElement($doc, $root, "link", "", $attributes);
1341 $attributes = ["rel" => "enclosure",
1342 "href" => $siteinfo["url"],
1343 "type" => "text/html; charset=UTF-8",
1345 "title" => $siteinfo["title"]];
1346 XML::addElement($doc, $root, "link", "", $attributes);
1352 if (!Config::get('system', 'ostatus_not_attach_preview') && ($siteinfo["type"] != "photo") && isset($siteinfo["image"])) {
1353 $imgdata = Image::getInfoFromURL($siteinfo["image"]);
1355 $attributes = ["rel" => "enclosure",
1356 "href" => $siteinfo["image"],
1357 "type" => $imgdata["mime"],
1358 "length" => intval($imgdata["size"])];
1360 XML::addElement($doc, $root, "link", "", $attributes);
1364 $arr = explode('[/attach],', $item['attach']);
1366 foreach ($arr as $r) {
1368 $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"|', $r, $matches);
1370 $attributes = ["rel" => "enclosure",
1371 "href" => $matches[1],
1372 "type" => $matches[3]];
1374 if (intval($matches[2])) {
1375 $attributes["length"] = intval($matches[2]);
1377 if (trim($matches[4]) != "") {
1378 $attributes["title"] = trim($matches[4]);
1380 XML::addElement($doc, $root, "link", "", $attributes);
1387 * @brief Adds the author element to the XML document
1389 * @param object $doc XML document
1390 * @param array $owner Contact data of the poster
1392 * @return object author element
1394 private static function addAuthor($doc, $owner, $show_profile = true)
1396 $profile = dba::selectFirst('profile', ['homepage', 'publish'], ['uid' => $owner['uid'], 'is-default' => true]);
1397 $author = $doc->createElement("author");
1398 XML::addElement($doc, $author, "id", $owner["url"]);
1399 if ($owner['account-type'] == ACCOUNT_TYPE_COMMUNITY) {
1400 XML::addElement($doc, $author, "activity:object-type", ACTIVITY_OBJ_GROUP);
1402 XML::addElement($doc, $author, "activity:object-type", ACTIVITY_OBJ_PERSON);
1404 XML::addElement($doc, $author, "uri", $owner["url"]);
1405 XML::addElement($doc, $author, "name", $owner["nick"]);
1406 XML::addElement($doc, $author, "email", $owner["addr"]);
1407 if ($show_profile) {
1408 XML::addElement($doc, $author, "summary", BBCode::convert($owner["about"], false, 7));
1411 $attributes = ["rel" => "alternate", "type" => "text/html", "href" => $owner["url"]];
1412 XML::addElement($doc, $author, "link", "", $attributes);
1416 "type" => "image/jpeg", // To-Do?
1417 "media:width" => 175,
1418 "media:height" => 175,
1419 "href" => $owner["photo"]];
1420 XML::addElement($doc, $author, "link", "", $attributes);
1422 if (isset($owner["thumb"])) {
1425 "type" => "image/jpeg", // To-Do?
1426 "media:width" => 80,
1427 "media:height" => 80,
1428 "href" => $owner["thumb"]];
1429 XML::addElement($doc, $author, "link", "", $attributes);
1432 XML::addElement($doc, $author, "poco:preferredUsername", $owner["nick"]);
1433 XML::addElement($doc, $author, "poco:displayName", $owner["name"]);
1434 if ($show_profile) {
1435 XML::addElement($doc, $author, "poco:note", BBCode::convert($owner["about"], false, 7));
1437 if (trim($owner["location"]) != "") {
1438 $element = $doc->createElement("poco:address");
1439 XML::addElement($doc, $element, "poco:formatted", $owner["location"]);
1440 $author->appendChild($element);
1444 if (DBM::is_result($profile) && !$show_profile) {
1445 if (trim($profile["homepage"]) != "") {
1446 $urls = $doc->createElement("poco:urls");
1447 XML::addElement($doc, $urls, "poco:type", "homepage");
1448 XML::addElement($doc, $urls, "poco:value", $profile["homepage"]);
1449 XML::addElement($doc, $urls, "poco:primary", "true");
1450 $author->appendChild($urls);
1453 XML::addElement($doc, $author, "followers", "", ["url" => System::baseUrl()."/viewcontacts/".$owner["nick"]]);
1454 XML::addElement($doc, $author, "statusnet:profile_info", "", ["local_id" => $owner["uid"]]);
1456 if ($profile["publish"]) {
1457 XML::addElement($doc, $author, "mastodon:scope", "public");
1465 * @TODO Picture attachments should look like this:
1466 * <a href="https://status.pirati.ca/attachment/572819" title="https://status.pirati.ca/file/heluecht-20151202T222602-rd3u49p.gif"
1467 * class="attachment thumbnail" id="attachment-572819" rel="nofollow external">https://status.pirati.ca/attachment/572819</a>
1471 * @brief Returns the given activity if present - otherwise returns the "post" activity
1473 * @param array $item Data of the item that is to be posted
1475 * @return string activity
1477 private static function constructVerb($item)
1479 if ($item['verb']) {
1480 return $item['verb'];
1483 return ACTIVITY_POST;
1487 * @brief Returns the given object type if present - otherwise returns the "note" object type
1489 * @param array $item Data of the item that is to be posted
1491 * @return string Object type
1493 private static function constructObjecttype($item)
1495 if (in_array($item['object-type'], [ACTIVITY_OBJ_NOTE, ACTIVITY_OBJ_COMMENT]))
1496 return $item['object-type'];
1497 return ACTIVITY_OBJ_NOTE;
1501 * @brief Adds an entry element to the XML document
1503 * @param object $doc XML document
1504 * @param array $item Data of the item that is to be posted
1505 * @param array $owner Contact data of the poster
1506 * @param bool $toplevel optional default false
1508 * @return object Entry element
1510 private static function entry($doc, $item, $owner, $toplevel = false)
1514 $repeated_guid = self::getResharedGuid($item);
1515 if ($repeated_guid != "") {
1516 $xml = self::reshareEntry($doc, $item, $owner, $repeated_guid, $toplevel);
1523 if ($item["verb"] == ACTIVITY_LIKE) {
1524 return self::likeEntry($doc, $item, $owner, $toplevel);
1525 } elseif (in_array($item["verb"], [ACTIVITY_FOLLOW, NAMESPACE_OSTATUS."/unfollow"])) {
1526 return self::followEntry($doc, $item, $owner, $toplevel);
1528 return self::noteEntry($doc, $item, $owner, $toplevel);
1533 * @brief Adds a source entry to the XML document
1535 * @param object $doc XML document
1536 * @param array $contact Array of the contact that is added
1538 * @return object Source element
1540 private static function sourceEntry($doc, $contact)
1542 $source = $doc->createElement("source");
1543 XML::addElement($doc, $source, "id", $contact["poll"]);
1544 XML::addElement($doc, $source, "title", $contact["name"]);
1545 XML::addElement($doc, $source, "link", "", ["rel" => "alternate", "type" => "text/html", "href" => $contact["alias"]]);
1546 XML::addElement($doc, $source, "link", "", ["rel" => "self", "type" => "application/atom+xml", "href" => $contact["poll"]]);
1547 XML::addElement($doc, $source, "icon", $contact["photo"]);
1548 XML::addElement($doc, $source, "updated", DateTimeFormat::utc($contact["success_update"]."+00:00", DateTimeFormat::ATOM));
1554 * @brief Fetches contact data from the contact or the gcontact table
1556 * @param string $url URL of the contact
1557 * @param array $owner Contact data of the poster
1559 * @return array Contact array
1561 private static function contactEntry($url, $owner)
1564 "SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` IN (0, %d) ORDER BY `uid` DESC LIMIT 1",
1565 dbesc(normalise_link($url)),
1566 intval($owner["uid"])
1568 if (DBM::is_result($r)) {
1570 $contact["uid"] = -1;
1573 if (!DBM::is_result($r)) {
1575 "SELECT * FROM `gcontact` WHERE `nurl` = '%s' LIMIT 1",
1576 dbesc(normalise_link($url))
1578 if (DBM::is_result($r)) {
1580 $contact["uid"] = -1;
1581 $contact["success_update"] = $contact["updated"];
1585 if (!DBM::is_result($r)) {
1589 if (!isset($contact["poll"])) {
1590 $data = Probe::uri($url);
1591 $contact["poll"] = $data["poll"];
1593 if (!$contact["alias"]) {
1594 $contact["alias"] = $data["alias"];
1598 if (!isset($contact["alias"])) {
1599 $contact["alias"] = $contact["url"];
1606 * @brief Adds an entry element with reshared content
1608 * @param object $doc XML document
1609 * @param array $item Data of the item that is to be posted
1610 * @param array $owner Contact data of the poster
1611 * @param string $repeated_guid guid
1612 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1614 * @return object Entry element
1616 private static function reshareEntry($doc, $item, $owner, $repeated_guid, $toplevel)
1618 if (($item["id"] != $item["parent"]) && (normalise_link($item["author-link"]) != normalise_link($owner["url"]))) {
1619 logger("OStatus entry is from author ".$owner["url"]." - not from ".$item["author-link"].". Quitting.", LOGGER_DEBUG);
1622 $title = self::entryHeader($doc, $entry, $owner, $item, $toplevel);
1624 $condition = ['uid' => $owner["uid"], 'guid' => $repeated_guid, 'private' => false,
1625 'network' => [NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS]];
1626 $repeated_item = Item::selectFirst([], $condition);
1627 if (!DBM::is_result($repeated_item)) {
1631 $contact = self::contactEntry($repeated_item['author-link'], $owner);
1633 $title = $owner["nick"]." repeated a notice by ".$contact["nick"];
1635 self::entryContent($doc, $entry, $item, $owner, $title, ACTIVITY_SHARE, false);
1637 $as_object = $doc->createElement("activity:object");
1639 XML::addElement($doc, $as_object, "activity:object-type", NAMESPACE_ACTIVITY_SCHEMA."activity");
1641 self::entryContent($doc, $as_object, $repeated_item, $owner, "", "", false);
1643 $author = self::addAuthor($doc, $contact, false);
1644 $as_object->appendChild($author);
1646 $as_object2 = $doc->createElement("activity:object");
1648 XML::addElement($doc, $as_object2, "activity:object-type", self::constructObjecttype($repeated_item));
1650 $title = sprintf("New comment by %s", $contact["nick"]);
1652 self::entryContent($doc, $as_object2, $repeated_item, $owner, $title);
1654 $as_object->appendChild($as_object2);
1656 self::entryFooter($doc, $as_object, $item, $owner, false);
1658 $source = self::sourceEntry($doc, $contact);
1660 $as_object->appendChild($source);
1662 $entry->appendChild($as_object);
1664 self::entryFooter($doc, $entry, $item, $owner);
1670 * @brief Adds an entry element with a "like"
1672 * @param object $doc XML document
1673 * @param array $item Data of the item that is to be posted
1674 * @param array $owner Contact data of the poster
1675 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1677 * @return object Entry element with "like"
1679 private static function likeEntry($doc, $item, $owner, $toplevel)
1681 if (($item["id"] != $item["parent"]) && (normalise_link($item["author-link"]) != normalise_link($owner["url"]))) {
1682 logger("OStatus entry is from author ".$owner["url"]." - not from ".$item["author-link"].". Quitting.", LOGGER_DEBUG);
1685 $title = self::entryHeader($doc, $entry, $owner, $item, $toplevel);
1687 $verb = NAMESPACE_ACTIVITY_SCHEMA."favorite";
1688 self::entryContent($doc, $entry, $item, $owner, "Favorite", $verb, false);
1690 $as_object = $doc->createElement("activity:object");
1692 $parent = Item::selectFirst([], ['uri' => $item["thr-parent"], 'uid' => $item["uid"]]);
1694 XML::addElement($doc, $as_object, "activity:object-type", self::constructObjecttype($parent));
1696 self::entryContent($doc, $as_object, $parent, $owner, "New entry");
1698 $entry->appendChild($as_object);
1700 self::entryFooter($doc, $entry, $item, $owner);
1706 * @brief Adds the person object element to the XML document
1708 * @param object $doc XML document
1709 * @param array $owner Contact data of the poster
1710 * @param array $contact Contact data of the target
1712 * @return object author element
1714 private static function addPersonObject($doc, $owner, $contact)
1716 $object = $doc->createElement("activity:object");
1717 XML::addElement($doc, $object, "activity:object-type", ACTIVITY_OBJ_PERSON);
1719 if ($contact['network'] == NETWORK_PHANTOM) {
1720 XML::addElement($doc, $object, "id", $contact['url']);
1724 XML::addElement($doc, $object, "id", $contact["alias"]);
1725 XML::addElement($doc, $object, "title", $contact["nick"]);
1727 $attributes = ["rel" => "alternate", "type" => "text/html", "href" => $contact["url"]];
1728 XML::addElement($doc, $object, "link", "", $attributes);
1732 "type" => "image/jpeg", // To-Do?
1733 "media:width" => 175,
1734 "media:height" => 175,
1735 "href" => $contact["photo"]];
1736 XML::addElement($doc, $object, "link", "", $attributes);
1738 XML::addElement($doc, $object, "poco:preferredUsername", $contact["nick"]);
1739 XML::addElement($doc, $object, "poco:displayName", $contact["name"]);
1741 if (trim($contact["location"]) != "") {
1742 $element = $doc->createElement("poco:address");
1743 XML::addElement($doc, $element, "poco:formatted", $contact["location"]);
1744 $object->appendChild($element);
1751 * @brief Adds a follow/unfollow entry element
1753 * @param object $doc XML document
1754 * @param array $item Data of the follow/unfollow message
1755 * @param array $owner Contact data of the poster
1756 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1758 * @return object Entry element
1760 private static function followEntry($doc, $item, $owner, $toplevel)
1762 $item["id"] = $item["parent"] = 0;
1763 $item["created"] = $item["edited"] = date("c");
1764 $item["private"] = true;
1766 $contact = Probe::uri($item['follow']);
1768 if ($contact['alias'] == '') {
1769 $contact['alias'] = $contact["url"];
1771 $item['follow'] = $contact['alias'];
1775 "SELECT `id` FROM `contact` WHERE `uid` = %d AND `nurl` = '%s'",
1776 intval($owner['uid']),
1777 dbesc(normalise_link($contact["url"]))
1780 if (DBM::is_result($r)) {
1781 $connect_id = $r[0]['id'];
1786 if ($item['verb'] == ACTIVITY_FOLLOW) {
1787 $message = L10n::t('%s is now following %s.');
1788 $title = L10n::t('following');
1789 $action = "subscription";
1791 $message = L10n::t('%s stopped following %s.');
1792 $title = L10n::t('stopped following');
1793 $action = "unfollow";
1796 $item["uri"] = $item['parent-uri'] = $item['thr-parent']
1797 = 'tag:'.get_app()->get_hostname().
1798 ','.date('Y-m-d').':'.$action.':'.$owner['uid'].
1799 ':person:'.$connect_id.':'.$item['created'];
1801 $item["body"] = sprintf($message, $owner["nick"], $contact["nick"]);
1803 self::entryHeader($doc, $entry, $owner, $item, $toplevel);
1805 self::entryContent($doc, $entry, $item, $owner, $title);
1807 $object = self::addPersonObject($doc, $owner, $contact);
1808 $entry->appendChild($object);
1810 self::entryFooter($doc, $entry, $item, $owner);
1816 * @brief Adds a regular entry element
1818 * @param object $doc XML document
1819 * @param array $item Data of the item that is to be posted
1820 * @param array $owner Contact data of the poster
1821 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1823 * @return object Entry element
1825 private static function noteEntry($doc, $item, $owner, $toplevel)
1827 if (($item["id"] != $item["parent"]) && (normalise_link($item["author-link"]) != normalise_link($owner["url"]))) {
1828 logger("OStatus entry is from author ".$owner["url"]." - not from ".$item["author-link"].". Quitting.", LOGGER_DEBUG);
1831 $title = self::entryHeader($doc, $entry, $owner, $item, $toplevel);
1833 XML::addElement($doc, $entry, "activity:object-type", ACTIVITY_OBJ_NOTE);
1835 self::entryContent($doc, $entry, $item, $owner, $title);
1837 self::entryFooter($doc, $entry, $item, $owner);
1843 * @brief Adds a header element to the XML document
1845 * @param object $doc XML document
1846 * @param object $entry The entry element where the elements are added
1847 * @param array $owner Contact data of the poster
1848 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1850 * @return string The title for the element
1852 private static function entryHeader($doc, &$entry, $owner, $item, $toplevel)
1854 /// @todo Check if this title stuff is really needed (I guess not)
1856 $entry = $doc->createElement("entry");
1857 $title = sprintf("New note by %s", $owner["nick"]);
1859 if ($owner['account-type'] == ACCOUNT_TYPE_COMMUNITY) {
1860 $contact = self::contactEntry($item['author-link'], $owner);
1861 $author = self::addAuthor($doc, $contact, false);
1862 $entry->appendChild($author);
1865 $entry = $doc->createElementNS(NAMESPACE_ATOM1, "entry");
1867 $entry->setAttribute("xmlns:thr", NAMESPACE_THREAD);
1868 $entry->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
1869 $entry->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
1870 $entry->setAttribute("xmlns:media", NAMESPACE_MEDIA);
1871 $entry->setAttribute("xmlns:poco", NAMESPACE_POCO);
1872 $entry->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
1873 $entry->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
1874 $entry->setAttribute("xmlns:mastodon", NAMESPACE_MASTODON);
1876 $author = self::addAuthor($doc, $owner);
1877 $entry->appendChild($author);
1879 $title = sprintf("New comment by %s", $owner["nick"]);
1885 * @brief Adds elements to the XML document
1887 * @param object $doc XML document
1888 * @param object $entry Entry element where the content is added
1889 * @param array $item Data of the item that is to be posted
1890 * @param array $owner Contact data of the poster
1891 * @param string $title Title for the post
1892 * @param string $verb The activity verb
1893 * @param bool $complete Add the "status_net" element?
1896 private static function entryContent($doc, $entry, $item, $owner, $title, $verb = "", $complete = true)
1899 $verb = self::constructVerb($item);
1902 XML::addElement($doc, $entry, "id", $item["uri"]);
1903 XML::addElement($doc, $entry, "title", $title);
1905 $body = self::formatPicturePost($item['body']);
1907 if ($item['title'] != "") {
1908 $body = "[b]".$item['title']."[/b]\n\n".$body;
1911 $body = BBCode::convert($body, false, 7);
1913 XML::addElement($doc, $entry, "content", $body, ["type" => "html"]);
1915 XML::addElement($doc, $entry, "link", "", ["rel" => "alternate", "type" => "text/html",
1916 "href" => System::baseUrl()."/display/".$item["guid"]]
1919 if ($complete && ($item["id"] > 0)) {
1920 XML::addElement($doc, $entry, "status_net", "", ["notice_id" => $item["id"]]);
1923 XML::addElement($doc, $entry, "activity:verb", $verb);
1925 XML::addElement($doc, $entry, "published", DateTimeFormat::utc($item["created"]."+00:00", DateTimeFormat::ATOM));
1926 XML::addElement($doc, $entry, "updated", DateTimeFormat::utc($item["edited"]."+00:00", DateTimeFormat::ATOM));
1930 * @brief Adds the elements at the foot of an entry to the XML document
1932 * @param object $doc XML document
1933 * @param object $entry The entry element where the elements are added
1934 * @param array $item Data of the item that is to be posted
1935 * @param array $owner Contact data of the poster
1936 * @param bool $complete default true
1939 private static function entryFooter($doc, $entry, array $item, array $owner, $complete = true)
1943 if (($item['parent'] != $item['id']) || ($item['parent-uri'] !== $item['uri']) || (($item['thr-parent'] !== '') && ($item['thr-parent'] !== $item['uri']))) {
1944 $parent = Item::selectFirst(['guid', 'author-link', 'owner-link'], ['id' => $item["parent"]]);
1945 $parent_item = (($item['thr-parent']) ? $item['thr-parent'] : $item['parent-uri']);
1947 $thrparent = Item::selectFirst(['guid', 'author-link', 'owner-link', 'plink'], ['uid' => $owner["uid"], 'uri' => $parent_item]);
1949 if (DBM::is_result($thrparent)) {
1950 $mentioned[$thrparent["author-link"]] = $thrparent["author-link"];
1951 $mentioned[$thrparent["owner-link"]] = $thrparent["owner-link"];
1952 $parent_plink = $thrparent["plink"];
1954 $mentioned[$parent["author-link"]] = $parent["author-link"];
1955 $mentioned[$parent["owner-link"]] = $parent["owner-link"];
1956 $parent_plink = System::baseUrl()."/display/".$parent["guid"];
1960 "ref" => $parent_item,
1961 "href" => $parent_plink];
1962 XML::addElement($doc, $entry, "thr:in-reply-to", "", $attributes);
1966 "href" => $parent_plink];
1967 XML::addElement($doc, $entry, "link", "", $attributes);
1970 if (intval($item["parent"]) > 0) {
1971 $conversation_href = System::baseUrl()."/display/".$owner["nick"]."/".$item["parent"];
1972 $conversation_uri = $conversation_href;
1974 if (isset($parent_item)) {
1975 $conversation = dba::selectFirst('conversation', ['conversation-uri', 'conversation-href'], ['item-uri' => $parent_item]);
1976 if (DBM::is_result($conversation)) {
1977 if ($r['conversation-uri'] != '') {
1978 $conversation_uri = $conversation['conversation-uri'];
1980 if ($r['conversation-href'] != '') {
1981 $conversation_href = $conversation['conversation-href'];
1986 XML::addElement($doc, $entry, "link", "", ["rel" => "ostatus:conversation", "href" => $conversation_href]);
1989 "href" => $conversation_href,
1990 "local_id" => $item["parent"],
1991 "ref" => $conversation_uri];
1993 XML::addElement($doc, $entry, "ostatus:conversation", $conversation_uri, $attributes);
1996 $tags = item::getFeedTags($item);
1999 foreach ($tags as $t) {
2001 $mentioned[$t[1]] = $t[1];
2006 // Make sure that mentions are accepted (GNU Social has problems with mixing HTTP and HTTPS)
2008 foreach ($mentioned as $mention) {
2009 $newmentions[str_replace("http://", "https://", $mention)] = str_replace("http://", "https://", $mention);
2010 $newmentions[str_replace("https://", "http://", $mention)] = str_replace("https://", "http://", $mention);
2012 $mentioned = $newmentions;
2014 foreach ($mentioned as $mention) {
2015 $condition = ['uid' => $owner['uid'], 'nurl' => normalise_link($mention)];
2016 $contact = dba::selectFirst('contact', ['forum', 'prv', 'self', 'contact-type'], $condition);
2017 if ($contact["forum"] || $contact["prv"] || ($owner['contact-type'] == ACCOUNT_TYPE_COMMUNITY) ||
2018 ($contact['self'] && ($owner['account-type'] == ACCOUNT_TYPE_COMMUNITY))) {
2019 XML::addElement($doc, $entry, "link", "",
2021 "rel" => "mentioned",
2022 "ostatus:object-type" => ACTIVITY_OBJ_GROUP,
2026 XML::addElement($doc, $entry, "link", "",
2028 "rel" => "mentioned",
2029 "ostatus:object-type" => ACTIVITY_OBJ_PERSON,
2035 if ($owner['account-type'] == ACCOUNT_TYPE_COMMUNITY) {
2036 XML::addElement($doc, $entry, "link", "", [
2037 "rel" => "mentioned",
2038 "ostatus:object-type" => "http://activitystrea.ms/schema/1.0/group",
2039 "href" => $owner['url']
2043 if (!$item["private"]) {
2044 XML::addElement($doc, $entry, "link", "", ["rel" => "ostatus:attention",
2045 "href" => "http://activityschema.org/collection/public"]);
2046 XML::addElement($doc, $entry, "link", "", ["rel" => "mentioned",
2047 "ostatus:object-type" => "http://activitystrea.ms/schema/1.0/collection",
2048 "href" => "http://activityschema.org/collection/public"]);
2049 XML::addElement($doc, $entry, "mastodon:scope", "public");
2053 foreach ($tags as $t) {
2055 XML::addElement($doc, $entry, "category", "", ["term" => $t[2]]);
2060 self::getAttachment($doc, $entry, $item);
2062 if ($complete && ($item["id"] > 0)) {
2063 $app = $item["app"];
2068 $attributes = ["local_id" => $item["id"], "source" => $app];
2070 if (isset($parent["id"])) {
2071 $attributes["repeat_of"] = $parent["id"];
2074 if ($item["coord"] != "") {
2075 XML::addElement($doc, $entry, "georss:point", $item["coord"]);
2078 XML::addElement($doc, $entry, "statusnet:notice_info", "", $attributes);
2083 * Creates the XML feed for a given nickname
2085 * Supported filters:
2086 * - activity (default): all the public posts
2087 * - posts: all the public top-level posts
2088 * - comments: all the public replies
2090 * Updates the provided last_update parameter if the result comes from the
2091 * cache or it is empty
2093 * @brief Creates the XML feed for a given nickname
2095 * @param string $owner_nick Nickname of the feed owner
2096 * @param string $last_update Date of the last update
2097 * @param integer $max_items Number of maximum items to fetch
2098 * @param string $filter Feed items filter (activity, posts or comments)
2099 * @param boolean $nocache Wether to bypass caching
2101 * @return string XML feed
2103 public static function feed($owner_nick, &$last_update, $max_items = 300, $filter = 'activity', $nocache = false)
2105 $stamp = microtime(true);
2107 $owner = User::getOwnerDataByNick($owner_nick);
2112 $cachekey = "ostatus:feed:" . $owner_nick . ":" . $filter . ":" . $last_update;
2114 $previous_created = $last_update;
2116 // Don't cache when the last item was posted less then 15 minutes ago (Cache duration)
2117 if ((time() - strtotime($owner['last-item'])) < 15*60) {
2118 $result = Cache::get($cachekey);
2119 if (!$nocache && !is_null($result)) {
2120 logger('Feed duration: ' . number_format(microtime(true) - $stamp, 3) . ' - ' . $owner_nick . ' - ' . $filter . ' - ' . $previous_created . ' (cached)', LOGGER_DEBUG);
2121 $last_update = $result['last_update'];
2122 return $result['feed'];
2126 if (!strlen($last_update)) {
2127 $last_update = 'now -30 days';
2130 $check_date = DateTimeFormat::utc($last_update);
2131 $authorid = Contact::getIdForURL($owner["url"], 0, true);
2133 $condition = ["`uid` = ? AND `created` > ? AND NOT `deleted`
2134 AND NOT `private` AND `visible` AND `wall` AND `parent-network` IN (?, ?)",
2135 $owner["uid"], $check_date, NETWORK_OSTATUS, NETWORK_DFRN];
2137 if ($filter === 'comments') {
2138 $condition[0] .= " AND `object-type` = ? ";
2139 $condition[] = ACTIVITY_OBJ_COMMENT;
2142 if ($owner['account-type'] != ACCOUNT_TYPE_COMMUNITY) {
2143 $condition[0] .= " AND `contact-id` = ? AND `author-id` = ?";
2144 $condition[] = $owner["id"];
2145 $condition[] = $authorid;
2148 $params = ['order' => ['created' => true], 'limit' => $max_items];
2150 if ($filter === 'posts') {
2151 $ret = Item::selectThread([], $condition, $params);
2153 $ret = Item::select([], $condition, $params);
2156 $items = Item::inArray($ret);
2158 $doc = new DOMDocument('1.0', 'utf-8');
2159 $doc->formatOutput = true;
2161 $root = self::addHeader($doc, $owner, $filter);
2163 foreach ($items as $item) {
2164 if (Config::get('system', 'ostatus_debug')) {
2165 $item['body'] .= '🍼';
2167 $entry = self::entry($doc, $item, $owner);
2168 $root->appendChild($entry);
2170 if ($last_update < $item['created']) {
2171 $last_update = $item['created'];
2175 $feeddata = trim($doc->saveXML());
2177 $msg = ['feed' => $feeddata, 'last_update' => $last_update];
2178 Cache::set($cachekey, $msg, CACHE_QUARTER_HOUR);
2180 logger('Feed duration: ' . number_format(microtime(true) - $stamp, 3) . ' - ' . $owner_nick . ' - ' . $filter . ' - ' . $previous_created, LOGGER_DEBUG);
2186 * @brief Creates the XML for a salmon message
2188 * @param array $item Data of the item that is to be posted
2189 * @param array $owner Contact data of the poster
2191 * @return string XML for the salmon
2193 public static function salmon($item, $owner)
2195 $doc = new DOMDocument('1.0', 'utf-8');
2196 $doc->formatOutput = true;
2198 if (Config::get('system', 'ostatus_debug')) {
2199 $item['body'] .= '🐟';
2202 $entry = self::entry($doc, $item, $owner, true);
2204 $doc->appendChild($entry);
2206 return trim($doc->saveXML());