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 Create an url out of an uri
802 * @param string $href URI in the format "parameter1:parameter1:..."
804 * @return string URL in the format http(s)://....
806 public static function convert_href($href) {
807 $elements = explode(":",$href);
809 if ((count($elements) <= 2) || ($elements[0] != "tag"))
812 $server = explode(",", $elements[1]);
813 $conversation = explode("=", $elements[2]);
815 if ((count($elements) == 4) && ($elements[2] == "post"))
816 return "http://".$server[0]."/notice/".$elements[3];
818 if ((count($conversation) != 2) || ($conversation[1] =="")) {
821 if ($elements[3] == "objectType=thread") {
822 return "http://".$server[0]."/conversation/".$conversation[1];
824 return "http://".$server[0]."/notice/".$conversation[1];
830 * @brief Checks if the current post is a reshare
832 * @param array $item The item array of thw post
834 * @return string The guid if the post is a reshare
836 private static function get_reshared_guid($item) {
837 $body = trim($item["body"]);
839 // Skip if it isn't a pure repeated messages
840 // Does it start with a share?
841 if (strpos($body, "[share") > 0)
844 // Does it end with a share?
845 if (strlen($body) > (strrpos($body, "[/share]") + 8))
848 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$1",$body);
849 // Skip if there is no shared message in there
850 if ($body == $attributes)
854 preg_match("/guid='(.*?)'/ism", $attributes, $matches);
855 if ($matches[1] != "")
858 preg_match('/guid="(.*?)"/ism', $attributes, $matches);
859 if ($matches[1] != "")
866 * @brief Cleans the body of a post if it contains picture links
868 * @param string $body The body
870 * @return string The cleaned body
872 private static function format_picture_post($body) {
873 $siteinfo = get_attached_data($body);
875 if (($siteinfo["type"] == "photo")) {
876 if (isset($siteinfo["preview"]))
877 $preview = $siteinfo["preview"];
879 $preview = $siteinfo["image"];
881 // Is it a remote picture? Then make a smaller preview here
882 $preview = proxy_url($preview, false, PROXY_SIZE_SMALL);
884 // Is it a local picture? Then make it smaller here
885 $preview = str_replace(array("-0.jpg", "-0.png"), array("-2.jpg", "-2.png"), $preview);
886 $preview = str_replace(array("-1.jpg", "-1.png"), array("-2.jpg", "-2.png"), $preview);
888 if (isset($siteinfo["url"]))
889 $url = $siteinfo["url"];
891 $url = $siteinfo["image"];
893 $body = trim($siteinfo["text"])." [url]".$url."[/url]\n[img]".$preview."[/img]";
900 * @brief Adds the header elements to the XML document
902 * @param object $doc XML document
903 * @param array $owner Contact data of the poster
905 * @return object header root element
907 private static function add_header($doc, $owner) {
911 $root = $doc->createElementNS(NAMESPACE_ATOM1, 'feed');
912 $doc->appendChild($root);
914 $root->setAttribute("xmlns:thr", NAMESPACE_THREAD);
915 $root->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
916 $root->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
917 $root->setAttribute("xmlns:media", NAMESPACE_MEDIA);
918 $root->setAttribute("xmlns:poco", NAMESPACE_POCO);
919 $root->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
920 $root->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
921 $root->setAttribute("xmlns:mastodon", NAMESPACE_MASTODON);
923 $attributes = array("uri" => "https://friendi.ca", "version" => FRIENDICA_VERSION."-".DB_UPDATE_VERSION);
924 xml::add_element($doc, $root, "generator", FRIENDICA_PLATFORM, $attributes);
925 xml::add_element($doc, $root, "id", System::baseUrl()."/profile/".$owner["nick"]);
926 xml::add_element($doc, $root, "title", sprintf("%s timeline", $owner["name"]));
927 xml::add_element($doc, $root, "subtitle", sprintf("Updates from %s on %s", $owner["name"], $a->config["sitename"]));
928 xml::add_element($doc, $root, "logo", $owner["photo"]);
929 xml::add_element($doc, $root, "updated", datetime_convert("UTC", "UTC", "now", ATOM_TIME));
931 $author = self::add_author($doc, $owner);
932 $root->appendChild($author);
934 $attributes = array("href" => $owner["url"], "rel" => "alternate", "type" => "text/html");
935 xml::add_element($doc, $root, "link", "", $attributes);
937 /// @TODO We have to find out what this is
938 /// $attributes = array("href" => System::baseUrl()."/sup",
939 /// "rel" => "http://api.friendfeed.com/2008/03#sup",
940 /// "type" => "application/json");
941 /// xml::add_element($doc, $root, "link", "", $attributes);
943 self::hublinks($doc, $root, $owner["nick"]);
945 $attributes = array("href" => System::baseUrl()."/salmon/".$owner["nick"], "rel" => "salmon");
946 xml::add_element($doc, $root, "link", "", $attributes);
948 $attributes = array("href" => System::baseUrl()."/salmon/".$owner["nick"], "rel" => "http://salmon-protocol.org/ns/salmon-replies");
949 xml::add_element($doc, $root, "link", "", $attributes);
951 $attributes = array("href" => System::baseUrl()."/salmon/".$owner["nick"], "rel" => "http://salmon-protocol.org/ns/salmon-mention");
952 xml::add_element($doc, $root, "link", "", $attributes);
954 $attributes = array("href" => System::baseUrl()."/api/statuses/user_timeline/".$owner["nick"].".atom",
955 "rel" => "self", "type" => "application/atom+xml");
956 xml::add_element($doc, $root, "link", "", $attributes);
962 * @brief Add the link to the push hubs to the XML document
964 * @param object $doc XML document
965 * @param object $root XML root element where the hub links are added
967 public static function hublinks($doc, $root, $nick) {
968 $h = System::baseUrl() . '/pubsubhubbub/'.$nick;
969 xml::add_element($doc, $root, "link", "", array("href" => $h, "rel" => "hub"));
973 * @brief Adds attachement data to the XML document
975 * @param object $doc XML document
976 * @param object $root XML root element where the hub links are added
977 * @param array $item Data of the item that is to be posted
979 private static function get_attachment($doc, $root, $item) {
981 $siteinfo = get_attached_data($item["body"]);
983 switch ($siteinfo["type"]) {
985 $imgdata = get_photo_info($siteinfo["image"]);
986 $attributes = array("rel" => "enclosure",
987 "href" => $siteinfo["image"],
988 "type" => $imgdata["mime"],
989 "length" => intval($imgdata["size"]));
990 xml::add_element($doc, $root, "link", "", $attributes);
993 $attributes = array("rel" => "enclosure",
994 "href" => $siteinfo["url"],
995 "type" => "text/html; charset=UTF-8",
997 "title" => $siteinfo["title"]);
998 xml::add_element($doc, $root, "link", "", $attributes);
1004 if (!Config::get('system', 'ostatus_not_attach_preview') && ($siteinfo["type"] != "photo") && isset($siteinfo["image"])) {
1005 $imgdata = get_photo_info($siteinfo["image"]);
1006 $attributes = array("rel" => "enclosure",
1007 "href" => $siteinfo["image"],
1008 "type" => $imgdata["mime"],
1009 "length" => intval($imgdata["size"]));
1011 xml::add_element($doc, $root, "link", "", $attributes);
1014 $arr = explode('[/attach],', $item['attach']);
1016 foreach ($arr as $r) {
1018 $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"|', $r, $matches);
1020 $attributes = array("rel" => "enclosure",
1021 "href" => $matches[1],
1022 "type" => $matches[3]);
1024 if (intval($matches[2])) {
1025 $attributes["length"] = intval($matches[2]);
1027 if (trim($matches[4]) != "") {
1028 $attributes["title"] = trim($matches[4]);
1030 xml::add_element($doc, $root, "link", "", $attributes);
1037 * @brief Adds the author element to the XML document
1039 * @param object $doc XML document
1040 * @param array $owner Contact data of the poster
1042 * @return object author element
1044 private static function add_author($doc, $owner) {
1046 $r = q("SELECT `homepage`, `publish` FROM `profile` WHERE `uid` = %d AND `is-default` LIMIT 1", intval($owner["uid"]));
1047 if (dbm::is_result($r)) {
1050 $author = $doc->createElement("author");
1051 xml::add_element($doc, $author, "id", $owner["url"]);
1052 xml::add_element($doc, $author, "activity:object-type", ACTIVITY_OBJ_PERSON);
1053 xml::add_element($doc, $author, "uri", $owner["url"]);
1054 xml::add_element($doc, $author, "name", $owner["nick"]);
1055 xml::add_element($doc, $author, "email", $owner["addr"]);
1056 xml::add_element($doc, $author, "summary", bbcode($owner["about"], false, false, 7));
1058 $attributes = array("rel" => "alternate", "type" => "text/html", "href" => $owner["url"]);
1059 xml::add_element($doc, $author, "link", "", $attributes);
1061 $attributes = array(
1063 "type" => "image/jpeg", // To-Do?
1064 "media:width" => 175,
1065 "media:height" => 175,
1066 "href" => $owner["photo"]);
1067 xml::add_element($doc, $author, "link", "", $attributes);
1069 if (isset($owner["thumb"])) {
1070 $attributes = array(
1072 "type" => "image/jpeg", // To-Do?
1073 "media:width" => 80,
1074 "media:height" => 80,
1075 "href" => $owner["thumb"]);
1076 xml::add_element($doc, $author, "link", "", $attributes);
1079 xml::add_element($doc, $author, "poco:preferredUsername", $owner["nick"]);
1080 xml::add_element($doc, $author, "poco:displayName", $owner["name"]);
1081 xml::add_element($doc, $author, "poco:note", bbcode($owner["about"], false, false, 7));
1083 if (trim($owner["location"]) != "") {
1084 $element = $doc->createElement("poco:address");
1085 xml::add_element($doc, $element, "poco:formatted", $owner["location"]);
1086 $author->appendChild($element);
1089 if (trim($profile["homepage"]) != "") {
1090 $urls = $doc->createElement("poco:urls");
1091 xml::add_element($doc, $urls, "poco:type", "homepage");
1092 xml::add_element($doc, $urls, "poco:value", $profile["homepage"]);
1093 xml::add_element($doc, $urls, "poco:primary", "true");
1094 $author->appendChild($urls);
1097 if (count($profile)) {
1098 xml::add_element($doc, $author, "followers", "", array("url" => System::baseUrl()."/viewcontacts/".$owner["nick"]));
1099 xml::add_element($doc, $author, "statusnet:profile_info", "", array("local_id" => $owner["uid"]));
1102 if ($profile["publish"]) {
1103 xml::add_element($doc, $author, "mastodon:scope", "public");
1109 * @TODO Picture attachments should look like this:
1110 * <a href="https://status.pirati.ca/attachment/572819" title="https://status.pirati.ca/file/heluecht-20151202T222602-rd3u49p.gif"
1111 * class="attachment thumbnail" id="attachment-572819" rel="nofollow external">https://status.pirati.ca/attachment/572819</a>
1116 * @brief Returns the given activity if present - otherwise returns the "post" activity
1118 * @param array $item Data of the item that is to be posted
1120 * @return string activity
1122 private static function construct_verb($item) {
1124 return $item['verb'];
1125 return ACTIVITY_POST;
1129 * @brief Returns the given object type if present - otherwise returns the "note" object type
1131 * @param array $item Data of the item that is to be posted
1133 * @return string Object type
1135 private static function construct_objecttype($item) {
1136 if (in_array($item['object-type'], array(ACTIVITY_OBJ_NOTE, ACTIVITY_OBJ_COMMENT)))
1137 return $item['object-type'];
1138 return ACTIVITY_OBJ_NOTE;
1142 * @brief Adds an entry element to the XML document
1144 * @param object $doc XML document
1145 * @param array $item Data of the item that is to be posted
1146 * @param array $owner Contact data of the poster
1147 * @param bool $toplevel
1149 * @return object Entry element
1151 private static function entry($doc, $item, $owner, $toplevel = false) {
1152 $repeated_guid = self::get_reshared_guid($item);
1153 if ($repeated_guid != "")
1154 $xml = self::reshare_entry($doc, $item, $owner, $repeated_guid, $toplevel);
1159 if ($item["verb"] == ACTIVITY_LIKE) {
1160 return self::like_entry($doc, $item, $owner, $toplevel);
1161 } elseif (in_array($item["verb"], array(ACTIVITY_FOLLOW, NAMESPACE_OSTATUS."/unfollow"))) {
1162 return self::follow_entry($doc, $item, $owner, $toplevel);
1164 return self::note_entry($doc, $item, $owner, $toplevel);
1169 * @brief Adds a source entry to the XML document
1171 * @param object $doc XML document
1172 * @param array $contact Array of the contact that is added
1174 * @return object Source element
1176 private static function source_entry($doc, $contact) {
1177 $source = $doc->createElement("source");
1178 xml::add_element($doc, $source, "id", $contact["poll"]);
1179 xml::add_element($doc, $source, "title", $contact["name"]);
1180 xml::add_element($doc, $source, "link", "", array("rel" => "alternate",
1181 "type" => "text/html",
1182 "href" => $contact["alias"]));
1183 xml::add_element($doc, $source, "link", "", array("rel" => "self",
1184 "type" => "application/atom+xml",
1185 "href" => $contact["poll"]));
1186 xml::add_element($doc, $source, "icon", $contact["photo"]);
1187 xml::add_element($doc, $source, "updated", datetime_convert("UTC","UTC",$contact["success_update"]."+00:00",ATOM_TIME));
1193 * @brief Fetches contact data from the contact or the gcontact table
1195 * @param string $url URL of the contact
1196 * @param array $owner Contact data of the poster
1198 * @return array Contact array
1200 private static function contact_entry($url, $owner) {
1202 $r = q("SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` IN (0, %d) ORDER BY `uid` DESC LIMIT 1",
1203 dbesc(normalise_link($url)), intval($owner["uid"]));
1204 if (dbm::is_result($r)) {
1206 $contact["uid"] = -1;
1209 if (!dbm::is_result($r)) {
1210 $r = q("SELECT * FROM `gcontact` WHERE `nurl` = '%s' LIMIT 1",
1211 dbesc(normalise_link($url)));
1212 if (dbm::is_result($r)) {
1214 $contact["uid"] = -1;
1215 $contact["success_update"] = $contact["updated"];
1219 if (!dbm::is_result($r))
1222 if (!isset($contact["poll"])) {
1223 $data = probe_url($url);
1224 $contact["poll"] = $data["poll"];
1226 if (!$contact["alias"])
1227 $contact["alias"] = $data["alias"];
1230 if (!isset($contact["alias"]))
1231 $contact["alias"] = $contact["url"];
1237 * @brief Adds an entry element with reshared content
1239 * @param object $doc XML document
1240 * @param array $item Data of the item that is to be posted
1241 * @param array $owner Contact data of the poster
1242 * @param $repeated_guid
1243 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1245 * @return object Entry element
1247 private static function reshare_entry($doc, $item, $owner, $repeated_guid, $toplevel) {
1249 if (($item["id"] != $item["parent"]) && (normalise_link($item["author-link"]) != normalise_link($owner["url"]))) {
1250 logger("OStatus entry is from author ".$owner["url"]." - not from ".$item["author-link"].". Quitting.", LOGGER_DEBUG);
1253 $title = self::entry_header($doc, $entry, $owner, $toplevel);
1255 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' AND NOT `private` AND `network` IN ('%s', '%s', '%s') LIMIT 1",
1256 intval($owner["uid"]), dbesc($repeated_guid),
1257 dbesc(NETWORK_DFRN), dbesc(NETWORK_DIASPORA), dbesc(NETWORK_OSTATUS));
1258 if (dbm::is_result($r)) {
1259 $repeated_item = $r[0];
1263 $contact = self::contact_entry($repeated_item['author-link'], $owner);
1265 $parent_item = (($item['thr-parent']) ? $item['thr-parent'] : $item['parent-uri']);
1267 $title = $owner["nick"]." repeated a notice by ".$contact["nick"];
1269 self::entry_content($doc, $entry, $item, $owner, $title, ACTIVITY_SHARE, false);
1271 $as_object = $doc->createElement("activity:object");
1273 xml::add_element($doc, $as_object, "activity:object-type", NAMESPACE_ACTIVITY_SCHEMA."activity");
1275 self::entry_content($doc, $as_object, $repeated_item, $owner, "", "", false);
1277 $author = self::add_author($doc, $contact);
1278 $as_object->appendChild($author);
1280 $as_object2 = $doc->createElement("activity:object");
1282 xml::add_element($doc, $as_object2, "activity:object-type", self::construct_objecttype($repeated_item));
1284 $title = sprintf("New comment by %s", $contact["nick"]);
1286 self::entry_content($doc, $as_object2, $repeated_item, $owner, $title);
1288 $as_object->appendChild($as_object2);
1290 self::entry_footer($doc, $as_object, $item, $owner, false);
1292 $source = self::source_entry($doc, $contact);
1294 $as_object->appendChild($source);
1296 $entry->appendChild($as_object);
1298 self::entry_footer($doc, $entry, $item, $owner);
1304 * @brief Adds an entry element with a "like"
1306 * @param object $doc XML document
1307 * @param array $item Data of the item that is to be posted
1308 * @param array $owner Contact data of the poster
1309 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1311 * @return object Entry element with "like"
1313 private static function like_entry($doc, $item, $owner, $toplevel) {
1315 if (($item["id"] != $item["parent"]) && (normalise_link($item["author-link"]) != normalise_link($owner["url"]))) {
1316 logger("OStatus entry is from author ".$owner["url"]." - not from ".$item["author-link"].". Quitting.", LOGGER_DEBUG);
1319 $title = self::entry_header($doc, $entry, $owner, $toplevel);
1321 $verb = NAMESPACE_ACTIVITY_SCHEMA."favorite";
1322 self::entry_content($doc, $entry, $item, $owner, "Favorite", $verb, false);
1324 $as_object = $doc->createElement("activity:object");
1326 $parent = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d",
1327 dbesc($item["thr-parent"]), intval($item["uid"]));
1328 $parent_item = (($item['thr-parent']) ? $item['thr-parent'] : $item['parent-uri']);
1330 xml::add_element($doc, $as_object, "activity:object-type", self::construct_objecttype($parent[0]));
1332 self::entry_content($doc, $as_object, $parent[0], $owner, "New entry");
1334 $entry->appendChild($as_object);
1336 self::entry_footer($doc, $entry, $item, $owner);
1342 * @brief Adds the person object element to the XML document
1344 * @param object $doc XML document
1345 * @param array $owner Contact data of the poster
1346 * @param array $contact Contact data of the target
1348 * @return object author element
1350 private static function add_person_object($doc, $owner, $contact) {
1352 $object = $doc->createElement("activity:object");
1353 xml::add_element($doc, $object, "activity:object-type", ACTIVITY_OBJ_PERSON);
1355 if ($contact['network'] == NETWORK_PHANTOM) {
1356 xml::add_element($doc, $object, "id", $contact['url']);
1360 xml::add_element($doc, $object, "id", $contact["alias"]);
1361 xml::add_element($doc, $object, "title", $contact["nick"]);
1363 $attributes = array("rel" => "alternate", "type" => "text/html", "href" => $contact["url"]);
1364 xml::add_element($doc, $object, "link", "", $attributes);
1366 $attributes = array(
1368 "type" => "image/jpeg", // To-Do?
1369 "media:width" => 175,
1370 "media:height" => 175,
1371 "href" => $contact["photo"]);
1372 xml::add_element($doc, $object, "link", "", $attributes);
1374 xml::add_element($doc, $object, "poco:preferredUsername", $contact["nick"]);
1375 xml::add_element($doc, $object, "poco:displayName", $contact["name"]);
1377 if (trim($contact["location"]) != "") {
1378 $element = $doc->createElement("poco:address");
1379 xml::add_element($doc, $element, "poco:formatted", $contact["location"]);
1380 $object->appendChild($element);
1387 * @brief Adds a follow/unfollow entry element
1389 * @param object $doc XML document
1390 * @param array $item Data of the follow/unfollow message
1391 * @param array $owner Contact data of the poster
1392 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1394 * @return object Entry element
1396 private static function follow_entry($doc, $item, $owner, $toplevel) {
1398 $item["id"] = $item["parent"] = 0;
1399 $item["created"] = $item["edited"] = date("c");
1400 $item["private"] = true;
1402 $contact = Probe::uri($item['follow']);
1404 if ($contact['alias'] == '') {
1405 $contact['alias'] = $contact["url"];
1407 $item['follow'] = $contact['alias'];
1410 $r = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `nurl` = '%s'",
1411 intval($owner['uid']), dbesc(normalise_link($contact["url"])));
1413 if (dbm::is_result($r)) {
1414 $connect_id = $r[0]['id'];
1419 if ($item['verb'] == ACTIVITY_FOLLOW) {
1420 $message = t('%s is now following %s.');
1421 $title = t('following');
1422 $action = "subscription";
1424 $message = t('%s stopped following %s.');
1425 $title = t('stopped following');
1426 $action = "unfollow";
1429 $item["uri"] = $item['parent-uri'] = $item['thr-parent'] =
1430 'tag:'.get_app()->get_hostname().
1431 ','.date('Y-m-d').':'.$action.':'.$owner['uid'].
1432 ':person:'.$connect_id.':'.$item['created'];
1434 $item["body"] = sprintf($message, $owner["nick"], $contact["nick"]);
1436 self::entry_header($doc, $entry, $owner, $toplevel);
1438 self::entry_content($doc, $entry, $item, $owner, $title);
1440 $object = self::add_person_object($doc, $owner, $contact);
1441 $entry->appendChild($object);
1443 self::entry_footer($doc, $entry, $item, $owner);
1449 * @brief Adds a regular entry element
1451 * @param object $doc XML document
1452 * @param array $item Data of the item that is to be posted
1453 * @param array $owner Contact data of the poster
1454 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1456 * @return object Entry element
1458 private static function note_entry($doc, $item, $owner, $toplevel) {
1460 if (($item["id"] != $item["parent"]) && (normalise_link($item["author-link"]) != normalise_link($owner["url"]))) {
1461 logger("OStatus entry is from author ".$owner["url"]." - not from ".$item["author-link"].". Quitting.", LOGGER_DEBUG);
1464 $title = self::entry_header($doc, $entry, $owner, $toplevel);
1466 xml::add_element($doc, $entry, "activity:object-type", ACTIVITY_OBJ_NOTE);
1468 self::entry_content($doc, $entry, $item, $owner, $title);
1470 self::entry_footer($doc, $entry, $item, $owner);
1476 * @brief Adds a header element to the XML document
1478 * @param object $doc XML document
1479 * @param object $entry The entry element where the elements are added
1480 * @param array $owner Contact data of the poster
1481 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1483 * @return string The title for the element
1485 private static function entry_header($doc, &$entry, $owner, $toplevel) {
1486 /// @todo Check if this title stuff is really needed (I guess not)
1488 $entry = $doc->createElement("entry");
1489 $title = sprintf("New note by %s", $owner["nick"]);
1491 $entry = $doc->createElementNS(NAMESPACE_ATOM1, "entry");
1493 $entry->setAttribute("xmlns:thr", NAMESPACE_THREAD);
1494 $entry->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
1495 $entry->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
1496 $entry->setAttribute("xmlns:media", NAMESPACE_MEDIA);
1497 $entry->setAttribute("xmlns:poco", NAMESPACE_POCO);
1498 $entry->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
1499 $entry->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
1500 $entry->setAttribute("xmlns:mastodon", NAMESPACE_MASTODON);
1502 $author = self::add_author($doc, $owner);
1503 $entry->appendChild($author);
1505 $title = sprintf("New comment by %s", $owner["nick"]);
1511 * @brief Adds elements to the XML document
1513 * @param object $doc XML document
1514 * @param object $entry Entry element where the content is added
1515 * @param array $item Data of the item that is to be posted
1516 * @param array $owner Contact data of the poster
1517 * @param string $title Title for the post
1518 * @param string $verb The activity verb
1519 * @param bool $complete Add the "status_net" element?
1521 private static function entry_content($doc, $entry, $item, $owner, $title, $verb = "", $complete = true) {
1524 $verb = self::construct_verb($item);
1526 xml::add_element($doc, $entry, "id", $item["uri"]);
1527 xml::add_element($doc, $entry, "title", $title);
1529 $body = self::format_picture_post($item['body']);
1531 if ($item['title'] != "")
1532 $body = "[b]".$item['title']."[/b]\n\n".$body;
1534 $body = bbcode($body, false, false, 7);
1536 xml::add_element($doc, $entry, "content", $body, array("type" => "html"));
1538 xml::add_element($doc, $entry, "link", "", array("rel" => "alternate", "type" => "text/html",
1539 "href" => System::baseUrl()."/display/".$item["guid"]));
1541 if ($complete && ($item["id"] > 0))
1542 xml::add_element($doc, $entry, "status_net", "", array("notice_id" => $item["id"]));
1544 xml::add_element($doc, $entry, "activity:verb", $verb);
1546 xml::add_element($doc, $entry, "published", datetime_convert("UTC","UTC",$item["created"]."+00:00",ATOM_TIME));
1547 xml::add_element($doc, $entry, "updated", datetime_convert("UTC","UTC",$item["edited"]."+00:00",ATOM_TIME));
1551 * @brief Adds the elements at the foot of an entry to the XML document
1553 * @param object $doc XML document
1554 * @param object $entry The entry element where the elements are added
1555 * @param array $item Data of the item that is to be posted
1556 * @param array $owner Contact data of the poster
1559 private static function entry_footer($doc, $entry, $item, $owner, $complete = true) {
1561 $mentioned = array();
1563 if (($item['parent'] != $item['id']) || ($item['parent-uri'] !== $item['uri']) || (($item['thr-parent'] !== '') && ($item['thr-parent'] !== $item['uri']))) {
1564 $parent = q("SELECT `guid`, `author-link`, `owner-link` FROM `item` WHERE `id` = %d", intval($item["parent"]));
1565 $parent_item = (($item['thr-parent']) ? $item['thr-parent'] : $item['parent-uri']);
1567 $thrparent = q("SELECT `guid`, `author-link`, `owner-link`, `plink` FROM `item` WHERE `uid` = %d AND `uri` = '%s'",
1568 intval($owner["uid"]),
1569 dbesc($parent_item));
1571 $mentioned[$thrparent[0]["author-link"]] = $thrparent[0]["author-link"];
1572 $mentioned[$thrparent[0]["owner-link"]] = $thrparent[0]["owner-link"];
1573 $parent_plink = $thrparent[0]["plink"];
1575 $mentioned[$parent[0]["author-link"]] = $parent[0]["author-link"];
1576 $mentioned[$parent[0]["owner-link"]] = $parent[0]["owner-link"];
1577 $parent_plink = System::baseUrl()."/display/".$parent[0]["guid"];
1580 $attributes = array(
1581 "ref" => $parent_item,
1582 "href" => $parent_plink);
1583 xml::add_element($doc, $entry, "thr:in-reply-to", "", $attributes);
1585 $attributes = array(
1587 "href" => $parent_plink);
1588 xml::add_element($doc, $entry, "link", "", $attributes);
1591 if (intval($item["parent"]) > 0) {
1592 $conversation_href = System::baseUrl()."/display/".$owner["nick"]."/".$item["parent"];
1593 $conversation_uri = $conversation_href;
1595 if (isset($parent_item)) {
1596 $r = dba::fetch_first("SELECT `conversation-uri`, `conversation-href` FROM `conversation` WHERE `item-uri` = ?", $parent_item);
1597 if (dbm::is_result($r)) {
1598 if ($r['conversation-uri'] != '') {
1599 $conversation_uri = $r['conversation-uri'];
1601 if ($r['conversation-href'] != '') {
1602 $conversation_href = $r['conversation-href'];
1607 xml::add_element($doc, $entry, "link", "", array("rel" => "ostatus:conversation", "href" => $conversation_href));
1609 $attributes = array(
1610 "href" => $conversation_href,
1611 "local_id" => $item["parent"],
1612 "ref" => $conversation_uri);
1614 xml::add_element($doc, $entry, "ostatus:conversation", $conversation_uri, $attributes);
1617 $tags = item_getfeedtags($item);
1620 foreach ($tags as $t)
1622 $mentioned[$t[1]] = $t[1];
1624 // Make sure that mentions are accepted (GNU Social has problems with mixing HTTP and HTTPS)
1625 $newmentions = array();
1626 foreach ($mentioned AS $mention) {
1627 $newmentions[str_replace("http://", "https://", $mention)] = str_replace("http://", "https://", $mention);
1628 $newmentions[str_replace("https://", "http://", $mention)] = str_replace("https://", "http://", $mention);
1630 $mentioned = $newmentions;
1632 foreach ($mentioned AS $mention) {
1633 $r = q("SELECT `forum`, `prv` FROM `contact` WHERE `uid` = %d AND `nurl` = '%s'",
1634 intval($owner["uid"]),
1635 dbesc(normalise_link($mention)));
1636 if ($r[0]["forum"] || $r[0]["prv"])
1637 xml::add_element($doc, $entry, "link", "", array("rel" => "mentioned",
1638 "ostatus:object-type" => ACTIVITY_OBJ_GROUP,
1639 "href" => $mention));
1641 xml::add_element($doc, $entry, "link", "", array("rel" => "mentioned",
1642 "ostatus:object-type" => ACTIVITY_OBJ_PERSON,
1643 "href" => $mention));
1646 if (!$item["private"]) {
1647 xml::add_element($doc, $entry, "link", "", array("rel" => "ostatus:attention",
1648 "href" => "http://activityschema.org/collection/public"));
1649 xml::add_element($doc, $entry, "link", "", array("rel" => "mentioned",
1650 "ostatus:object-type" => "http://activitystrea.ms/schema/1.0/collection",
1651 "href" => "http://activityschema.org/collection/public"));
1652 xml::add_element($doc, $entry, "mastodon:scope", "public");
1656 foreach ($tags as $t)
1658 xml::add_element($doc, $entry, "category", "", array("term" => $t[2]));
1660 self::get_attachment($doc, $entry, $item);
1662 if ($complete && ($item["id"] > 0)) {
1663 $app = $item["app"];
1667 $attributes = array("local_id" => $item["id"], "source" => $app);
1669 if (isset($parent["id"]))
1670 $attributes["repeat_of"] = $parent["id"];
1672 if ($item["coord"] != "")
1673 xml::add_element($doc, $entry, "georss:point", $item["coord"]);
1675 xml::add_element($doc, $entry, "statusnet:notice_info", "", $attributes);
1680 * @brief Creates the XML feed for a given nickname
1682 * @param App $a The application class
1683 * @param string $owner_nick Nickname of the feed owner
1684 * @param string $last_update Date of the last update
1685 * @param integer $max_items Number of maximum items to fetch
1687 * @return string XML feed
1689 public static function feed(App $a, $owner_nick, &$last_update, $max_items = 300) {
1690 $stamp = microtime(true);
1692 $cachekey = "ostatus:feed:".$owner_nick.":".$last_update;
1694 $previous_created = $last_update;
1696 $result = Cache::get($cachekey);
1697 if (!is_null($result)) {
1698 logger('Feed duration: '.number_format(microtime(true) - $stamp, 3).' - '.$owner_nick.' - '.$previous_created.' (cached)', LOGGER_DEBUG);
1699 $last_update = $result['last_update'];
1700 return $result['feed'];
1703 $r = q("SELECT `contact`.*, `user`.`nickname`, `user`.`timezone`, `user`.`page-flags`
1704 FROM `contact` INNER JOIN `user` ON `user`.`uid` = `contact`.`uid`
1705 WHERE `contact`.`self` AND `user`.`nickname` = '%s' LIMIT 1",
1706 dbesc($owner_nick));
1707 if (!dbm::is_result($r)) {
1713 if (!strlen($last_update)) {
1714 $last_update = 'now -30 days';
1717 $check_date = datetime_convert('UTC','UTC',$last_update,'Y-m-d H:i:s');
1718 $authorid = get_contact($owner["url"], 0);
1720 $items = q("SELECT `item`.*, `item`.`id` AS `item_id` FROM `item` USE INDEX (`uid_contactid_created`)
1721 STRAIGHT_JOIN `thread` ON `thread`.`iid` = `item`.`parent`
1722 WHERE `item`.`uid` = %d AND `item`.`contact-id` = %d AND
1723 `item`.`author-id` = %d AND `item`.`created` > '%s' AND
1724 NOT `item`.`deleted` AND NOT `item`.`private` AND
1725 `thread`.`network` IN ('%s', '%s')
1726 ORDER BY `item`.`created` DESC LIMIT %d",
1727 intval($owner["uid"]), intval($owner["id"]),
1728 intval($authorid), dbesc($check_date),
1729 dbesc(NETWORK_OSTATUS), dbesc(NETWORK_DFRN), intval($max_items));
1731 $doc = new DOMDocument('1.0', 'utf-8');
1732 $doc->formatOutput = true;
1734 $root = self::add_header($doc, $owner);
1736 foreach ($items AS $item) {
1737 if (Config::get('system', 'ostatus_debug')) {
1738 $item['body'] .= '🍼';
1740 $entry = self::entry($doc, $item, $owner);
1741 $root->appendChild($entry);
1743 if ($last_update < $item['created']) {
1744 $last_update = $item['created'];
1748 $feeddata = trim($doc->saveXML());
1750 $msg = array('feed' => $feeddata, 'last_update' => $last_update);
1751 Cache::set($cachekey, $msg, CACHE_QUARTER_HOUR);
1753 logger('Feed duration: '.number_format(microtime(true) - $stamp, 3).' - '.$owner_nick.' - '.$previous_created, LOGGER_DEBUG);
1759 * @brief Creates the XML for a salmon message
1761 * @param array $item Data of the item that is to be posted
1762 * @param array $owner Contact data of the poster
1764 * @return string XML for the salmon
1766 public static function salmon($item,$owner) {
1768 $doc = new DOMDocument('1.0', 'utf-8');
1769 $doc->formatOutput = true;
1771 if (Config::get('system', 'ostatus_debug')) {
1772 $item['body'] .= '🐟';
1775 $entry = self::entry($doc, $item, $owner, true);
1777 $doc->appendChild($entry);
1779 return trim($doc->saveXML());