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
32 const OSTATUS_DEFAULT_POLL_INTERVAL = 30; // given in minutes
33 const OSTATUS_DEFAULT_POLL_TIMEFRAME = 1440; // given in minutes
34 const OSTATUS_DEFAULT_POLL_TIMEFRAME_MENTIONS = 14400; // given in minutes
36 private static $itemlist;
39 * @brief Fetches author data
41 * @param object $xpath The xpath object
42 * @param object $context The xml context of the author detals
43 * @param array $importer user record of the importing user
44 * @param array $contact Called by reference, will contain the fetched contact
45 * @param bool $onlyfetch Only fetch the header without updating the contact entries
47 * @return array Array of author related entries for the item
49 private static function fetchauthor($xpath, $context, $importer, &$contact, $onlyfetch) {
52 $author["author-link"] = $xpath->evaluate('atom:author/atom:uri/text()', $context)->item(0)->nodeValue;
53 $author["author-name"] = $xpath->evaluate('atom:author/atom:name/text()', $context)->item(0)->nodeValue;
54 $addr = $xpath->evaluate('atom:author/atom:email/text()', $context)->item(0)->nodeValue;
56 $aliaslink = $author["author-link"];
58 $alternate = $xpath->query("atom:author/atom:link[@rel='alternate']", $context)->item(0)->attributes;
59 if (is_object($alternate)) {
60 foreach ($alternate AS $attributes) {
61 if (($attributes->name == "href") && ($attributes->textContent != "")) {
62 $author["author-link"] = $attributes->textContent;
67 $author["contact-id"] = $contact["id"];
69 if ($author["author-link"] != "") {
70 if ($aliaslink == "") {
71 $aliaslink = $author["author-link"];
74 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `nurl` IN ('%s', '%s') AND `network` != '%s'",
75 intval($importer["uid"]), dbesc(normalise_link($author["author-link"])),
76 dbesc(normalise_link($aliaslink)), dbesc(NETWORK_STATUSNET));
78 if (dbm::is_result($r)) {
80 $author["contact-id"] = $r[0]["id"];
81 $author["author-link"] = $r[0]["url"];
83 } elseif ($addr != "") {
85 $contact = dba::fetch_first("SELECT * FROM `contact` WHERE `uid` = ? AND `addr` = ? AND `network` != ?",
86 $importer["uid"], $addr, NETWORK_STATUSNET);
88 if (dbm::is_result($contact)) {
89 $author["contact-id"] = $contact["id"];
90 $author["author-link"] = $contact["url"];
94 $avatarlist = array();
95 $avatars = $xpath->query("atom:author/atom:link[@rel='avatar']", $context);
96 foreach ($avatars AS $avatar) {
99 foreach ($avatar->attributes AS $attributes) {
100 if ($attributes->name == "href") {
101 $href = $attributes->textContent;
103 if ($attributes->name == "width") {
104 $width = $attributes->textContent;
108 $avatarlist[$width] = $href;
111 if (count($avatarlist) > 0) {
113 $author["author-avatar"] = Probe::fixAvatar(current($avatarlist), $author["author-link"]);
116 $displayname = $xpath->evaluate('atom:author/poco:displayName/text()', $context)->item(0)->nodeValue;
117 if ($displayname != "") {
118 $author["author-name"] = $displayname;
121 $author["owner-name"] = $author["author-name"];
122 $author["owner-link"] = $author["author-link"];
123 $author["owner-avatar"] = $author["author-avatar"];
125 // Only update the contacts if it is an OStatus contact
126 if ($r && !$onlyfetch && ($contact["network"] == NETWORK_OSTATUS)) {
128 // Update contact data
130 // This query doesn't seem to work
131 // $value = $xpath->query("atom:link[@rel='salmon']", $context)->item(0)->nodeValue;
133 // $contact["notify"] = $value;
135 // This query doesn't seem to work as well - I hate these queries
136 // $value = $xpath->query("atom:link[@rel='self' and @type='application/atom+xml']", $context)->item(0)->nodeValue;
138 // $contact["poll"] = $value;
140 $value = $xpath->evaluate('atom:author/atom:uri/text()', $context)->item(0)->nodeValue;
142 $contact["alias"] = $value;
144 $value = $xpath->evaluate('atom:author/poco:displayName/text()', $context)->item(0)->nodeValue;
146 $contact["name"] = $value;
148 $value = $xpath->evaluate('atom:author/poco:preferredUsername/text()', $context)->item(0)->nodeValue;
150 $contact["nick"] = $value;
152 $value = $xpath->evaluate('atom:author/poco:note/text()', $context)->item(0)->nodeValue;
154 $contact["about"] = html2bbcode($value);
156 $value = $xpath->evaluate('atom:author/poco:address/poco:formatted/text()', $context)->item(0)->nodeValue;
158 $contact["location"] = $value;
160 if (($contact["name"] != $r[0]["name"]) || ($contact["nick"] != $r[0]["nick"]) || ($contact["about"] != $r[0]["about"]) ||
161 ($contact["alias"] != $r[0]["alias"]) || ($contact["location"] != $r[0]["location"])) {
163 logger("Update contact data for contact ".$contact["id"], LOGGER_DEBUG);
165 q("UPDATE `contact` SET `name` = '%s', `nick` = '%s', `alias` = '%s', `about` = '%s', `location` = '%s', `name-date` = '%s' WHERE `id` = %d",
166 dbesc($contact["name"]), dbesc($contact["nick"]), dbesc($contact["alias"]),
167 dbesc($contact["about"]), dbesc($contact["location"]),
168 dbesc(datetime_convert()), intval($contact["id"]));
171 if (isset($author["author-avatar"]) && ($author["author-avatar"] != $r[0]['avatar'])) {
172 logger("Update profile picture for contact ".$contact["id"], LOGGER_DEBUG);
174 update_contact_avatar($author["author-avatar"], $importer["uid"], $contact["id"]);
177 // Ensure that we are having this contact (with uid=0)
178 $cid = get_contact($author["author-link"], 0);
181 // Update it with the current values
182 q("UPDATE `contact` SET `url` = '%s', `name` = '%s', `nick` = '%s', `alias` = '%s',
183 `about` = '%s', `location` = '%s',
184 `success_update` = '%s', `last-update` = '%s'
186 dbesc($author["author-link"]), dbesc($contact["name"]), dbesc($contact["nick"]),
187 dbesc($contact["alias"]), dbesc($contact["about"]), dbesc($contact["location"]),
188 dbesc(datetime_convert()), dbesc(datetime_convert()), intval($cid));
191 update_contact_avatar($author["author-avatar"], 0, $cid);
194 $contact["generation"] = 2;
195 $contact["hide"] = false; // OStatus contacts are never hidden
196 $contact["photo"] = $author["author-avatar"];
197 $gcid = update_gcontact($contact);
199 link_gcontact($gcid, $contact["uid"], $contact["id"]);
206 * @brief Fetches author data from a given XML string
208 * @param string $xml The XML
209 * @param array $importer user record of the importing user
211 * @return array Array of author related entries for the item
213 public static function salmon_author($xml, $importer) {
218 $doc = new DOMDocument();
219 @$doc->loadXML($xml);
221 $xpath = new DomXPath($doc);
222 $xpath->registerNamespace('atom', NAMESPACE_ATOM1);
223 $xpath->registerNamespace('thr', NAMESPACE_THREAD);
224 $xpath->registerNamespace('georss', NAMESPACE_GEORSS);
225 $xpath->registerNamespace('activity', NAMESPACE_ACTIVITY);
226 $xpath->registerNamespace('media', NAMESPACE_MEDIA);
227 $xpath->registerNamespace('poco', NAMESPACE_POCO);
228 $xpath->registerNamespace('ostatus', NAMESPACE_OSTATUS);
229 $xpath->registerNamespace('statusnet', NAMESPACE_STATUSNET);
231 $entries = $xpath->query('/atom:entry');
233 foreach ($entries AS $entry) {
235 $author = self::fetchauthor($xpath, $entry, $importer, $contact, true);
241 * @brief Read attributes from element
243 * @param object $element Element object
245 * @return array attributes
247 private static function read_attributes($element) {
248 $attribute = array();
250 foreach ($element->attributes AS $attributes) {
251 $attribute[$attributes->name] = $attributes->textContent;
258 * @brief Imports an XML string containing OStatus elements
260 * @param string $xml The XML
261 * @param array $importer user record of the importing user
263 * @param array $hub Called by reference, returns the fetched hub data
265 public static function import($xml, $importer, &$contact, &$hub) {
266 self::process($xml, $importer, $contact, $hub);
270 * @brief Imports an XML string containing OStatus elements
272 * @param string $xml The XML
273 * @param array $importer user record of the importing user
275 * @param array $hub Called by reference, returns the fetched hub data
277 private static function process($xml, $importer, &$contact, &$hub, $stored = false, $initialize = true) {
279 self::$itemlist = array();
282 logger("Import OStatus message", LOGGER_DEBUG);
287 $doc = new DOMDocument();
288 @$doc->loadXML($xml);
290 $xpath = new DomXPath($doc);
291 $xpath->registerNamespace('atom', NAMESPACE_ATOM1);
292 $xpath->registerNamespace('thr', NAMESPACE_THREAD);
293 $xpath->registerNamespace('georss', NAMESPACE_GEORSS);
294 $xpath->registerNamespace('activity', NAMESPACE_ACTIVITY);
295 $xpath->registerNamespace('media', NAMESPACE_MEDIA);
296 $xpath->registerNamespace('poco', NAMESPACE_POCO);
297 $xpath->registerNamespace('ostatus', NAMESPACE_OSTATUS);
298 $xpath->registerNamespace('statusnet', NAMESPACE_STATUSNET);
301 $hub_attributes = $xpath->query("/atom:feed/atom:link[@rel='hub']")->item(0)->attributes;
302 if (is_object($hub_attributes)) {
303 foreach ($hub_attributes AS $hub_attribute) {
304 if ($hub_attribute->name == "href") {
305 $hub = $hub_attribute->textContent;
306 logger("Found hub ".$hub, LOGGER_DEBUG);
312 $header["uid"] = $importer["uid"];
313 $header["network"] = NETWORK_OSTATUS;
314 $header["type"] = "remote";
316 $header["origin"] = 0;
317 $header["gravity"] = GRAVITY_PARENT;
319 $first_child = $doc->firstChild->tagName;
321 if ($first_child == "feed") {
322 $entries = $xpath->query('/atom:feed/atom:entry');
323 $header["protocol"] = PROTOCOL_OSTATUS_FEED;
325 $entries = $xpath->query('/atom:entry');
326 $header["protocol"] = PROTOCOL_OSTATUS_SALMON;
329 // Fetch the first author
330 $authordata = $xpath->query('//author')->item(0);
331 $author = self::fetchauthor($xpath, $authordata, $importer, $contact, $stored);
333 $entry = $xpath->query('/atom:entry');
334 $header["protocol"] = PROTOCOL_OSTATUS_SALMON;
336 // Reverse the order of the entries
337 $entrylist = array();
339 foreach ($entries AS $entry) {
340 $entrylist[] = $entry;
343 if (!$initialize && (count($entrylist) > 1)) {
347 foreach (array_reverse($entrylist) AS $entry) {
349 $authorelement = $xpath->query('/atom:entry/atom:author', $entry);
350 if ($authorelement->length > 0) {
351 $author = self::fetchauthor($xpath, $entry, $importer, $contact, $stored);
354 $value = $xpath->evaluate('atom:author/poco:preferredUsername/text()', $entry)->item(0)->nodeValue;
358 $nickname = $author["author-name"];
361 $item = array_merge($header, $author);
363 $item["verb"] = $xpath->query('activity:verb/text()', $entry)->item(0)->nodeValue;
366 if ($item["verb"] == "qvitter-delete-notice" || $item["verb"] == ACTIVITY_DELETE) {
367 // ignore "Delete" messages (by now)
368 logger("Ignore delete message ".print_r($item, true));
372 if ($item["verb"] == ACTIVITY_JOIN) {
373 // ignore "Join" messages
374 logger("Ignore join message ".print_r($item, true));
378 if ($item["verb"] == ACTIVITY_FOLLOW) {
379 new_follower($importer, $contact, $item, $nickname);
383 if ($item["verb"] == NAMESPACE_OSTATUS."/unfollow") {
384 lose_follower($importer, $contact, $item, $dummy);
388 if ($item["verb"] == NAMESPACE_OSTATUS."/unfavorite") {
389 // Ignore "Unfavorite" message
390 logger("Ignore unfavorite message ".print_r($item, true));
394 if ($item["verb"] == ACTIVITY_FAVORITE) {
395 $orig_uri = $xpath->query("activity:object/atom:id", $entry)->item(0)->nodeValue;
396 logger("Favorite ".$orig_uri." ".print_r($item, true));
398 $item["verb"] = ACTIVITY_LIKE;
399 $item["parent-uri"] = $orig_uri;
400 $item["gravity"] = GRAVITY_LIKE;
403 // http://activitystrea.ms/schema/1.0/rsvp-yes
404 if (!in_array($item["verb"], array(ACTIVITY_POST, ACTIVITY_LIKE, ACTIVITY_SHARE))) {
405 logger("Unhandled verb ".$item["verb"]." ".print_r($item, true));
408 $doc2 = new DOMDocument();
409 $doc2->loadXML($xml);
410 $doc2->preserveWhiteSpace = false;
411 $doc2->formatOutput = true;
412 $xml2 = $doc2->saveXML();
414 $item["source"] = $xml2;
416 self::processPost($xpath, $entry, $item, $importer);
418 if ($initialize && (count(self::$itemlist) > 0)) {
419 // We will import it everytime, when it is started by our contacts
420 $valid = !empty(self::$itemlist[0]['contact-id']);
422 // If not, then it depends on this setting
423 $valid = !Config::get('system','ostatus_full_threads');
427 // But we will only import complete threads
428 $valid = self::$itemlist[0]['uri'] == self::$itemlist[0]['parent-uri'];
432 // Never post a thread when the only interaction by our contact was a like
434 $verbs = array(ACTIVITY_POST, ACTIVITY_SHARE);
435 foreach (self::$itemlist AS $item) {
436 if (!empty($item['contact-id']) && in_array($item['verb'], $verbs)) {
443 $default_contact = 0;
444 $key = count(self::$itemlist);
445 for ($key = count(self::$itemlist) - 1; $key >= 0; $key--) {
446 if (empty(self::$itemlist[$key]['contact-id'])) {
447 self::$itemlist[$key]['contact-id'] = $default_contact;
449 $default_contact = $item['contact-id'];
452 foreach (self::$itemlist AS $item) {
453 $found = dba::exists('item', array('uid' => $importer["uid"], 'uri' => $item["uri"]));
455 logger("Item with uri ".$item["uri"]." for user ".$importer["uid"]." already exists.", LOGGER_DEBUG);
457 $ret = item_store($item);
458 logger('Item was stored with return value '.$ret);
462 self::$itemlist = array();
468 private static function processPost($xpath, $entry, &$item, $importer) {
469 $item["uri"] = $xpath->query('atom:id/text()', $entry)->item(0)->nodeValue;
470 $item["body"] = html2bbcode($xpath->query('atom:content/text()', $entry)->item(0)->nodeValue);
471 $item["object-type"] = $xpath->query('activity:object-type/text()', $entry)->item(0)->nodeValue;
472 if (($item["object-type"] == ACTIVITY_OBJ_BOOKMARK) || ($item["object-type"] == ACTIVITY_OBJ_EVENT)) {
473 $item["title"] = $xpath->query('atom:title/text()', $entry)->item(0)->nodeValue;
474 $item["body"] = $xpath->query('atom:summary/text()', $entry)->item(0)->nodeValue;
475 } elseif ($item["object-type"] == ACTIVITY_OBJ_QUESTION) {
476 $item["title"] = $xpath->query('atom:title/text()', $entry)->item(0)->nodeValue;
479 $item["created"] = $xpath->query('atom:published/text()', $entry)->item(0)->nodeValue;
480 $item["edited"] = $xpath->query('atom:updated/text()', $entry)->item(0)->nodeValue;
481 $conversation = $xpath->query('ostatus:conversation/text()', $entry)->item(0)->nodeValue;
482 $item['conversation-uri'] = $conversation;
484 $conv = $xpath->query('ostatus:conversation', $entry);
485 if (is_object($conv->item(0))) {
486 foreach ($conv->item(0)->attributes AS $attributes) {
487 if ($attributes->name == "ref") {
488 $item['conversation-uri'] = $attributes->textContent;
490 if ($attributes->name == "href") {
491 $item['conversation-href'] = $attributes->textContent;
496 if (empty($item['conversation-href']) && !empty($item['conversation-uri'])) {
497 $item['conversation-href'] = $item['conversation-uri'];
502 $inreplyto = $xpath->query('thr:in-reply-to', $entry);
503 if (is_object($inreplyto->item(0))) {
504 foreach ($inreplyto->item(0)->attributes AS $attributes) {
505 if ($attributes->name == "ref") {
506 $item["parent-uri"] = $attributes->textContent;
508 if ($attributes->name == "href") {
509 $related = $attributes->textContent;
514 $georsspoint = $xpath->query('georss:point', $entry);
515 if (!empty($georsspoint) && ($georsspoint->length > 0)) {
516 $item["coord"] = $georsspoint->item(0)->nodeValue;
519 $categories = $xpath->query('atom:category', $entry);
521 foreach ($categories AS $category) {
522 foreach ($category->attributes AS $attributes) {
523 if ($attributes->name == "term") {
524 $term = $attributes->textContent;
525 if (strlen($item["tag"])) {
528 $item["tag"] .= "#[url=".System::baseUrl()."/search?tag=".$term."]".$term."[/url]";
537 $links = $xpath->query('atom:link', $entry);
539 $link_data = self::processLinks($links, $item);
540 $self = $link_data['self'];
541 $add_body = $link_data['add_body'];
546 $notice_info = $xpath->query('statusnet:notice_info', $entry);
547 if ($notice_info && ($notice_info->length > 0)) {
548 foreach ($notice_info->item(0)->attributes AS $attributes) {
549 if ($attributes->name == "source") {
550 $item["app"] = strip_tags($attributes->textContent);
552 if ($attributes->name == "repeat_of") {
553 $repeat_of = $attributes->textContent;
557 // Is it a repeated post?
558 if (($repeat_of != "") || ($item["verb"] == ACTIVITY_SHARE)) {
559 $link_data = self::processRepeatedItem($xpath, $entry, $item, $importer);
560 if (!empty($link_data['add_body'])) {
561 $add_body .= $link_data['add_body'];
565 $item["body"] .= $add_body;
567 // Only add additional data when there is no picture in the post
568 if (!strstr($item["body"],'[/img]')) {
569 $item["body"] = add_page_info_to_body($item["body"]);
572 // Mastodon Content Warning
573 if (($item["verb"] == ACTIVITY_POST) && $xpath->evaluate('boolean(atom:summary)', $entry)) {
574 $clear_text = $xpath->query('atom:summary/text()', $entry)->item(0)->nodeValue;
576 $item["body"] = html2bbcode($clear_text) . '[spoiler]' . $item["body"] . '[/spoiler]';
579 if (isset($item["parent-uri"]) && ($related != '')) {
580 self::FetchRelated($related, $item["parent-uri"], $importer);
581 $item["type"] = 'remote-comment';
582 $item["gravity"] = GRAVITY_COMMENT;
584 $item["parent-uri"] = $item["uri"];
587 if ($item['author-link'] != '') {
588 $item = store_conversation($item);
591 self::$itemlist[] = $item;
594 private static function fetchRelated($related, $related_uri, $importer) {
595 $condition = array('`item-uri` = ? AND `protocol` IN (?, ?)', $related_uri, PROTOCOL_DFRN, PROTOCOL_OSTATUS_SALMON);
596 $conversation = dba::select('conversation', array('source', 'protocol'), $condition, array('limit' => 1));
597 if (dbm::is_result($conversation)) {
599 $xml = $conversation['source'];
600 if (self::process($xml, $importer, $contact, $hub, $stored, false)) {
603 if ($conversation['protocol'] == PROTOCOL_OSTATUS_SALMON) {
604 dba::delete('conversation', array('item-uri' => $related_uri));
609 $related_data = z_fetch_url($related);
611 if (!$related_data['success']) {
617 if (stristr($related_data['header'], 'Content-Type: application/atom+xml')) {
618 $xml = $related_data['body'];
622 $doc = new DOMDocument();
623 if (!@$doc->loadHTML($related_data['body'])) {
626 $xpath = new DomXPath($doc);
628 $links = $xpath->query('//link');
630 foreach ($links AS $link) {
631 $attribute = self::read_attributes($link);
632 if (($attribute['rel'] == 'alternate') && ($attribute['type'] == 'application/atom+xml')) {
633 $related_atom = z_fetch_url($attribute['href']);
635 if ($related_atom['success']) {
636 $xml = $related_atom['body'];
643 // Workaround for older GNU Social servers
644 if (($xml == '') && strstr($related, '/notice/')) {
645 $related_atom = z_fetch_url(str_replace('/notice/', '/api/statuses/show/', $related).',atom');
647 if ($related_atom['success']) {
648 $xml = $related_atom['body'];
653 self::process($xml, $importer, $contact, $hub, $stored, false);
658 private static function processRepeatedItem($xpath, $entry, &$item, $importer) {
659 $activityobjects = $xpath->query('activity:object', $entry)->item(0);
661 if (!is_object($activityobjects)) {
665 $link_data = array();
667 $orig_uri = $xpath->query('atom:id/text()', $activityobjects)->item(0)->nodeValue;
669 $links = $xpath->query("atom:link", $activityobjects);
671 $link_data = self::processLinks($links, $item);
674 $orig_body = $xpath->query('atom:content/text()', $activityobjects)->item(0)->nodeValue;
675 $orig_created = $xpath->query('atom:published/text()', $activityobjects)->item(0)->nodeValue;
676 $orig_edited = $xpath->query('atom:updated/text()', $activityobjects)->item(0)->nodeValue;
678 $orig_contact = $contact;
679 $orig_author = self::fetchauthor($xpath, $activityobjects, $importer, $orig_contact, false);
681 $item["author-name"] = $orig_author["author-name"];
682 $item["author-link"] = $orig_author["author-link"];
683 $item["author-avatar"] = $orig_author["author-avatar"];
685 $item["body"] = html2bbcode($orig_body);
686 $item["created"] = $orig_created;
687 $item["edited"] = $orig_edited;
689 $item["uri"] = $orig_uri;
691 $item["verb"] = $xpath->query('activity:verb/text()', $activityobjects)->item(0)->nodeValue;
693 $item["object-type"] = $xpath->query('activity:object-type/text()', $activityobjects)->item(0)->nodeValue;
695 $inreplyto = $xpath->query('thr:in-reply-to', $activityobjects);
696 if (is_object($inreplyto->item(0))) {
697 foreach ($inreplyto->item(0)->attributes AS $attributes) {
698 if ($attributes->name == "ref") {
699 $item["parent-uri"] = $attributes->textContent;
707 private static function processLinks($links, &$item) {
708 $link_data = array('add_body' => '', 'self' => '');
710 foreach ($links AS $link) {
711 $attribute = self::read_attributes($link);
713 if (($attribute['rel'] != "") && ($attribute['href'] != "")) {
714 switch ($attribute['rel']) {
716 $item["plink"] = $attribute['href'];
717 if (($item["object-type"] == ACTIVITY_OBJ_QUESTION) ||
718 ($item["object-type"] == ACTIVITY_OBJ_EVENT)) {
719 $item["body"] .= add_page_info($attribute['href']);
722 case "ostatus:conversation":
723 $link_data['conversation'] = $attribute['href'];
724 $item['conversation-href'] = $link_data['conversation'];
725 if (!isset($item['conversation-uri'])) {
726 $item['conversation-uri'] = $item['conversation-href'];
730 $filetype = strtolower(substr($attribute['type'], 0, strpos($attribute['type'],'/')));
731 if ($filetype == 'image') {
732 $link_data['add_body'] .= "\n[img]".$attribute['href'].'[/img]';
734 if (strlen($item["attach"])) {
735 $item["attach"] .= ',';
737 if (!isset($attribute['length'])) {
738 $attribute['length'] = "0";
740 $item["attach"] .= '[attach]href="'.$attribute['href'].'" length="'.$attribute['length'].'" type="'.$attribute['type'].'" title="'.$attribute['title'].'"[/attach]';
744 if ($item["object-type"] != ACTIVITY_OBJ_BOOKMARK) {
745 if (!isset($item["parent-uri"])) {
746 $item["parent-uri"] = $attribute['href'];
748 $link_data['related'] = $attribute['href'];
750 $item["body"] .= add_page_info($attribute['href']);
754 if ($item["plink"] == '') {
755 $item["plink"] = $attribute['href'];
757 $link_data['self'] = $attribute['href'];
766 * @brief Checks if the current post is a reshare
768 * @param array $item The item array of thw post
770 * @return string The guid if the post is a reshare
772 private static function get_reshared_guid($item) {
773 $body = trim($item["body"]);
775 // Skip if it isn't a pure repeated messages
776 // Does it start with a share?
777 if (strpos($body, "[share") > 0)
780 // Does it end with a share?
781 if (strlen($body) > (strrpos($body, "[/share]") + 8))
784 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$1",$body);
785 // Skip if there is no shared message in there
786 if ($body == $attributes)
790 preg_match("/guid='(.*?)'/ism", $attributes, $matches);
791 if ($matches[1] != "")
794 preg_match('/guid="(.*?)"/ism', $attributes, $matches);
795 if ($matches[1] != "")
802 * @brief Cleans the body of a post if it contains picture links
804 * @param string $body The body
806 * @return string The cleaned body
808 private static function format_picture_post($body) {
809 $siteinfo = get_attached_data($body);
811 if (($siteinfo["type"] == "photo")) {
812 if (isset($siteinfo["preview"]))
813 $preview = $siteinfo["preview"];
815 $preview = $siteinfo["image"];
817 // Is it a remote picture? Then make a smaller preview here
818 $preview = proxy_url($preview, false, PROXY_SIZE_SMALL);
820 // Is it a local picture? Then make it smaller here
821 $preview = str_replace(array("-0.jpg", "-0.png"), array("-2.jpg", "-2.png"), $preview);
822 $preview = str_replace(array("-1.jpg", "-1.png"), array("-2.jpg", "-2.png"), $preview);
824 if (isset($siteinfo["url"]))
825 $url = $siteinfo["url"];
827 $url = $siteinfo["image"];
829 $body = trim($siteinfo["text"])." [url]".$url."[/url]\n[img]".$preview."[/img]";
836 * @brief Adds the header elements to the XML document
838 * @param object $doc XML document
839 * @param array $owner Contact data of the poster
841 * @return object header root element
843 private static function add_header($doc, $owner) {
847 $root = $doc->createElementNS(NAMESPACE_ATOM1, 'feed');
848 $doc->appendChild($root);
850 $root->setAttribute("xmlns:thr", NAMESPACE_THREAD);
851 $root->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
852 $root->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
853 $root->setAttribute("xmlns:media", NAMESPACE_MEDIA);
854 $root->setAttribute("xmlns:poco", NAMESPACE_POCO);
855 $root->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
856 $root->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
857 $root->setAttribute("xmlns:mastodon", NAMESPACE_MASTODON);
859 $attributes = array("uri" => "https://friendi.ca", "version" => FRIENDICA_VERSION."-".DB_UPDATE_VERSION);
860 xml::add_element($doc, $root, "generator", FRIENDICA_PLATFORM, $attributes);
861 xml::add_element($doc, $root, "id", System::baseUrl()."/profile/".$owner["nick"]);
862 xml::add_element($doc, $root, "title", sprintf("%s timeline", $owner["name"]));
863 xml::add_element($doc, $root, "subtitle", sprintf("Updates from %s on %s", $owner["name"], $a->config["sitename"]));
864 xml::add_element($doc, $root, "logo", $owner["photo"]);
865 xml::add_element($doc, $root, "updated", datetime_convert("UTC", "UTC", "now", ATOM_TIME));
867 $author = self::add_author($doc, $owner);
868 $root->appendChild($author);
870 $attributes = array("href" => $owner["url"], "rel" => "alternate", "type" => "text/html");
871 xml::add_element($doc, $root, "link", "", $attributes);
873 /// @TODO We have to find out what this is
874 /// $attributes = array("href" => System::baseUrl()."/sup",
875 /// "rel" => "http://api.friendfeed.com/2008/03#sup",
876 /// "type" => "application/json");
877 /// xml::add_element($doc, $root, "link", "", $attributes);
879 self::hublinks($doc, $root, $owner["nick"]);
881 $attributes = array("href" => System::baseUrl()."/salmon/".$owner["nick"], "rel" => "salmon");
882 xml::add_element($doc, $root, "link", "", $attributes);
884 $attributes = array("href" => System::baseUrl()."/salmon/".$owner["nick"], "rel" => "http://salmon-protocol.org/ns/salmon-replies");
885 xml::add_element($doc, $root, "link", "", $attributes);
887 $attributes = array("href" => System::baseUrl()."/salmon/".$owner["nick"], "rel" => "http://salmon-protocol.org/ns/salmon-mention");
888 xml::add_element($doc, $root, "link", "", $attributes);
890 $attributes = array("href" => System::baseUrl()."/api/statuses/user_timeline/".$owner["nick"].".atom",
891 "rel" => "self", "type" => "application/atom+xml");
892 xml::add_element($doc, $root, "link", "", $attributes);
898 * @brief Add the link to the push hubs to the XML document
900 * @param object $doc XML document
901 * @param object $root XML root element where the hub links are added
903 public static function hublinks($doc, $root, $nick) {
904 $h = System::baseUrl() . '/pubsubhubbub/'.$nick;
905 xml::add_element($doc, $root, "link", "", array("href" => $h, "rel" => "hub"));
909 * @brief Adds attachement data to the XML document
911 * @param object $doc XML document
912 * @param object $root XML root element where the hub links are added
913 * @param array $item Data of the item that is to be posted
915 private static function get_attachment($doc, $root, $item) {
917 $siteinfo = get_attached_data($item["body"]);
919 switch ($siteinfo["type"]) {
921 $imgdata = get_photo_info($siteinfo["image"]);
922 $attributes = array("rel" => "enclosure",
923 "href" => $siteinfo["image"],
924 "type" => $imgdata["mime"],
925 "length" => intval($imgdata["size"]));
926 xml::add_element($doc, $root, "link", "", $attributes);
929 $attributes = array("rel" => "enclosure",
930 "href" => $siteinfo["url"],
931 "type" => "text/html; charset=UTF-8",
933 "title" => $siteinfo["title"]);
934 xml::add_element($doc, $root, "link", "", $attributes);
940 if (!Config::get('system', 'ostatus_not_attach_preview') && ($siteinfo["type"] != "photo") && isset($siteinfo["image"])) {
941 $imgdata = get_photo_info($siteinfo["image"]);
942 $attributes = array("rel" => "enclosure",
943 "href" => $siteinfo["image"],
944 "type" => $imgdata["mime"],
945 "length" => intval($imgdata["size"]));
947 xml::add_element($doc, $root, "link", "", $attributes);
950 $arr = explode('[/attach],', $item['attach']);
952 foreach ($arr as $r) {
954 $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"|', $r, $matches);
956 $attributes = array("rel" => "enclosure",
957 "href" => $matches[1],
958 "type" => $matches[3]);
960 if (intval($matches[2])) {
961 $attributes["length"] = intval($matches[2]);
963 if (trim($matches[4]) != "") {
964 $attributes["title"] = trim($matches[4]);
966 xml::add_element($doc, $root, "link", "", $attributes);
973 * @brief Adds the author element to the XML document
975 * @param object $doc XML document
976 * @param array $owner Contact data of the poster
978 * @return object author element
980 private static function add_author($doc, $owner) {
982 $r = q("SELECT `homepage`, `publish` FROM `profile` WHERE `uid` = %d AND `is-default` LIMIT 1", intval($owner["uid"]));
983 if (dbm::is_result($r)) {
986 $author = $doc->createElement("author");
987 xml::add_element($doc, $author, "id", $owner["url"]);
988 xml::add_element($doc, $author, "activity:object-type", ACTIVITY_OBJ_PERSON);
989 xml::add_element($doc, $author, "uri", $owner["url"]);
990 xml::add_element($doc, $author, "name", $owner["nick"]);
991 xml::add_element($doc, $author, "email", $owner["addr"]);
992 xml::add_element($doc, $author, "summary", bbcode($owner["about"], false, false, 7));
994 $attributes = array("rel" => "alternate", "type" => "text/html", "href" => $owner["url"]);
995 xml::add_element($doc, $author, "link", "", $attributes);
999 "type" => "image/jpeg", // To-Do?
1000 "media:width" => 175,
1001 "media:height" => 175,
1002 "href" => $owner["photo"]);
1003 xml::add_element($doc, $author, "link", "", $attributes);
1005 if (isset($owner["thumb"])) {
1006 $attributes = array(
1008 "type" => "image/jpeg", // To-Do?
1009 "media:width" => 80,
1010 "media:height" => 80,
1011 "href" => $owner["thumb"]);
1012 xml::add_element($doc, $author, "link", "", $attributes);
1015 xml::add_element($doc, $author, "poco:preferredUsername", $owner["nick"]);
1016 xml::add_element($doc, $author, "poco:displayName", $owner["name"]);
1017 xml::add_element($doc, $author, "poco:note", bbcode($owner["about"], false, false, 7));
1019 if (trim($owner["location"]) != "") {
1020 $element = $doc->createElement("poco:address");
1021 xml::add_element($doc, $element, "poco:formatted", $owner["location"]);
1022 $author->appendChild($element);
1025 if (trim($profile["homepage"]) != "") {
1026 $urls = $doc->createElement("poco:urls");
1027 xml::add_element($doc, $urls, "poco:type", "homepage");
1028 xml::add_element($doc, $urls, "poco:value", $profile["homepage"]);
1029 xml::add_element($doc, $urls, "poco:primary", "true");
1030 $author->appendChild($urls);
1033 if (count($profile)) {
1034 xml::add_element($doc, $author, "followers", "", array("url" => System::baseUrl()."/viewcontacts/".$owner["nick"]));
1035 xml::add_element($doc, $author, "statusnet:profile_info", "", array("local_id" => $owner["uid"]));
1038 if ($profile["publish"]) {
1039 xml::add_element($doc, $author, "mastodon:scope", "public");
1045 * @TODO Picture attachments should look like this:
1046 * <a href="https://status.pirati.ca/attachment/572819" title="https://status.pirati.ca/file/heluecht-20151202T222602-rd3u49p.gif"
1047 * class="attachment thumbnail" id="attachment-572819" rel="nofollow external">https://status.pirati.ca/attachment/572819</a>
1052 * @brief Returns the given activity if present - otherwise returns the "post" activity
1054 * @param array $item Data of the item that is to be posted
1056 * @return string activity
1058 private static function construct_verb($item) {
1060 return $item['verb'];
1061 return ACTIVITY_POST;
1065 * @brief Returns the given object type if present - otherwise returns the "note" object type
1067 * @param array $item Data of the item that is to be posted
1069 * @return string Object type
1071 private static function construct_objecttype($item) {
1072 if (in_array($item['object-type'], array(ACTIVITY_OBJ_NOTE, ACTIVITY_OBJ_COMMENT)))
1073 return $item['object-type'];
1074 return ACTIVITY_OBJ_NOTE;
1078 * @brief Adds an entry element to the XML document
1080 * @param object $doc XML document
1081 * @param array $item Data of the item that is to be posted
1082 * @param array $owner Contact data of the poster
1083 * @param bool $toplevel
1085 * @return object Entry element
1087 private static function entry($doc, $item, $owner, $toplevel = false) {
1088 $repeated_guid = self::get_reshared_guid($item);
1089 if ($repeated_guid != "")
1090 $xml = self::reshare_entry($doc, $item, $owner, $repeated_guid, $toplevel);
1095 if ($item["verb"] == ACTIVITY_LIKE) {
1096 return self::like_entry($doc, $item, $owner, $toplevel);
1097 } elseif (in_array($item["verb"], array(ACTIVITY_FOLLOW, NAMESPACE_OSTATUS."/unfollow"))) {
1098 return self::follow_entry($doc, $item, $owner, $toplevel);
1100 return self::note_entry($doc, $item, $owner, $toplevel);
1105 * @brief Adds a source entry to the XML document
1107 * @param object $doc XML document
1108 * @param array $contact Array of the contact that is added
1110 * @return object Source element
1112 private static function source_entry($doc, $contact) {
1113 $source = $doc->createElement("source");
1114 xml::add_element($doc, $source, "id", $contact["poll"]);
1115 xml::add_element($doc, $source, "title", $contact["name"]);
1116 xml::add_element($doc, $source, "link", "", array("rel" => "alternate",
1117 "type" => "text/html",
1118 "href" => $contact["alias"]));
1119 xml::add_element($doc, $source, "link", "", array("rel" => "self",
1120 "type" => "application/atom+xml",
1121 "href" => $contact["poll"]));
1122 xml::add_element($doc, $source, "icon", $contact["photo"]);
1123 xml::add_element($doc, $source, "updated", datetime_convert("UTC","UTC",$contact["success_update"]."+00:00",ATOM_TIME));
1129 * @brief Fetches contact data from the contact or the gcontact table
1131 * @param string $url URL of the contact
1132 * @param array $owner Contact data of the poster
1134 * @return array Contact array
1136 private static function contact_entry($url, $owner) {
1138 $r = q("SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` IN (0, %d) ORDER BY `uid` DESC LIMIT 1",
1139 dbesc(normalise_link($url)), intval($owner["uid"]));
1140 if (dbm::is_result($r)) {
1142 $contact["uid"] = -1;
1145 if (!dbm::is_result($r)) {
1146 $r = q("SELECT * FROM `gcontact` WHERE `nurl` = '%s' LIMIT 1",
1147 dbesc(normalise_link($url)));
1148 if (dbm::is_result($r)) {
1150 $contact["uid"] = -1;
1151 $contact["success_update"] = $contact["updated"];
1155 if (!dbm::is_result($r))
1158 if (!isset($contact["poll"])) {
1159 $data = probe_url($url);
1160 $contact["poll"] = $data["poll"];
1162 if (!$contact["alias"])
1163 $contact["alias"] = $data["alias"];
1166 if (!isset($contact["alias"]))
1167 $contact["alias"] = $contact["url"];
1173 * @brief Adds an entry element with reshared content
1175 * @param object $doc XML document
1176 * @param array $item Data of the item that is to be posted
1177 * @param array $owner Contact data of the poster
1178 * @param $repeated_guid
1179 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1181 * @return object Entry element
1183 private static function reshare_entry($doc, $item, $owner, $repeated_guid, $toplevel) {
1185 if (($item["id"] != $item["parent"]) && (normalise_link($item["author-link"]) != normalise_link($owner["url"]))) {
1186 logger("OStatus entry is from author ".$owner["url"]." - not from ".$item["author-link"].". Quitting.", LOGGER_DEBUG);
1189 $title = self::entry_header($doc, $entry, $owner, $toplevel);
1191 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' AND NOT `private` AND `network` IN ('%s', '%s', '%s') LIMIT 1",
1192 intval($owner["uid"]), dbesc($repeated_guid),
1193 dbesc(NETWORK_DFRN), dbesc(NETWORK_DIASPORA), dbesc(NETWORK_OSTATUS));
1194 if (dbm::is_result($r)) {
1195 $repeated_item = $r[0];
1199 $contact = self::contact_entry($repeated_item['author-link'], $owner);
1201 $parent_item = (($item['thr-parent']) ? $item['thr-parent'] : $item['parent-uri']);
1203 $title = $owner["nick"]." repeated a notice by ".$contact["nick"];
1205 self::entry_content($doc, $entry, $item, $owner, $title, ACTIVITY_SHARE, false);
1207 $as_object = $doc->createElement("activity:object");
1209 xml::add_element($doc, $as_object, "activity:object-type", NAMESPACE_ACTIVITY_SCHEMA."activity");
1211 self::entry_content($doc, $as_object, $repeated_item, $owner, "", "", false);
1213 $author = self::add_author($doc, $contact);
1214 $as_object->appendChild($author);
1216 $as_object2 = $doc->createElement("activity:object");
1218 xml::add_element($doc, $as_object2, "activity:object-type", self::construct_objecttype($repeated_item));
1220 $title = sprintf("New comment by %s", $contact["nick"]);
1222 self::entry_content($doc, $as_object2, $repeated_item, $owner, $title);
1224 $as_object->appendChild($as_object2);
1226 self::entry_footer($doc, $as_object, $item, $owner, false);
1228 $source = self::source_entry($doc, $contact);
1230 $as_object->appendChild($source);
1232 $entry->appendChild($as_object);
1234 self::entry_footer($doc, $entry, $item, $owner);
1240 * @brief Adds an entry element with a "like"
1242 * @param object $doc XML document
1243 * @param array $item Data of the item that is to be posted
1244 * @param array $owner Contact data of the poster
1245 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1247 * @return object Entry element with "like"
1249 private static function like_entry($doc, $item, $owner, $toplevel) {
1251 if (($item["id"] != $item["parent"]) && (normalise_link($item["author-link"]) != normalise_link($owner["url"]))) {
1252 logger("OStatus entry is from author ".$owner["url"]." - not from ".$item["author-link"].". Quitting.", LOGGER_DEBUG);
1255 $title = self::entry_header($doc, $entry, $owner, $toplevel);
1257 $verb = NAMESPACE_ACTIVITY_SCHEMA."favorite";
1258 self::entry_content($doc, $entry, $item, $owner, "Favorite", $verb, false);
1260 $as_object = $doc->createElement("activity:object");
1262 $parent = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d",
1263 dbesc($item["thr-parent"]), intval($item["uid"]));
1264 $parent_item = (($item['thr-parent']) ? $item['thr-parent'] : $item['parent-uri']);
1266 xml::add_element($doc, $as_object, "activity:object-type", self::construct_objecttype($parent[0]));
1268 self::entry_content($doc, $as_object, $parent[0], $owner, "New entry");
1270 $entry->appendChild($as_object);
1272 self::entry_footer($doc, $entry, $item, $owner);
1278 * @brief Adds the person object element to the XML document
1280 * @param object $doc XML document
1281 * @param array $owner Contact data of the poster
1282 * @param array $contact Contact data of the target
1284 * @return object author element
1286 private static function add_person_object($doc, $owner, $contact) {
1288 $object = $doc->createElement("activity:object");
1289 xml::add_element($doc, $object, "activity:object-type", ACTIVITY_OBJ_PERSON);
1291 if ($contact['network'] == NETWORK_PHANTOM) {
1292 xml::add_element($doc, $object, "id", $contact['url']);
1296 xml::add_element($doc, $object, "id", $contact["alias"]);
1297 xml::add_element($doc, $object, "title", $contact["nick"]);
1299 $attributes = array("rel" => "alternate", "type" => "text/html", "href" => $contact["url"]);
1300 xml::add_element($doc, $object, "link", "", $attributes);
1302 $attributes = array(
1304 "type" => "image/jpeg", // To-Do?
1305 "media:width" => 175,
1306 "media:height" => 175,
1307 "href" => $contact["photo"]);
1308 xml::add_element($doc, $object, "link", "", $attributes);
1310 xml::add_element($doc, $object, "poco:preferredUsername", $contact["nick"]);
1311 xml::add_element($doc, $object, "poco:displayName", $contact["name"]);
1313 if (trim($contact["location"]) != "") {
1314 $element = $doc->createElement("poco:address");
1315 xml::add_element($doc, $element, "poco:formatted", $contact["location"]);
1316 $object->appendChild($element);
1323 * @brief Adds a follow/unfollow entry element
1325 * @param object $doc XML document
1326 * @param array $item Data of the follow/unfollow message
1327 * @param array $owner Contact data of the poster
1328 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1330 * @return object Entry element
1332 private static function follow_entry($doc, $item, $owner, $toplevel) {
1334 $item["id"] = $item["parent"] = 0;
1335 $item["created"] = $item["edited"] = date("c");
1336 $item["private"] = true;
1338 $contact = Probe::uri($item['follow']);
1340 if ($contact['alias'] == '') {
1341 $contact['alias'] = $contact["url"];
1343 $item['follow'] = $contact['alias'];
1346 $r = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `nurl` = '%s'",
1347 intval($owner['uid']), dbesc(normalise_link($contact["url"])));
1349 if (dbm::is_result($r)) {
1350 $connect_id = $r[0]['id'];
1355 if ($item['verb'] == ACTIVITY_FOLLOW) {
1356 $message = t('%s is now following %s.');
1357 $title = t('following');
1358 $action = "subscription";
1360 $message = t('%s stopped following %s.');
1361 $title = t('stopped following');
1362 $action = "unfollow";
1365 $item["uri"] = $item['parent-uri'] = $item['thr-parent'] =
1366 'tag:'.get_app()->get_hostname().
1367 ','.date('Y-m-d').':'.$action.':'.$owner['uid'].
1368 ':person:'.$connect_id.':'.$item['created'];
1370 $item["body"] = sprintf($message, $owner["nick"], $contact["nick"]);
1372 self::entry_header($doc, $entry, $owner, $toplevel);
1374 self::entry_content($doc, $entry, $item, $owner, $title);
1376 $object = self::add_person_object($doc, $owner, $contact);
1377 $entry->appendChild($object);
1379 self::entry_footer($doc, $entry, $item, $owner);
1385 * @brief Adds a regular entry element
1387 * @param object $doc XML document
1388 * @param array $item Data of the item that is to be posted
1389 * @param array $owner Contact data of the poster
1390 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1392 * @return object Entry element
1394 private static function note_entry($doc, $item, $owner, $toplevel) {
1396 if (($item["id"] != $item["parent"]) && (normalise_link($item["author-link"]) != normalise_link($owner["url"]))) {
1397 logger("OStatus entry is from author ".$owner["url"]." - not from ".$item["author-link"].". Quitting.", LOGGER_DEBUG);
1400 $title = self::entry_header($doc, $entry, $owner, $toplevel);
1402 xml::add_element($doc, $entry, "activity:object-type", ACTIVITY_OBJ_NOTE);
1404 self::entry_content($doc, $entry, $item, $owner, $title);
1406 self::entry_footer($doc, $entry, $item, $owner);
1412 * @brief Adds a header element to the XML document
1414 * @param object $doc XML document
1415 * @param object $entry The entry element where the elements are added
1416 * @param array $owner Contact data of the poster
1417 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1419 * @return string The title for the element
1421 private static function entry_header($doc, &$entry, $owner, $toplevel) {
1422 /// @todo Check if this title stuff is really needed (I guess not)
1424 $entry = $doc->createElement("entry");
1425 $title = sprintf("New note by %s", $owner["nick"]);
1427 $entry = $doc->createElementNS(NAMESPACE_ATOM1, "entry");
1429 $entry->setAttribute("xmlns:thr", NAMESPACE_THREAD);
1430 $entry->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
1431 $entry->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
1432 $entry->setAttribute("xmlns:media", NAMESPACE_MEDIA);
1433 $entry->setAttribute("xmlns:poco", NAMESPACE_POCO);
1434 $entry->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
1435 $entry->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
1436 $entry->setAttribute("xmlns:mastodon", NAMESPACE_MASTODON);
1438 $author = self::add_author($doc, $owner);
1439 $entry->appendChild($author);
1441 $title = sprintf("New comment by %s", $owner["nick"]);
1447 * @brief Adds elements to the XML document
1449 * @param object $doc XML document
1450 * @param object $entry Entry element where the content is added
1451 * @param array $item Data of the item that is to be posted
1452 * @param array $owner Contact data of the poster
1453 * @param string $title Title for the post
1454 * @param string $verb The activity verb
1455 * @param bool $complete Add the "status_net" element?
1457 private static function entry_content($doc, $entry, $item, $owner, $title, $verb = "", $complete = true) {
1460 $verb = self::construct_verb($item);
1462 xml::add_element($doc, $entry, "id", $item["uri"]);
1463 xml::add_element($doc, $entry, "title", $title);
1465 $body = self::format_picture_post($item['body']);
1467 if ($item['title'] != "")
1468 $body = "[b]".$item['title']."[/b]\n\n".$body;
1470 $body = bbcode($body, false, false, 7);
1472 xml::add_element($doc, $entry, "content", $body, array("type" => "html"));
1474 xml::add_element($doc, $entry, "link", "", array("rel" => "alternate", "type" => "text/html",
1475 "href" => System::baseUrl()."/display/".$item["guid"]));
1477 if ($complete && ($item["id"] > 0))
1478 xml::add_element($doc, $entry, "status_net", "", array("notice_id" => $item["id"]));
1480 xml::add_element($doc, $entry, "activity:verb", $verb);
1482 xml::add_element($doc, $entry, "published", datetime_convert("UTC","UTC",$item["created"]."+00:00",ATOM_TIME));
1483 xml::add_element($doc, $entry, "updated", datetime_convert("UTC","UTC",$item["edited"]."+00:00",ATOM_TIME));
1487 * @brief Adds the elements at the foot of an entry to the XML document
1489 * @param object $doc XML document
1490 * @param object $entry The entry element where the elements are added
1491 * @param array $item Data of the item that is to be posted
1492 * @param array $owner Contact data of the poster
1495 private static function entry_footer($doc, $entry, $item, $owner, $complete = true) {
1497 $mentioned = array();
1499 if (($item['parent'] != $item['id']) || ($item['parent-uri'] !== $item['uri']) || (($item['thr-parent'] !== '') && ($item['thr-parent'] !== $item['uri']))) {
1500 $parent = q("SELECT `guid`, `author-link`, `owner-link` FROM `item` WHERE `id` = %d", intval($item["parent"]));
1501 $parent_item = (($item['thr-parent']) ? $item['thr-parent'] : $item['parent-uri']);
1503 $thrparent = q("SELECT `guid`, `author-link`, `owner-link`, `plink` FROM `item` WHERE `uid` = %d AND `uri` = '%s'",
1504 intval($owner["uid"]),
1505 dbesc($parent_item));
1507 $mentioned[$thrparent[0]["author-link"]] = $thrparent[0]["author-link"];
1508 $mentioned[$thrparent[0]["owner-link"]] = $thrparent[0]["owner-link"];
1509 $parent_plink = $thrparent[0]["plink"];
1511 $mentioned[$parent[0]["author-link"]] = $parent[0]["author-link"];
1512 $mentioned[$parent[0]["owner-link"]] = $parent[0]["owner-link"];
1513 $parent_plink = System::baseUrl()."/display/".$parent[0]["guid"];
1516 $attributes = array(
1517 "ref" => $parent_item,
1518 "href" => $parent_plink);
1519 xml::add_element($doc, $entry, "thr:in-reply-to", "", $attributes);
1521 $attributes = array(
1523 "href" => $parent_plink);
1524 xml::add_element($doc, $entry, "link", "", $attributes);
1527 if (intval($item["parent"]) > 0) {
1528 $conversation_href = System::baseUrl()."/display/".$owner["nick"]."/".$item["parent"];
1529 $conversation_uri = $conversation_href;
1531 if (isset($parent_item)) {
1532 $r = dba::fetch_first("SELECT `conversation-uri`, `conversation-href` FROM `conversation` WHERE `item-uri` = ?", $parent_item);
1533 if (dbm::is_result($r)) {
1534 if ($r['conversation-uri'] != '') {
1535 $conversation_uri = $r['conversation-uri'];
1537 if ($r['conversation-href'] != '') {
1538 $conversation_href = $r['conversation-href'];
1543 xml::add_element($doc, $entry, "link", "", array("rel" => "ostatus:conversation", "href" => $conversation_href));
1545 $attributes = array(
1546 "href" => $conversation_href,
1547 "local_id" => $item["parent"],
1548 "ref" => $conversation_uri);
1550 xml::add_element($doc, $entry, "ostatus:conversation", $conversation_uri, $attributes);
1553 $tags = item_getfeedtags($item);
1556 foreach ($tags as $t)
1558 $mentioned[$t[1]] = $t[1];
1560 // Make sure that mentions are accepted (GNU Social has problems with mixing HTTP and HTTPS)
1561 $newmentions = array();
1562 foreach ($mentioned AS $mention) {
1563 $newmentions[str_replace("http://", "https://", $mention)] = str_replace("http://", "https://", $mention);
1564 $newmentions[str_replace("https://", "http://", $mention)] = str_replace("https://", "http://", $mention);
1566 $mentioned = $newmentions;
1568 foreach ($mentioned AS $mention) {
1569 $r = q("SELECT `forum`, `prv` FROM `contact` WHERE `uid` = %d AND `nurl` = '%s'",
1570 intval($owner["uid"]),
1571 dbesc(normalise_link($mention)));
1572 if ($r[0]["forum"] || $r[0]["prv"])
1573 xml::add_element($doc, $entry, "link", "", array("rel" => "mentioned",
1574 "ostatus:object-type" => ACTIVITY_OBJ_GROUP,
1575 "href" => $mention));
1577 xml::add_element($doc, $entry, "link", "", array("rel" => "mentioned",
1578 "ostatus:object-type" => ACTIVITY_OBJ_PERSON,
1579 "href" => $mention));
1582 if (!$item["private"]) {
1583 xml::add_element($doc, $entry, "link", "", array("rel" => "ostatus:attention",
1584 "href" => "http://activityschema.org/collection/public"));
1585 xml::add_element($doc, $entry, "link", "", array("rel" => "mentioned",
1586 "ostatus:object-type" => "http://activitystrea.ms/schema/1.0/collection",
1587 "href" => "http://activityschema.org/collection/public"));
1588 xml::add_element($doc, $entry, "mastodon:scope", "public");
1592 foreach ($tags as $t)
1594 xml::add_element($doc, $entry, "category", "", array("term" => $t[2]));
1596 self::get_attachment($doc, $entry, $item);
1598 if ($complete && ($item["id"] > 0)) {
1599 $app = $item["app"];
1603 $attributes = array("local_id" => $item["id"], "source" => $app);
1605 if (isset($parent["id"]))
1606 $attributes["repeat_of"] = $parent["id"];
1608 if ($item["coord"] != "")
1609 xml::add_element($doc, $entry, "georss:point", $item["coord"]);
1611 xml::add_element($doc, $entry, "statusnet:notice_info", "", $attributes);
1616 * @brief Creates the XML feed for a given nickname
1618 * @param App $a The application class
1619 * @param string $owner_nick Nickname of the feed owner
1620 * @param string $last_update Date of the last update
1621 * @param integer $max_items Number of maximum items to fetch
1623 * @return string XML feed
1625 public static function feed(App $a, $owner_nick, &$last_update, $max_items = 300) {
1626 $stamp = microtime(true);
1628 $cachekey = "ostatus:feed:".$owner_nick.":".$last_update;
1630 $previous_created = $last_update;
1632 $result = Cache::get($cachekey);
1633 if (!is_null($result)) {
1634 logger('Feed duration: '.number_format(microtime(true) - $stamp, 3).' - '.$owner_nick.' - '.$previous_created.' (cached)', LOGGER_DEBUG);
1635 $last_update = $result['last_update'];
1636 return $result['feed'];
1639 $r = q("SELECT `contact`.*, `user`.`nickname`, `user`.`timezone`, `user`.`page-flags`
1640 FROM `contact` INNER JOIN `user` ON `user`.`uid` = `contact`.`uid`
1641 WHERE `contact`.`self` AND `user`.`nickname` = '%s' LIMIT 1",
1642 dbesc($owner_nick));
1643 if (!dbm::is_result($r)) {
1649 if (!strlen($last_update)) {
1650 $last_update = 'now -30 days';
1653 $check_date = datetime_convert('UTC','UTC',$last_update,'Y-m-d H:i:s');
1654 $authorid = get_contact($owner["url"], 0);
1656 $items = q("SELECT `item`.*, `item`.`id` AS `item_id` FROM `item` USE INDEX (`uid_contactid_created`)
1657 STRAIGHT_JOIN `thread` ON `thread`.`iid` = `item`.`parent`
1658 WHERE `item`.`uid` = %d AND `item`.`contact-id` = %d AND
1659 `item`.`author-id` = %d AND `item`.`created` > '%s' AND
1660 NOT `item`.`deleted` AND NOT `item`.`private` AND
1661 `thread`.`network` IN ('%s', '%s')
1662 ORDER BY `item`.`created` DESC LIMIT %d",
1663 intval($owner["uid"]), intval($owner["id"]),
1664 intval($authorid), dbesc($check_date),
1665 dbesc(NETWORK_OSTATUS), dbesc(NETWORK_DFRN), intval($max_items));
1667 $doc = new DOMDocument('1.0', 'utf-8');
1668 $doc->formatOutput = true;
1670 $root = self::add_header($doc, $owner);
1672 foreach ($items AS $item) {
1673 if (Config::get('system', 'ostatus_debug')) {
1674 $item['body'] .= '🍼';
1676 $entry = self::entry($doc, $item, $owner);
1677 $root->appendChild($entry);
1679 if ($last_update < $item['created']) {
1680 $last_update = $item['created'];
1684 $feeddata = trim($doc->saveXML());
1686 $msg = array('feed' => $feeddata, 'last_update' => $last_update);
1687 Cache::set($cachekey, $msg, CACHE_QUARTER_HOUR);
1689 logger('Feed duration: '.number_format(microtime(true) - $stamp, 3).' - '.$owner_nick.' - '.$previous_created, LOGGER_DEBUG);
1695 * @brief Creates the XML for a salmon message
1697 * @param array $item Data of the item that is to be posted
1698 * @param array $owner Contact data of the poster
1700 * @return string XML for the salmon
1702 public static function salmon($item,$owner) {
1704 $doc = new DOMDocument('1.0', 'utf-8');
1705 $doc->formatOutput = true;
1707 if (Config::get('system', 'ostatus_debug')) {
1708 $item['body'] .= '🐟';
1711 $entry = self::entry($doc, $item, $owner, true);
1713 $doc->appendChild($entry);
1715 return trim($doc->saveXML());