3 * @file include/ostatus.php
7 use Friendica\Core\System;
8 use Friendica\Core\Config;
9 use Friendica\Network\Probe;
11 require_once 'include/Contact.php';
12 require_once 'include/threads.php';
13 require_once 'include/html2bbcode.php';
14 require_once 'include/bbcode.php';
15 require_once 'include/items.php';
16 require_once 'mod/share.php';
17 require_once 'include/enotify.php';
18 require_once 'include/socgraph.php';
19 require_once 'include/Photo.php';
20 require_once 'include/probe.php';
21 require_once 'include/follow.php';
22 require_once 'include/api.php';
23 require_once 'mod/proxy.php';
24 require_once 'include/xml.php';
25 require_once 'include/cache.php';
28 * @brief This class contain functions for the OStatus protocol
33 private static $itemlist;
36 * @brief Fetches author data
38 * @param object $xpath The xpath object
39 * @param object $context The xml context of the author details
40 * @param array $importer user record of the importing user
41 * @param array $contact Called by reference, will contain the fetched contact
42 * @param bool $onlyfetch Only fetch the header without updating the contact entries
44 * @return array Array of author related entries for the item
46 private static function fetchauthor($xpath, $context, $importer, &$contact, $onlyfetch) {
49 $author["author-link"] = $xpath->evaluate('atom:author/atom:uri/text()', $context)->item(0)->nodeValue;
50 $author["author-name"] = $xpath->evaluate('atom:author/atom:name/text()', $context)->item(0)->nodeValue;
51 $addr = $xpath->evaluate('atom:author/atom:email/text()', $context)->item(0)->nodeValue;
53 $aliaslink = $author["author-link"];
55 $alternate = $xpath->query("atom:author/atom:link[@rel='alternate']", $context)->item(0)->attributes;
56 if (is_object($alternate)) {
57 foreach ($alternate AS $attributes) {
58 if (($attributes->name == "href") && ($attributes->textContent != "")) {
59 $author["author-link"] = $attributes->textContent;
64 $author["contact-id"] = $contact["id"];
66 if ($author["author-link"] != "") {
67 if ($aliaslink == "") {
68 $aliaslink = $author["author-link"];
71 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `nurl` IN ('%s', '%s') AND `network` != '%s'",
72 intval($importer["uid"]), dbesc(normalise_link($author["author-link"])),
73 dbesc(normalise_link($aliaslink)), dbesc(NETWORK_STATUSNET));
75 if (dbm::is_result($r)) {
77 $author["contact-id"] = $r[0]["id"];
78 $author["author-link"] = $r[0]["url"];
80 } elseif ($addr != "") {
82 $contact = dba::fetch_first("SELECT * FROM `contact` WHERE `uid` = ? AND `addr` = ? AND `network` != ?",
83 $importer["uid"], $addr, NETWORK_STATUSNET);
85 if (dbm::is_result($contact)) {
86 $author["contact-id"] = $contact["id"];
87 $author["author-link"] = $contact["url"];
91 $avatarlist = array();
92 $avatars = $xpath->query("atom:author/atom:link[@rel='avatar']", $context);
93 foreach ($avatars AS $avatar) {
96 foreach ($avatar->attributes AS $attributes) {
97 if ($attributes->name == "href") {
98 $href = $attributes->textContent;
100 if ($attributes->name == "width") {
101 $width = $attributes->textContent;
105 $avatarlist[$width] = $href;
108 if (count($avatarlist) > 0) {
110 $author["author-avatar"] = Probe::fixAvatar(current($avatarlist), $author["author-link"]);
113 $displayname = $xpath->evaluate('atom:author/poco:displayName/text()', $context)->item(0)->nodeValue;
114 if ($displayname != "") {
115 $author["author-name"] = $displayname;
118 $author["owner-name"] = $author["author-name"];
119 $author["owner-link"] = $author["author-link"];
120 $author["owner-avatar"] = $author["author-avatar"];
122 // Only update the contacts if it is an OStatus contact
123 if ($r && !$onlyfetch && ($contact["network"] == NETWORK_OSTATUS)) {
125 // Update contact data
127 // This query doesn't seem to work
128 // $value = $xpath->query("atom:link[@rel='salmon']", $context)->item(0)->nodeValue;
130 // $contact["notify"] = $value;
132 // This query doesn't seem to work as well - I hate these queries
133 // $value = $xpath->query("atom:link[@rel='self' and @type='application/atom+xml']", $context)->item(0)->nodeValue;
135 // $contact["poll"] = $value;
137 $value = $xpath->evaluate('atom:author/atom:uri/text()', $context)->item(0)->nodeValue;
139 $contact["alias"] = $value;
141 $value = $xpath->evaluate('atom:author/poco:displayName/text()', $context)->item(0)->nodeValue;
143 $contact["name"] = $value;
145 $value = $xpath->evaluate('atom:author/poco:preferredUsername/text()', $context)->item(0)->nodeValue;
147 $contact["nick"] = $value;
149 $value = $xpath->evaluate('atom:author/poco:note/text()', $context)->item(0)->nodeValue;
151 $contact["about"] = html2bbcode($value);
153 $value = $xpath->evaluate('atom:author/poco:address/poco:formatted/text()', $context)->item(0)->nodeValue;
155 $contact["location"] = $value;
157 if (($contact["name"] != $r[0]["name"]) || ($contact["nick"] != $r[0]["nick"]) || ($contact["about"] != $r[0]["about"]) ||
158 ($contact["alias"] != $r[0]["alias"]) || ($contact["location"] != $r[0]["location"])) {
160 logger("Update contact data for contact ".$contact["id"], LOGGER_DEBUG);
162 q("UPDATE `contact` SET `name` = '%s', `nick` = '%s', `alias` = '%s', `about` = '%s', `location` = '%s', `name-date` = '%s' WHERE `id` = %d",
163 dbesc($contact["name"]), dbesc($contact["nick"]), dbesc($contact["alias"]),
164 dbesc($contact["about"]), dbesc($contact["location"]),
165 dbesc(datetime_convert()), intval($contact["id"]));
168 if (isset($author["author-avatar"]) && ($author["author-avatar"] != $r[0]['avatar'])) {
169 logger("Update profile picture for contact ".$contact["id"], LOGGER_DEBUG);
171 update_contact_avatar($author["author-avatar"], $importer["uid"], $contact["id"]);
174 // Ensure that we are having this contact (with uid=0)
175 $cid = get_contact($author["author-link"], 0);
178 // Update it with the current values
179 q("UPDATE `contact` SET `url` = '%s', `name` = '%s', `nick` = '%s', `alias` = '%s',
180 `about` = '%s', `location` = '%s',
181 `success_update` = '%s', `last-update` = '%s'
183 dbesc($author["author-link"]), dbesc($contact["name"]), dbesc($contact["nick"]),
184 dbesc($contact["alias"]), dbesc($contact["about"]), dbesc($contact["location"]),
185 dbesc(datetime_convert()), dbesc(datetime_convert()), intval($cid));
188 update_contact_avatar($author["author-avatar"], 0, $cid);
191 $contact["generation"] = 2;
192 $contact["hide"] = false; // OStatus contacts are never hidden
193 $contact["photo"] = $author["author-avatar"];
194 $gcid = update_gcontact($contact);
196 link_gcontact($gcid, $contact["uid"], $contact["id"]);
203 * @brief Fetches author data from a given XML string
205 * @param string $xml The XML
206 * @param array $importer user record of the importing user
208 * @return array Array of author related entries for the item
210 public static function salmon_author($xml, $importer) {
215 $doc = new DOMDocument();
216 @$doc->loadXML($xml);
218 $xpath = new DomXPath($doc);
219 $xpath->registerNamespace('atom', NAMESPACE_ATOM1);
220 $xpath->registerNamespace('thr', NAMESPACE_THREAD);
221 $xpath->registerNamespace('georss', NAMESPACE_GEORSS);
222 $xpath->registerNamespace('activity', NAMESPACE_ACTIVITY);
223 $xpath->registerNamespace('media', NAMESPACE_MEDIA);
224 $xpath->registerNamespace('poco', NAMESPACE_POCO);
225 $xpath->registerNamespace('ostatus', NAMESPACE_OSTATUS);
226 $xpath->registerNamespace('statusnet', NAMESPACE_STATUSNET);
228 $entries = $xpath->query('/atom:entry');
230 foreach ($entries AS $entry) {
232 $author = self::fetchauthor($xpath, $entry, $importer, $contact, true);
238 * @brief Read attributes from element
240 * @param object $element Element object
242 * @return array attributes
244 private static function read_attributes($element) {
245 $attribute = array();
247 foreach ($element->attributes AS $attributes) {
248 $attribute[$attributes->name] = $attributes->textContent;
255 * @brief Imports an XML string containing OStatus elements
257 * @param string $xml The XML
258 * @param array $importer user record of the importing user
259 * @param array $contact
260 * @param string $hub Called by reference, returns the fetched hub data
262 public static function import($xml, $importer, &$contact, &$hub) {
263 self::process($xml, $importer, $contact, $hub);
267 * @brief Internal feed processing
269 * @param string $xml The XML
270 * @param array $importer user record of the importing user
271 * @param array $contact
272 * @param string $hub Called by reference, returns the fetched hub data
273 * @param boolean $stored Is the post fresh imported or from the database?
274 * @param boolean $initialize Is it the leading post so that data has to be initialized?
276 * @return boolean Could the XML be processed?
278 private static function process($xml, $importer, &$contact, &$hub, $stored = false, $initialize = true) {
280 self::$itemlist = array();
283 logger("Import OStatus message", LOGGER_DEBUG);
288 $doc = new DOMDocument();
289 @$doc->loadXML($xml);
291 $xpath = new DomXPath($doc);
292 $xpath->registerNamespace('atom', NAMESPACE_ATOM1);
293 $xpath->registerNamespace('thr', NAMESPACE_THREAD);
294 $xpath->registerNamespace('georss', NAMESPACE_GEORSS);
295 $xpath->registerNamespace('activity', NAMESPACE_ACTIVITY);
296 $xpath->registerNamespace('media', NAMESPACE_MEDIA);
297 $xpath->registerNamespace('poco', NAMESPACE_POCO);
298 $xpath->registerNamespace('ostatus', NAMESPACE_OSTATUS);
299 $xpath->registerNamespace('statusnet', NAMESPACE_STATUSNET);
302 $hub_attributes = $xpath->query("/atom:feed/atom:link[@rel='hub']")->item(0)->attributes;
303 if (is_object($hub_attributes)) {
304 foreach ($hub_attributes AS $hub_attribute) {
305 if ($hub_attribute->name == "href") {
306 $hub = $hub_attribute->textContent;
307 logger("Found hub ".$hub, LOGGER_DEBUG);
313 $header["uid"] = $importer["uid"];
314 $header["network"] = NETWORK_OSTATUS;
315 $header["type"] = "remote";
317 $header["origin"] = 0;
318 $header["gravity"] = GRAVITY_PARENT;
320 $first_child = $doc->firstChild->tagName;
322 if ($first_child == "feed") {
323 $entries = $xpath->query('/atom:feed/atom:entry');
324 $header["protocol"] = PROTOCOL_OSTATUS_FEED;
326 $entries = $xpath->query('/atom:entry');
327 $header["protocol"] = PROTOCOL_OSTATUS_SALMON;
330 // Fetch the first author
331 $authordata = $xpath->query('//author')->item(0);
332 $author = self::fetchauthor($xpath, $authordata, $importer, $contact, $stored);
334 $entry = $xpath->query('/atom:entry');
335 $header["protocol"] = PROTOCOL_OSTATUS_SALMON;
337 // Reverse the order of the entries
338 $entrylist = array();
340 foreach ($entries AS $entry) {
341 $entrylist[] = $entry;
344 if (!$initialize && (count($entrylist) > 1)) {
348 foreach (array_reverse($entrylist) AS $entry) {
350 $authorelement = $xpath->query('/atom:entry/atom:author', $entry);
351 if ($authorelement->length > 0) {
352 $author = self::fetchauthor($xpath, $entry, $importer, $contact, $stored);
355 $value = $xpath->evaluate('atom:author/poco:preferredUsername/text()', $entry)->item(0)->nodeValue;
359 $nickname = $author["author-name"];
362 $item = array_merge($header, $author);
364 $item["verb"] = $xpath->query('activity:verb/text()', $entry)->item(0)->nodeValue;
367 if ($item["verb"] == "qvitter-delete-notice" || $item["verb"] == ACTIVITY_DELETE) {
368 // ignore "Delete" messages (by now)
369 logger("Ignore delete message ".print_r($item, true));
373 if ($item["verb"] == ACTIVITY_JOIN) {
374 // ignore "Join" messages
375 logger("Ignore join message ".print_r($item, true));
379 if ($item["verb"] == ACTIVITY_FOLLOW) {
380 new_follower($importer, $contact, $item, $nickname);
384 if ($item["verb"] == NAMESPACE_OSTATUS."/unfollow") {
385 lose_follower($importer, $contact, $item, $dummy);
389 if ($item["verb"] == NAMESPACE_OSTATUS."/unfavorite") {
390 // Ignore "Unfavorite" message
391 logger("Ignore unfavorite message ".print_r($item, true));
395 if ($item["verb"] == ACTIVITY_FAVORITE) {
396 $orig_uri = $xpath->query("activity:object/atom:id", $entry)->item(0)->nodeValue;
397 logger("Favorite ".$orig_uri." ".print_r($item, true));
399 $item["verb"] = ACTIVITY_LIKE;
400 $item["parent-uri"] = $orig_uri;
401 $item["gravity"] = GRAVITY_LIKE;
404 // http://activitystrea.ms/schema/1.0/rsvp-yes
405 if (!in_array($item["verb"], array(ACTIVITY_POST, ACTIVITY_LIKE, ACTIVITY_SHARE))) {
406 logger("Unhandled verb ".$item["verb"]." ".print_r($item, true));
409 $doc2 = new DOMDocument();
410 $doc2->loadXML($xml);
411 $doc2->preserveWhiteSpace = false;
412 $doc2->formatOutput = true;
413 $xml2 = $doc2->saveXML();
415 $item["source"] = $xml2;
417 self::processPost($xpath, $entry, $item, $importer);
419 if ($initialize && (count(self::$itemlist) > 0)) {
420 // We will import it everytime, when it is started by our contacts
421 $valid = !empty(self::$itemlist[0]['contact-id']);
423 // If not, then it depends on this setting
424 $valid = !Config::get('system','ostatus_full_threads');
428 // But we will only import complete threads
429 $valid = self::$itemlist[0]['uri'] == self::$itemlist[0]['parent-uri'];
433 // Never post a thread when the only interaction by our contact was a like
435 $verbs = array(ACTIVITY_POST, ACTIVITY_SHARE);
436 foreach (self::$itemlist AS $item) {
437 if (!empty($item['contact-id']) && in_array($item['verb'], $verbs)) {
444 $default_contact = 0;
445 $key = count(self::$itemlist);
446 for ($key = count(self::$itemlist) - 1; $key >= 0; $key--) {
447 if (empty(self::$itemlist[$key]['contact-id'])) {
448 self::$itemlist[$key]['contact-id'] = $default_contact;
450 $default_contact = $item['contact-id'];
453 foreach (self::$itemlist AS $item) {
454 $found = dba::exists('item', array('uid' => $importer["uid"], 'uri' => $item["uri"]));
456 logger("Item with uri ".$item["uri"]." for user ".$importer["uid"]." already exists.", LOGGER_DEBUG);
458 $ret = item_store($item);
459 logger('Item was stored with return value '.$ret);
463 self::$itemlist = array();
470 * @brief Processes the XML for a post
472 * @param object $xpath The xpath object
473 * @param object $entry The xml entry that is processed
474 * @param array $item The item array
475 * @param array $importer user record of the importing user
477 private static function processPost($xpath, $entry, &$item, $importer) {
478 $item["uri"] = $xpath->query('atom:id/text()', $entry)->item(0)->nodeValue;
479 $item["body"] = html2bbcode($xpath->query('atom:content/text()', $entry)->item(0)->nodeValue);
480 $item["object-type"] = $xpath->query('activity:object-type/text()', $entry)->item(0)->nodeValue;
481 if (($item["object-type"] == ACTIVITY_OBJ_BOOKMARK) || ($item["object-type"] == ACTIVITY_OBJ_EVENT)) {
482 $item["title"] = $xpath->query('atom:title/text()', $entry)->item(0)->nodeValue;
483 $item["body"] = $xpath->query('atom:summary/text()', $entry)->item(0)->nodeValue;
484 } elseif ($item["object-type"] == ACTIVITY_OBJ_QUESTION) {
485 $item["title"] = $xpath->query('atom:title/text()', $entry)->item(0)->nodeValue;
488 $item["created"] = $xpath->query('atom:published/text()', $entry)->item(0)->nodeValue;
489 $item["edited"] = $xpath->query('atom:updated/text()', $entry)->item(0)->nodeValue;
490 $conversation = $xpath->query('ostatus:conversation/text()', $entry)->item(0)->nodeValue;
491 $item['conversation-uri'] = $conversation;
493 $conv = $xpath->query('ostatus:conversation', $entry);
494 if (is_object($conv->item(0))) {
495 foreach ($conv->item(0)->attributes AS $attributes) {
496 if ($attributes->name == "ref") {
497 $item['conversation-uri'] = $attributes->textContent;
499 if ($attributes->name == "href") {
500 $item['conversation-href'] = $attributes->textContent;
505 if (empty($item['conversation-href']) && !empty($item['conversation-uri'])) {
506 $item['conversation-href'] = $item['conversation-uri'];
511 $inreplyto = $xpath->query('thr:in-reply-to', $entry);
512 if (is_object($inreplyto->item(0))) {
513 foreach ($inreplyto->item(0)->attributes AS $attributes) {
514 if ($attributes->name == "ref") {
515 $item["parent-uri"] = $attributes->textContent;
517 if ($attributes->name == "href") {
518 $related = $attributes->textContent;
523 $georsspoint = $xpath->query('georss:point', $entry);
524 if (!empty($georsspoint) && ($georsspoint->length > 0)) {
525 $item["coord"] = $georsspoint->item(0)->nodeValue;
528 $categories = $xpath->query('atom:category', $entry);
530 foreach ($categories AS $category) {
531 foreach ($category->attributes AS $attributes) {
532 if ($attributes->name == "term") {
533 $term = $attributes->textContent;
534 if (strlen($item["tag"])) {
537 $item["tag"] .= "#[url=".System::baseUrl()."/search?tag=".$term."]".$term."[/url]";
546 $links = $xpath->query('atom:link', $entry);
548 $link_data = self::processLinks($links, $item);
549 $self = $link_data['self'];
550 $add_body = $link_data['add_body'];
555 $notice_info = $xpath->query('statusnet:notice_info', $entry);
556 if ($notice_info && ($notice_info->length > 0)) {
557 foreach ($notice_info->item(0)->attributes AS $attributes) {
558 if ($attributes->name == "source") {
559 $item["app"] = strip_tags($attributes->textContent);
561 if ($attributes->name == "repeat_of") {
562 $repeat_of = $attributes->textContent;
566 // Is it a repeated post?
567 if (($repeat_of != "") || ($item["verb"] == ACTIVITY_SHARE)) {
568 $link_data = self::processRepeatedItem($xpath, $entry, $item, $importer);
569 if (!empty($link_data['add_body'])) {
570 $add_body .= $link_data['add_body'];
574 $item["body"] .= $add_body;
576 // Only add additional data when there is no picture in the post
577 if (!strstr($item["body"],'[/img]')) {
578 $item["body"] = add_page_info_to_body($item["body"]);
581 // Mastodon Content Warning
582 if (($item["verb"] == ACTIVITY_POST) && $xpath->evaluate('boolean(atom:summary)', $entry)) {
583 $clear_text = $xpath->query('atom:summary/text()', $entry)->item(0)->nodeValue;
585 $item["body"] = html2bbcode($clear_text) . '[spoiler]' . $item["body"] . '[/spoiler]';
588 if (isset($item["parent-uri"]) && ($related != '')) {
589 self::FetchRelated($related, $item["parent-uri"], $importer);
590 $item["type"] = 'remote-comment';
591 $item["gravity"] = GRAVITY_COMMENT;
593 $item["parent-uri"] = $item["uri"];
596 if ($item['author-link'] != '') {
597 $item = store_conversation($item);
600 self::$itemlist[] = $item;
604 * @brief Fetch related posts and processes them
606 * @param string $related The link to the related item
607 * @param string $related_uri The related item in "uri" format
608 * @param array $importer user record of the importing user
610 private static function fetchRelated($related, $related_uri, $importer) {
611 $condition = array('`item-uri` = ? AND `protocol` IN (?, ?)', $related_uri, PROTOCOL_DFRN, PROTOCOL_OSTATUS_SALMON);
612 $conversation = dba::select('conversation', array('source', 'protocol'), $condition, array('limit' => 1));
613 if (dbm::is_result($conversation)) {
615 $xml = $conversation['source'];
616 if (self::process($xml, $importer, $contact, $hub, $stored, false)) {
619 if ($conversation['protocol'] == PROTOCOL_OSTATUS_SALMON) {
620 dba::delete('conversation', array('item-uri' => $related_uri));
625 $related_data = z_fetch_url($related);
627 if (!$related_data['success']) {
633 if (stristr($related_data['header'], 'Content-Type: application/atom+xml')) {
634 $xml = $related_data['body'];
638 $doc = new DOMDocument();
639 if (!@$doc->loadHTML($related_data['body'])) {
642 $xpath = new DomXPath($doc);
644 $links = $xpath->query('//link');
646 foreach ($links AS $link) {
647 $attribute = self::read_attributes($link);
648 if (($attribute['rel'] == 'alternate') && ($attribute['type'] == 'application/atom+xml')) {
649 $related_atom = z_fetch_url($attribute['href']);
651 if ($related_atom['success']) {
652 $xml = $related_atom['body'];
659 // Workaround for older GNU Social servers
660 if (($xml == '') && strstr($related, '/notice/')) {
661 $related_atom = z_fetch_url(str_replace('/notice/', '/api/statuses/show/', $related).',atom');
663 if ($related_atom['success']) {
664 $xml = $related_atom['body'];
669 self::process($xml, $importer, $contact, $hub, $stored, false);
675 * @brief Processes the XML for a repeated post
677 * @param object $xpath The xpath object
678 * @param object $entry The xml entry that is processed
679 * @param array $item The item array
680 * @param array $importer user record of the importing user
682 * @return array with data from links
684 private static function processRepeatedItem($xpath, $entry, &$item, $importer) {
685 $activityobjects = $xpath->query('activity:object', $entry)->item(0);
687 if (!is_object($activityobjects)) {
691 $link_data = array();
693 $orig_uri = $xpath->query('atom:id/text()', $activityobjects)->item(0)->nodeValue;
695 $links = $xpath->query("atom:link", $activityobjects);
697 $link_data = self::processLinks($links, $item);
700 $orig_body = $xpath->query('atom:content/text()', $activityobjects)->item(0)->nodeValue;
701 $orig_created = $xpath->query('atom:published/text()', $activityobjects)->item(0)->nodeValue;
702 $orig_edited = $xpath->query('atom:updated/text()', $activityobjects)->item(0)->nodeValue;
704 $orig_contact = $contact;
705 $orig_author = self::fetchauthor($xpath, $activityobjects, $importer, $orig_contact, false);
707 $item["author-name"] = $orig_author["author-name"];
708 $item["author-link"] = $orig_author["author-link"];
709 $item["author-avatar"] = $orig_author["author-avatar"];
711 $item["body"] = html2bbcode($orig_body);
712 $item["created"] = $orig_created;
713 $item["edited"] = $orig_edited;
715 $item["uri"] = $orig_uri;
717 $item["verb"] = $xpath->query('activity:verb/text()', $activityobjects)->item(0)->nodeValue;
719 $item["object-type"] = $xpath->query('activity:object-type/text()', $activityobjects)->item(0)->nodeValue;
721 $inreplyto = $xpath->query('thr:in-reply-to', $activityobjects);
722 if (is_object($inreplyto->item(0))) {
723 foreach ($inreplyto->item(0)->attributes AS $attributes) {
724 if ($attributes->name == "ref") {
725 $item["parent-uri"] = $attributes->textContent;
734 * @brief Processes links in the XML
736 * @param object $links The xml data that contain links
737 * @param array $item The item array
739 * @return array with data from the links
741 private static function processLinks($links, &$item) {
742 $link_data = array('add_body' => '', 'self' => '');
744 foreach ($links AS $link) {
745 $attribute = self::read_attributes($link);
747 if (($attribute['rel'] != "") && ($attribute['href'] != "")) {
748 switch ($attribute['rel']) {
750 $item["plink"] = $attribute['href'];
751 if (($item["object-type"] == ACTIVITY_OBJ_QUESTION) ||
752 ($item["object-type"] == ACTIVITY_OBJ_EVENT)) {
753 $item["body"] .= add_page_info($attribute['href']);
756 case "ostatus:conversation":
757 $link_data['conversation'] = $attribute['href'];
758 $item['conversation-href'] = $link_data['conversation'];
759 if (!isset($item['conversation-uri'])) {
760 $item['conversation-uri'] = $item['conversation-href'];
764 $filetype = strtolower(substr($attribute['type'], 0, strpos($attribute['type'],'/')));
765 if ($filetype == 'image') {
766 $link_data['add_body'] .= "\n[img]".$attribute['href'].'[/img]';
768 if (strlen($item["attach"])) {
769 $item["attach"] .= ',';
771 if (!isset($attribute['length'])) {
772 $attribute['length'] = "0";
774 $item["attach"] .= '[attach]href="'.$attribute['href'].'" length="'.$attribute['length'].'" type="'.$attribute['type'].'" title="'.$attribute['title'].'"[/attach]';
778 if ($item["object-type"] != ACTIVITY_OBJ_BOOKMARK) {
779 if (!isset($item["parent-uri"])) {
780 $item["parent-uri"] = $attribute['href'];
782 $link_data['related'] = $attribute['href'];
784 $item["body"] .= add_page_info($attribute['href']);
788 if ($item["plink"] == '') {
789 $item["plink"] = $attribute['href'];
791 $link_data['self'] = $attribute['href'];
800 * @brief Checks if the current post is a reshare
802 * @param array $item The item array of thw post
804 * @return string The guid if the post is a reshare
806 private static function get_reshared_guid($item) {
807 $body = trim($item["body"]);
809 // Skip if it isn't a pure repeated messages
810 // Does it start with a share?
811 if (strpos($body, "[share") > 0)
814 // Does it end with a share?
815 if (strlen($body) > (strrpos($body, "[/share]") + 8))
818 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$1",$body);
819 // Skip if there is no shared message in there
820 if ($body == $attributes)
824 preg_match("/guid='(.*?)'/ism", $attributes, $matches);
825 if ($matches[1] != "")
828 preg_match('/guid="(.*?)"/ism', $attributes, $matches);
829 if ($matches[1] != "")
836 * @brief Cleans the body of a post if it contains picture links
838 * @param string $body The body
840 * @return string The cleaned body
842 private static function format_picture_post($body) {
843 $siteinfo = get_attached_data($body);
845 if (($siteinfo["type"] == "photo")) {
846 if (isset($siteinfo["preview"]))
847 $preview = $siteinfo["preview"];
849 $preview = $siteinfo["image"];
851 // Is it a remote picture? Then make a smaller preview here
852 $preview = proxy_url($preview, false, PROXY_SIZE_SMALL);
854 // Is it a local picture? Then make it smaller here
855 $preview = str_replace(array("-0.jpg", "-0.png"), array("-2.jpg", "-2.png"), $preview);
856 $preview = str_replace(array("-1.jpg", "-1.png"), array("-2.jpg", "-2.png"), $preview);
858 if (isset($siteinfo["url"]))
859 $url = $siteinfo["url"];
861 $url = $siteinfo["image"];
863 $body = trim($siteinfo["text"])." [url]".$url."[/url]\n[img]".$preview."[/img]";
870 * @brief Adds the header elements to the XML document
872 * @param object $doc XML document
873 * @param array $owner Contact data of the poster
875 * @return object header root element
877 private static function add_header($doc, $owner) {
881 $root = $doc->createElementNS(NAMESPACE_ATOM1, 'feed');
882 $doc->appendChild($root);
884 $root->setAttribute("xmlns:thr", NAMESPACE_THREAD);
885 $root->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
886 $root->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
887 $root->setAttribute("xmlns:media", NAMESPACE_MEDIA);
888 $root->setAttribute("xmlns:poco", NAMESPACE_POCO);
889 $root->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
890 $root->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
891 $root->setAttribute("xmlns:mastodon", NAMESPACE_MASTODON);
893 $attributes = array("uri" => "https://friendi.ca", "version" => FRIENDICA_VERSION."-".DB_UPDATE_VERSION);
894 xml::add_element($doc, $root, "generator", FRIENDICA_PLATFORM, $attributes);
895 xml::add_element($doc, $root, "id", System::baseUrl()."/profile/".$owner["nick"]);
896 xml::add_element($doc, $root, "title", sprintf("%s timeline", $owner["name"]));
897 xml::add_element($doc, $root, "subtitle", sprintf("Updates from %s on %s", $owner["name"], $a->config["sitename"]));
898 xml::add_element($doc, $root, "logo", $owner["photo"]);
899 xml::add_element($doc, $root, "updated", datetime_convert("UTC", "UTC", "now", ATOM_TIME));
901 $author = self::add_author($doc, $owner);
902 $root->appendChild($author);
904 $attributes = array("href" => $owner["url"], "rel" => "alternate", "type" => "text/html");
905 xml::add_element($doc, $root, "link", "", $attributes);
907 /// @TODO We have to find out what this is
908 /// $attributes = array("href" => System::baseUrl()."/sup",
909 /// "rel" => "http://api.friendfeed.com/2008/03#sup",
910 /// "type" => "application/json");
911 /// xml::add_element($doc, $root, "link", "", $attributes);
913 self::hublinks($doc, $root, $owner["nick"]);
915 $attributes = array("href" => System::baseUrl()."/salmon/".$owner["nick"], "rel" => "salmon");
916 xml::add_element($doc, $root, "link", "", $attributes);
918 $attributes = array("href" => System::baseUrl()."/salmon/".$owner["nick"], "rel" => "http://salmon-protocol.org/ns/salmon-replies");
919 xml::add_element($doc, $root, "link", "", $attributes);
921 $attributes = array("href" => System::baseUrl()."/salmon/".$owner["nick"], "rel" => "http://salmon-protocol.org/ns/salmon-mention");
922 xml::add_element($doc, $root, "link", "", $attributes);
924 $attributes = array("href" => System::baseUrl()."/api/statuses/user_timeline/".$owner["nick"].".atom",
925 "rel" => "self", "type" => "application/atom+xml");
926 xml::add_element($doc, $root, "link", "", $attributes);
932 * @brief Add the link to the push hubs to the XML document
934 * @param object $doc XML document
935 * @param object $root XML root element where the hub links are added
937 public static function hublinks($doc, $root, $nick) {
938 $h = System::baseUrl() . '/pubsubhubbub/'.$nick;
939 xml::add_element($doc, $root, "link", "", array("href" => $h, "rel" => "hub"));
943 * @brief Adds attachement data to the XML document
945 * @param object $doc XML document
946 * @param object $root XML root element where the hub links are added
947 * @param array $item Data of the item that is to be posted
949 private static function get_attachment($doc, $root, $item) {
951 $siteinfo = get_attached_data($item["body"]);
953 switch ($siteinfo["type"]) {
955 $imgdata = get_photo_info($siteinfo["image"]);
956 $attributes = array("rel" => "enclosure",
957 "href" => $siteinfo["image"],
958 "type" => $imgdata["mime"],
959 "length" => intval($imgdata["size"]));
960 xml::add_element($doc, $root, "link", "", $attributes);
963 $attributes = array("rel" => "enclosure",
964 "href" => $siteinfo["url"],
965 "type" => "text/html; charset=UTF-8",
967 "title" => $siteinfo["title"]);
968 xml::add_element($doc, $root, "link", "", $attributes);
974 if (!Config::get('system', 'ostatus_not_attach_preview') && ($siteinfo["type"] != "photo") && isset($siteinfo["image"])) {
975 $imgdata = get_photo_info($siteinfo["image"]);
976 $attributes = array("rel" => "enclosure",
977 "href" => $siteinfo["image"],
978 "type" => $imgdata["mime"],
979 "length" => intval($imgdata["size"]));
981 xml::add_element($doc, $root, "link", "", $attributes);
984 $arr = explode('[/attach],', $item['attach']);
986 foreach ($arr as $r) {
988 $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"|', $r, $matches);
990 $attributes = array("rel" => "enclosure",
991 "href" => $matches[1],
992 "type" => $matches[3]);
994 if (intval($matches[2])) {
995 $attributes["length"] = intval($matches[2]);
997 if (trim($matches[4]) != "") {
998 $attributes["title"] = trim($matches[4]);
1000 xml::add_element($doc, $root, "link", "", $attributes);
1007 * @brief Adds the author element to the XML document
1009 * @param object $doc XML document
1010 * @param array $owner Contact data of the poster
1012 * @return object author element
1014 private static function add_author($doc, $owner) {
1016 $r = q("SELECT `homepage`, `publish` FROM `profile` WHERE `uid` = %d AND `is-default` LIMIT 1", intval($owner["uid"]));
1017 if (dbm::is_result($r)) {
1020 $author = $doc->createElement("author");
1021 xml::add_element($doc, $author, "id", $owner["url"]);
1022 xml::add_element($doc, $author, "activity:object-type", ACTIVITY_OBJ_PERSON);
1023 xml::add_element($doc, $author, "uri", $owner["url"]);
1024 xml::add_element($doc, $author, "name", $owner["nick"]);
1025 xml::add_element($doc, $author, "email", $owner["addr"]);
1026 xml::add_element($doc, $author, "summary", bbcode($owner["about"], false, false, 7));
1028 $attributes = array("rel" => "alternate", "type" => "text/html", "href" => $owner["url"]);
1029 xml::add_element($doc, $author, "link", "", $attributes);
1031 $attributes = array(
1033 "type" => "image/jpeg", // To-Do?
1034 "media:width" => 175,
1035 "media:height" => 175,
1036 "href" => $owner["photo"]);
1037 xml::add_element($doc, $author, "link", "", $attributes);
1039 if (isset($owner["thumb"])) {
1040 $attributes = array(
1042 "type" => "image/jpeg", // To-Do?
1043 "media:width" => 80,
1044 "media:height" => 80,
1045 "href" => $owner["thumb"]);
1046 xml::add_element($doc, $author, "link", "", $attributes);
1049 xml::add_element($doc, $author, "poco:preferredUsername", $owner["nick"]);
1050 xml::add_element($doc, $author, "poco:displayName", $owner["name"]);
1051 xml::add_element($doc, $author, "poco:note", bbcode($owner["about"], false, false, 7));
1053 if (trim($owner["location"]) != "") {
1054 $element = $doc->createElement("poco:address");
1055 xml::add_element($doc, $element, "poco:formatted", $owner["location"]);
1056 $author->appendChild($element);
1059 if (trim($profile["homepage"]) != "") {
1060 $urls = $doc->createElement("poco:urls");
1061 xml::add_element($doc, $urls, "poco:type", "homepage");
1062 xml::add_element($doc, $urls, "poco:value", $profile["homepage"]);
1063 xml::add_element($doc, $urls, "poco:primary", "true");
1064 $author->appendChild($urls);
1067 if (count($profile)) {
1068 xml::add_element($doc, $author, "followers", "", array("url" => System::baseUrl()."/viewcontacts/".$owner["nick"]));
1069 xml::add_element($doc, $author, "statusnet:profile_info", "", array("local_id" => $owner["uid"]));
1072 if ($profile["publish"]) {
1073 xml::add_element($doc, $author, "mastodon:scope", "public");
1079 * @TODO Picture attachments should look like this:
1080 * <a href="https://status.pirati.ca/attachment/572819" title="https://status.pirati.ca/file/heluecht-20151202T222602-rd3u49p.gif"
1081 * class="attachment thumbnail" id="attachment-572819" rel="nofollow external">https://status.pirati.ca/attachment/572819</a>
1086 * @brief Returns the given activity if present - otherwise returns the "post" activity
1088 * @param array $item Data of the item that is to be posted
1090 * @return string activity
1092 private static function construct_verb($item) {
1094 return $item['verb'];
1095 return ACTIVITY_POST;
1099 * @brief Returns the given object type if present - otherwise returns the "note" object type
1101 * @param array $item Data of the item that is to be posted
1103 * @return string Object type
1105 private static function construct_objecttype($item) {
1106 if (in_array($item['object-type'], array(ACTIVITY_OBJ_NOTE, ACTIVITY_OBJ_COMMENT)))
1107 return $item['object-type'];
1108 return ACTIVITY_OBJ_NOTE;
1112 * @brief Adds an entry element to the XML document
1114 * @param object $doc XML document
1115 * @param array $item Data of the item that is to be posted
1116 * @param array $owner Contact data of the poster
1117 * @param bool $toplevel
1119 * @return object Entry element
1121 private static function entry($doc, $item, $owner, $toplevel = false) {
1122 $repeated_guid = self::get_reshared_guid($item);
1123 if ($repeated_guid != "")
1124 $xml = self::reshare_entry($doc, $item, $owner, $repeated_guid, $toplevel);
1129 if ($item["verb"] == ACTIVITY_LIKE) {
1130 return self::like_entry($doc, $item, $owner, $toplevel);
1131 } elseif (in_array($item["verb"], array(ACTIVITY_FOLLOW, NAMESPACE_OSTATUS."/unfollow"))) {
1132 return self::follow_entry($doc, $item, $owner, $toplevel);
1134 return self::note_entry($doc, $item, $owner, $toplevel);
1139 * @brief Adds a source entry to the XML document
1141 * @param object $doc XML document
1142 * @param array $contact Array of the contact that is added
1144 * @return object Source element
1146 private static function source_entry($doc, $contact) {
1147 $source = $doc->createElement("source");
1148 xml::add_element($doc, $source, "id", $contact["poll"]);
1149 xml::add_element($doc, $source, "title", $contact["name"]);
1150 xml::add_element($doc, $source, "link", "", array("rel" => "alternate",
1151 "type" => "text/html",
1152 "href" => $contact["alias"]));
1153 xml::add_element($doc, $source, "link", "", array("rel" => "self",
1154 "type" => "application/atom+xml",
1155 "href" => $contact["poll"]));
1156 xml::add_element($doc, $source, "icon", $contact["photo"]);
1157 xml::add_element($doc, $source, "updated", datetime_convert("UTC","UTC",$contact["success_update"]."+00:00",ATOM_TIME));
1163 * @brief Fetches contact data from the contact or the gcontact table
1165 * @param string $url URL of the contact
1166 * @param array $owner Contact data of the poster
1168 * @return array Contact array
1170 private static function contact_entry($url, $owner) {
1172 $r = q("SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` IN (0, %d) ORDER BY `uid` DESC LIMIT 1",
1173 dbesc(normalise_link($url)), intval($owner["uid"]));
1174 if (dbm::is_result($r)) {
1176 $contact["uid"] = -1;
1179 if (!dbm::is_result($r)) {
1180 $r = q("SELECT * FROM `gcontact` WHERE `nurl` = '%s' LIMIT 1",
1181 dbesc(normalise_link($url)));
1182 if (dbm::is_result($r)) {
1184 $contact["uid"] = -1;
1185 $contact["success_update"] = $contact["updated"];
1189 if (!dbm::is_result($r))
1192 if (!isset($contact["poll"])) {
1193 $data = probe_url($url);
1194 $contact["poll"] = $data["poll"];
1196 if (!$contact["alias"])
1197 $contact["alias"] = $data["alias"];
1200 if (!isset($contact["alias"]))
1201 $contact["alias"] = $contact["url"];
1207 * @brief Adds an entry element with reshared content
1209 * @param object $doc XML document
1210 * @param array $item Data of the item that is to be posted
1211 * @param array $owner Contact data of the poster
1212 * @param $repeated_guid
1213 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1215 * @return object Entry element
1217 private static function reshare_entry($doc, $item, $owner, $repeated_guid, $toplevel) {
1219 if (($item["id"] != $item["parent"]) && (normalise_link($item["author-link"]) != normalise_link($owner["url"]))) {
1220 logger("OStatus entry is from author ".$owner["url"]." - not from ".$item["author-link"].". Quitting.", LOGGER_DEBUG);
1223 $title = self::entry_header($doc, $entry, $owner, $toplevel);
1225 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' AND NOT `private` AND `network` IN ('%s', '%s', '%s') LIMIT 1",
1226 intval($owner["uid"]), dbesc($repeated_guid),
1227 dbesc(NETWORK_DFRN), dbesc(NETWORK_DIASPORA), dbesc(NETWORK_OSTATUS));
1228 if (dbm::is_result($r)) {
1229 $repeated_item = $r[0];
1233 $contact = self::contact_entry($repeated_item['author-link'], $owner);
1235 $parent_item = (($item['thr-parent']) ? $item['thr-parent'] : $item['parent-uri']);
1237 $title = $owner["nick"]." repeated a notice by ".$contact["nick"];
1239 self::entry_content($doc, $entry, $item, $owner, $title, ACTIVITY_SHARE, false);
1241 $as_object = $doc->createElement("activity:object");
1243 xml::add_element($doc, $as_object, "activity:object-type", NAMESPACE_ACTIVITY_SCHEMA."activity");
1245 self::entry_content($doc, $as_object, $repeated_item, $owner, "", "", false);
1247 $author = self::add_author($doc, $contact);
1248 $as_object->appendChild($author);
1250 $as_object2 = $doc->createElement("activity:object");
1252 xml::add_element($doc, $as_object2, "activity:object-type", self::construct_objecttype($repeated_item));
1254 $title = sprintf("New comment by %s", $contact["nick"]);
1256 self::entry_content($doc, $as_object2, $repeated_item, $owner, $title);
1258 $as_object->appendChild($as_object2);
1260 self::entry_footer($doc, $as_object, $item, $owner, false);
1262 $source = self::source_entry($doc, $contact);
1264 $as_object->appendChild($source);
1266 $entry->appendChild($as_object);
1268 self::entry_footer($doc, $entry, $item, $owner);
1274 * @brief Adds an entry element with a "like"
1276 * @param object $doc XML document
1277 * @param array $item Data of the item that is to be posted
1278 * @param array $owner Contact data of the poster
1279 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1281 * @return object Entry element with "like"
1283 private static function like_entry($doc, $item, $owner, $toplevel) {
1285 if (($item["id"] != $item["parent"]) && (normalise_link($item["author-link"]) != normalise_link($owner["url"]))) {
1286 logger("OStatus entry is from author ".$owner["url"]." - not from ".$item["author-link"].". Quitting.", LOGGER_DEBUG);
1289 $title = self::entry_header($doc, $entry, $owner, $toplevel);
1291 $verb = NAMESPACE_ACTIVITY_SCHEMA."favorite";
1292 self::entry_content($doc, $entry, $item, $owner, "Favorite", $verb, false);
1294 $as_object = $doc->createElement("activity:object");
1296 $parent = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d",
1297 dbesc($item["thr-parent"]), intval($item["uid"]));
1298 $parent_item = (($item['thr-parent']) ? $item['thr-parent'] : $item['parent-uri']);
1300 xml::add_element($doc, $as_object, "activity:object-type", self::construct_objecttype($parent[0]));
1302 self::entry_content($doc, $as_object, $parent[0], $owner, "New entry");
1304 $entry->appendChild($as_object);
1306 self::entry_footer($doc, $entry, $item, $owner);
1312 * @brief Adds the person object element to the XML document
1314 * @param object $doc XML document
1315 * @param array $owner Contact data of the poster
1316 * @param array $contact Contact data of the target
1318 * @return object author element
1320 private static function add_person_object($doc, $owner, $contact) {
1322 $object = $doc->createElement("activity:object");
1323 xml::add_element($doc, $object, "activity:object-type", ACTIVITY_OBJ_PERSON);
1325 if ($contact['network'] == NETWORK_PHANTOM) {
1326 xml::add_element($doc, $object, "id", $contact['url']);
1330 xml::add_element($doc, $object, "id", $contact["alias"]);
1331 xml::add_element($doc, $object, "title", $contact["nick"]);
1333 $attributes = array("rel" => "alternate", "type" => "text/html", "href" => $contact["url"]);
1334 xml::add_element($doc, $object, "link", "", $attributes);
1336 $attributes = array(
1338 "type" => "image/jpeg", // To-Do?
1339 "media:width" => 175,
1340 "media:height" => 175,
1341 "href" => $contact["photo"]);
1342 xml::add_element($doc, $object, "link", "", $attributes);
1344 xml::add_element($doc, $object, "poco:preferredUsername", $contact["nick"]);
1345 xml::add_element($doc, $object, "poco:displayName", $contact["name"]);
1347 if (trim($contact["location"]) != "") {
1348 $element = $doc->createElement("poco:address");
1349 xml::add_element($doc, $element, "poco:formatted", $contact["location"]);
1350 $object->appendChild($element);
1357 * @brief Adds a follow/unfollow entry element
1359 * @param object $doc XML document
1360 * @param array $item Data of the follow/unfollow message
1361 * @param array $owner Contact data of the poster
1362 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1364 * @return object Entry element
1366 private static function follow_entry($doc, $item, $owner, $toplevel) {
1368 $item["id"] = $item["parent"] = 0;
1369 $item["created"] = $item["edited"] = date("c");
1370 $item["private"] = true;
1372 $contact = Probe::uri($item['follow']);
1374 if ($contact['alias'] == '') {
1375 $contact['alias'] = $contact["url"];
1377 $item['follow'] = $contact['alias'];
1380 $r = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `nurl` = '%s'",
1381 intval($owner['uid']), dbesc(normalise_link($contact["url"])));
1383 if (dbm::is_result($r)) {
1384 $connect_id = $r[0]['id'];
1389 if ($item['verb'] == ACTIVITY_FOLLOW) {
1390 $message = t('%s is now following %s.');
1391 $title = t('following');
1392 $action = "subscription";
1394 $message = t('%s stopped following %s.');
1395 $title = t('stopped following');
1396 $action = "unfollow";
1399 $item["uri"] = $item['parent-uri'] = $item['thr-parent'] =
1400 'tag:'.get_app()->get_hostname().
1401 ','.date('Y-m-d').':'.$action.':'.$owner['uid'].
1402 ':person:'.$connect_id.':'.$item['created'];
1404 $item["body"] = sprintf($message, $owner["nick"], $contact["nick"]);
1406 self::entry_header($doc, $entry, $owner, $toplevel);
1408 self::entry_content($doc, $entry, $item, $owner, $title);
1410 $object = self::add_person_object($doc, $owner, $contact);
1411 $entry->appendChild($object);
1413 self::entry_footer($doc, $entry, $item, $owner);
1419 * @brief Adds a regular entry element
1421 * @param object $doc XML document
1422 * @param array $item Data of the item that is to be posted
1423 * @param array $owner Contact data of the poster
1424 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1426 * @return object Entry element
1428 private static function note_entry($doc, $item, $owner, $toplevel) {
1430 if (($item["id"] != $item["parent"]) && (normalise_link($item["author-link"]) != normalise_link($owner["url"]))) {
1431 logger("OStatus entry is from author ".$owner["url"]." - not from ".$item["author-link"].". Quitting.", LOGGER_DEBUG);
1434 $title = self::entry_header($doc, $entry, $owner, $toplevel);
1436 xml::add_element($doc, $entry, "activity:object-type", ACTIVITY_OBJ_NOTE);
1438 self::entry_content($doc, $entry, $item, $owner, $title);
1440 self::entry_footer($doc, $entry, $item, $owner);
1446 * @brief Adds a header element to the XML document
1448 * @param object $doc XML document
1449 * @param object $entry The entry element where the elements are added
1450 * @param array $owner Contact data of the poster
1451 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1453 * @return string The title for the element
1455 private static function entry_header($doc, &$entry, $owner, $toplevel) {
1456 /// @todo Check if this title stuff is really needed (I guess not)
1458 $entry = $doc->createElement("entry");
1459 $title = sprintf("New note by %s", $owner["nick"]);
1461 $entry = $doc->createElementNS(NAMESPACE_ATOM1, "entry");
1463 $entry->setAttribute("xmlns:thr", NAMESPACE_THREAD);
1464 $entry->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
1465 $entry->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
1466 $entry->setAttribute("xmlns:media", NAMESPACE_MEDIA);
1467 $entry->setAttribute("xmlns:poco", NAMESPACE_POCO);
1468 $entry->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
1469 $entry->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
1470 $entry->setAttribute("xmlns:mastodon", NAMESPACE_MASTODON);
1472 $author = self::add_author($doc, $owner);
1473 $entry->appendChild($author);
1475 $title = sprintf("New comment by %s", $owner["nick"]);
1481 * @brief Adds elements to the XML document
1483 * @param object $doc XML document
1484 * @param object $entry Entry element where the content is added
1485 * @param array $item Data of the item that is to be posted
1486 * @param array $owner Contact data of the poster
1487 * @param string $title Title for the post
1488 * @param string $verb The activity verb
1489 * @param bool $complete Add the "status_net" element?
1491 private static function entry_content($doc, $entry, $item, $owner, $title, $verb = "", $complete = true) {
1494 $verb = self::construct_verb($item);
1496 xml::add_element($doc, $entry, "id", $item["uri"]);
1497 xml::add_element($doc, $entry, "title", $title);
1499 $body = self::format_picture_post($item['body']);
1501 if ($item['title'] != "")
1502 $body = "[b]".$item['title']."[/b]\n\n".$body;
1504 $body = bbcode($body, false, false, 7);
1506 xml::add_element($doc, $entry, "content", $body, array("type" => "html"));
1508 xml::add_element($doc, $entry, "link", "", array("rel" => "alternate", "type" => "text/html",
1509 "href" => System::baseUrl()."/display/".$item["guid"]));
1511 if ($complete && ($item["id"] > 0))
1512 xml::add_element($doc, $entry, "status_net", "", array("notice_id" => $item["id"]));
1514 xml::add_element($doc, $entry, "activity:verb", $verb);
1516 xml::add_element($doc, $entry, "published", datetime_convert("UTC","UTC",$item["created"]."+00:00",ATOM_TIME));
1517 xml::add_element($doc, $entry, "updated", datetime_convert("UTC","UTC",$item["edited"]."+00:00",ATOM_TIME));
1521 * @brief Adds the elements at the foot of an entry to the XML document
1523 * @param object $doc XML document
1524 * @param object $entry The entry element where the elements are added
1525 * @param array $item Data of the item that is to be posted
1526 * @param array $owner Contact data of the poster
1529 private static function entry_footer($doc, $entry, $item, $owner, $complete = true) {
1531 $mentioned = array();
1533 if (($item['parent'] != $item['id']) || ($item['parent-uri'] !== $item['uri']) || (($item['thr-parent'] !== '') && ($item['thr-parent'] !== $item['uri']))) {
1534 $parent = q("SELECT `guid`, `author-link`, `owner-link` FROM `item` WHERE `id` = %d", intval($item["parent"]));
1535 $parent_item = (($item['thr-parent']) ? $item['thr-parent'] : $item['parent-uri']);
1537 $thrparent = q("SELECT `guid`, `author-link`, `owner-link`, `plink` FROM `item` WHERE `uid` = %d AND `uri` = '%s'",
1538 intval($owner["uid"]),
1539 dbesc($parent_item));
1541 $mentioned[$thrparent[0]["author-link"]] = $thrparent[0]["author-link"];
1542 $mentioned[$thrparent[0]["owner-link"]] = $thrparent[0]["owner-link"];
1543 $parent_plink = $thrparent[0]["plink"];
1545 $mentioned[$parent[0]["author-link"]] = $parent[0]["author-link"];
1546 $mentioned[$parent[0]["owner-link"]] = $parent[0]["owner-link"];
1547 $parent_plink = System::baseUrl()."/display/".$parent[0]["guid"];
1550 $attributes = array(
1551 "ref" => $parent_item,
1552 "href" => $parent_plink);
1553 xml::add_element($doc, $entry, "thr:in-reply-to", "", $attributes);
1555 $attributes = array(
1557 "href" => $parent_plink);
1558 xml::add_element($doc, $entry, "link", "", $attributes);
1561 if (intval($item["parent"]) > 0) {
1562 $conversation_href = System::baseUrl()."/display/".$owner["nick"]."/".$item["parent"];
1563 $conversation_uri = $conversation_href;
1565 if (isset($parent_item)) {
1566 $r = dba::fetch_first("SELECT `conversation-uri`, `conversation-href` FROM `conversation` WHERE `item-uri` = ?", $parent_item);
1567 if (dbm::is_result($r)) {
1568 if ($r['conversation-uri'] != '') {
1569 $conversation_uri = $r['conversation-uri'];
1571 if ($r['conversation-href'] != '') {
1572 $conversation_href = $r['conversation-href'];
1577 xml::add_element($doc, $entry, "link", "", array("rel" => "ostatus:conversation", "href" => $conversation_href));
1579 $attributes = array(
1580 "href" => $conversation_href,
1581 "local_id" => $item["parent"],
1582 "ref" => $conversation_uri);
1584 xml::add_element($doc, $entry, "ostatus:conversation", $conversation_uri, $attributes);
1587 $tags = item_getfeedtags($item);
1590 foreach ($tags as $t)
1592 $mentioned[$t[1]] = $t[1];
1594 // Make sure that mentions are accepted (GNU Social has problems with mixing HTTP and HTTPS)
1595 $newmentions = array();
1596 foreach ($mentioned AS $mention) {
1597 $newmentions[str_replace("http://", "https://", $mention)] = str_replace("http://", "https://", $mention);
1598 $newmentions[str_replace("https://", "http://", $mention)] = str_replace("https://", "http://", $mention);
1600 $mentioned = $newmentions;
1602 foreach ($mentioned AS $mention) {
1603 $r = q("SELECT `forum`, `prv` FROM `contact` WHERE `uid` = %d AND `nurl` = '%s'",
1604 intval($owner["uid"]),
1605 dbesc(normalise_link($mention)));
1606 if ($r[0]["forum"] || $r[0]["prv"])
1607 xml::add_element($doc, $entry, "link", "", array("rel" => "mentioned",
1608 "ostatus:object-type" => ACTIVITY_OBJ_GROUP,
1609 "href" => $mention));
1611 xml::add_element($doc, $entry, "link", "", array("rel" => "mentioned",
1612 "ostatus:object-type" => ACTIVITY_OBJ_PERSON,
1613 "href" => $mention));
1616 if (!$item["private"]) {
1617 xml::add_element($doc, $entry, "link", "", array("rel" => "ostatus:attention",
1618 "href" => "http://activityschema.org/collection/public"));
1619 xml::add_element($doc, $entry, "link", "", array("rel" => "mentioned",
1620 "ostatus:object-type" => "http://activitystrea.ms/schema/1.0/collection",
1621 "href" => "http://activityschema.org/collection/public"));
1622 xml::add_element($doc, $entry, "mastodon:scope", "public");
1626 foreach ($tags as $t)
1628 xml::add_element($doc, $entry, "category", "", array("term" => $t[2]));
1630 self::get_attachment($doc, $entry, $item);
1632 if ($complete && ($item["id"] > 0)) {
1633 $app = $item["app"];
1637 $attributes = array("local_id" => $item["id"], "source" => $app);
1639 if (isset($parent["id"]))
1640 $attributes["repeat_of"] = $parent["id"];
1642 if ($item["coord"] != "")
1643 xml::add_element($doc, $entry, "georss:point", $item["coord"]);
1645 xml::add_element($doc, $entry, "statusnet:notice_info", "", $attributes);
1650 * @brief Creates the XML feed for a given nickname
1652 * @param App $a The application class
1653 * @param string $owner_nick Nickname of the feed owner
1654 * @param string $last_update Date of the last update
1655 * @param integer $max_items Number of maximum items to fetch
1657 * @return string XML feed
1659 public static function feed(App $a, $owner_nick, &$last_update, $max_items = 300) {
1660 $stamp = microtime(true);
1662 $cachekey = "ostatus:feed:".$owner_nick.":".$last_update;
1664 $previous_created = $last_update;
1666 $result = Cache::get($cachekey);
1667 if (!is_null($result)) {
1668 logger('Feed duration: '.number_format(microtime(true) - $stamp, 3).' - '.$owner_nick.' - '.$previous_created.' (cached)', LOGGER_DEBUG);
1669 $last_update = $result['last_update'];
1670 return $result['feed'];
1673 $r = q("SELECT `contact`.*, `user`.`nickname`, `user`.`timezone`, `user`.`page-flags`
1674 FROM `contact` INNER JOIN `user` ON `user`.`uid` = `contact`.`uid`
1675 WHERE `contact`.`self` AND `user`.`nickname` = '%s' LIMIT 1",
1676 dbesc($owner_nick));
1677 if (!dbm::is_result($r)) {
1683 if (!strlen($last_update)) {
1684 $last_update = 'now -30 days';
1687 $check_date = datetime_convert('UTC','UTC',$last_update,'Y-m-d H:i:s');
1688 $authorid = get_contact($owner["url"], 0);
1690 $items = q("SELECT `item`.*, `item`.`id` AS `item_id` FROM `item` USE INDEX (`uid_contactid_created`)
1691 STRAIGHT_JOIN `thread` ON `thread`.`iid` = `item`.`parent`
1692 WHERE `item`.`uid` = %d AND `item`.`contact-id` = %d AND
1693 `item`.`author-id` = %d AND `item`.`created` > '%s' AND
1694 NOT `item`.`deleted` AND NOT `item`.`private` AND
1695 `thread`.`network` IN ('%s', '%s')
1696 ORDER BY `item`.`created` DESC LIMIT %d",
1697 intval($owner["uid"]), intval($owner["id"]),
1698 intval($authorid), dbesc($check_date),
1699 dbesc(NETWORK_OSTATUS), dbesc(NETWORK_DFRN), intval($max_items));
1701 $doc = new DOMDocument('1.0', 'utf-8');
1702 $doc->formatOutput = true;
1704 $root = self::add_header($doc, $owner);
1706 foreach ($items AS $item) {
1707 if (Config::get('system', 'ostatus_debug')) {
1708 $item['body'] .= '🍼';
1710 $entry = self::entry($doc, $item, $owner);
1711 $root->appendChild($entry);
1713 if ($last_update < $item['created']) {
1714 $last_update = $item['created'];
1718 $feeddata = trim($doc->saveXML());
1720 $msg = array('feed' => $feeddata, 'last_update' => $last_update);
1721 Cache::set($cachekey, $msg, CACHE_QUARTER_HOUR);
1723 logger('Feed duration: '.number_format(microtime(true) - $stamp, 3).' - '.$owner_nick.' - '.$previous_created, LOGGER_DEBUG);
1729 * @brief Creates the XML for a salmon message
1731 * @param array $item Data of the item that is to be posted
1732 * @param array $owner Contact data of the poster
1734 * @return string XML for the salmon
1736 public static function salmon($item,$owner) {
1738 $doc = new DOMDocument('1.0', 'utf-8');
1739 $doc->formatOutput = true;
1741 if (Config::get('system', 'ostatus_debug')) {
1742 $item['body'] .= '🐟';
1745 $entry = self::entry($doc, $item, $owner, true);
1747 $doc->appendChild($entry);
1749 return trim($doc->saveXML());