3 * @file include/ostatus.php
7 use Friendica\Core\Config;
8 use Friendica\Network\Probe;
10 require_once 'include/Contact.php';
11 require_once 'include/threads.php';
12 require_once 'include/html2bbcode.php';
13 require_once 'include/bbcode.php';
14 require_once 'include/items.php';
15 require_once 'mod/share.php';
16 require_once 'include/enotify.php';
17 require_once 'include/socgraph.php';
18 require_once 'include/Photo.php';
19 require_once 'include/probe.php';
20 require_once 'include/follow.php';
21 require_once 'include/api.php';
22 require_once 'mod/proxy.php';
23 require_once 'include/xml.php';
24 require_once 'include/cache.php';
27 * @brief This class contain functions for the OStatus protocol
31 const OSTATUS_DEFAULT_POLL_INTERVAL = 30; // given in minutes
32 const OSTATUS_DEFAULT_POLL_TIMEFRAME = 1440; // given in minutes
33 const OSTATUS_DEFAULT_POLL_TIMEFRAME_MENTIONS = 14400; // given in minutes
36 * @brief Fetches author data
38 * @param object $xpath The xpath object
39 * @param object $context The xml context of the author detals
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
260 * @param array $hub Called by reference, returns the fetched hub data
262 public static function import($xml,$importer,&$contact, &$hub) {
263 /// @todo this function is too long. It has to be split in many parts
265 logger("Import OStatus message", LOGGER_DEBUG);
270 //$tempfile = tempnam(get_temppath(), "import");
271 //file_put_contents($tempfile, $xml);
273 $doc = new DOMDocument();
274 @$doc->loadXML($xml);
276 $xpath = new DomXPath($doc);
277 $xpath->registerNamespace('atom', NAMESPACE_ATOM1);
278 $xpath->registerNamespace('thr', NAMESPACE_THREAD);
279 $xpath->registerNamespace('georss', NAMESPACE_GEORSS);
280 $xpath->registerNamespace('activity', NAMESPACE_ACTIVITY);
281 $xpath->registerNamespace('media', NAMESPACE_MEDIA);
282 $xpath->registerNamespace('poco', NAMESPACE_POCO);
283 $xpath->registerNamespace('ostatus', NAMESPACE_OSTATUS);
284 $xpath->registerNamespace('statusnet', NAMESPACE_STATUSNET);
287 $hub_attributes = $xpath->query("/atom:feed/atom:link[@rel='hub']")->item(0)->attributes;
288 if (is_object($hub_attributes)) {
289 foreach ($hub_attributes AS $hub_attribute) {
290 if ($hub_attribute->name == "href") {
291 $hub = $hub_attribute->textContent;
292 logger("Found hub ".$hub, LOGGER_DEBUG);
297 $header["uid"] = $importer["uid"];
298 $header["network"] = NETWORK_OSTATUS;
299 $header["type"] = "remote";
301 $header["origin"] = 0;
302 $header["gravity"] = GRAVITY_PARENT;
304 // it could either be a received post or a post we fetched by ourselves
305 // depending on that, the first node is different
306 $first_child = $doc->firstChild->tagName;
308 if ($first_child == "feed") {
309 $entries = $xpath->query('/atom:feed/atom:entry');
310 $header["protocol"] = PROTOCOL_OSTATUS_FEED;
312 $entries = $xpath->query('/atom:entry');
313 $header["protocol"] = PROTOCOL_OSTATUS_SALMON;
316 $conversationlist = array();
319 // Reverse the order of the entries
320 $entrylist = array();
322 foreach ($entries AS $entry) {
323 $entrylist[] = $entry;
325 foreach (array_reverse($entrylist) AS $entry) {
330 if ($first_child == "feed") {
331 $author = self::fetchauthor($xpath, $doc->firstChild, $importer, $contact, false);
333 $author = self::fetchauthor($xpath, $entry, $importer, $contact, false);
335 $value = $xpath->evaluate('atom:author/poco:preferredUsername/text()', $context)->item(0)->nodeValue;
339 $nickname = $author["author-name"];
341 $item = array_merge($header, $author);
344 $item["uri"] = $xpath->query('atom:id/text()', $entry)->item(0)->nodeValue;
346 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s'",
347 intval($importer["uid"]), dbesc($item["uri"]));
348 if (dbm::is_result($r)) {
349 logger("Item with uri ".$item["uri"]." for user ".$importer["uid"]." already existed under id ".$r[0]["id"], LOGGER_DEBUG);
353 $item["body"] = add_page_info_to_body(html2bbcode($xpath->query('atom:content/text()', $entry)->item(0)->nodeValue));
354 $item["object-type"] = $xpath->query('activity:object-type/text()', $entry)->item(0)->nodeValue;
355 $item["verb"] = $xpath->query('activity:verb/text()', $entry)->item(0)->nodeValue;
357 // Mastodon Content Warning
358 if (($item["verb"] == ACTIVITY_POST) && $xpath->evaluate('boolean(atom:summary)', $entry)) {
359 $clear_text = $xpath->query('atom:summary/text()', $entry)->item(0)->nodeValue;
361 $item["body"] = html2bbcode($clear_text) . '[spoiler]' . $item["body"] . '[/spoiler]';
364 if (($item["object-type"] == ACTIVITY_OBJ_BOOKMARK) || ($item["object-type"] == ACTIVITY_OBJ_EVENT)) {
365 $item["title"] = $xpath->query('atom:title/text()', $entry)->item(0)->nodeValue;
366 $item["body"] = $xpath->query('atom:summary/text()', $entry)->item(0)->nodeValue;
367 } elseif ($item["object-type"] == ACTIVITY_OBJ_QUESTION) {
368 $item["title"] = $xpath->query('atom:title/text()', $entry)->item(0)->nodeValue;
370 $item["source"] = $xml;
374 if ($item["verb"] == "qvitter-delete-notice" || $item["verb"] == ACTIVITY_DELETE) {
375 // ignore "Delete" messages (by now)
376 logger("Ignore delete message ".print_r($item, true));
380 if ($item["verb"] == ACTIVITY_JOIN) {
381 // ignore "Join" messages
382 logger("Ignore join message ".print_r($item, true));
386 if ($item["verb"] == ACTIVITY_FOLLOW) {
387 new_follower($importer, $contact, $item, $nickname);
391 if ($item["verb"] == NAMESPACE_OSTATUS."/unfollow") {
392 lose_follower($importer, $contact, $item, $dummy);
396 if ($item["verb"] == ACTIVITY_FAVORITE) {
397 $orig_uri = $xpath->query("activity:object/atom:id", $entry)->item(0)->nodeValue;
398 logger("Favorite ".$orig_uri." ".print_r($item, true));
400 $item["verb"] = ACTIVITY_LIKE;
401 $item["parent-uri"] = $orig_uri;
402 $item["gravity"] = GRAVITY_LIKE;
405 if ($item["verb"] == NAMESPACE_OSTATUS."/unfavorite") {
406 // Ignore "Unfavorite" message
407 logger("Ignore unfavorite message ".print_r($item, true));
411 // http://activitystrea.ms/schema/1.0/rsvp-yes
412 if (!in_array($item["verb"], array(ACTIVITY_POST, ACTIVITY_LIKE, ACTIVITY_SHARE))) {
413 logger("Unhandled verb ".$item["verb"]." ".print_r($item, true));
415 $item["created"] = $xpath->query('atom:published/text()', $entry)->item(0)->nodeValue;
416 $item["edited"] = $xpath->query('atom:updated/text()', $entry)->item(0)->nodeValue;
417 $conversation = $xpath->query('ostatus:conversation/text()', $entry)->item(0)->nodeValue;
418 $item['conversation-uri'] = $conversation;
420 $conv = $xpath->query('ostatus:conversation', $entry);
421 if (is_object($conv->item(0))) {
422 foreach ($conv->item(0)->attributes AS $attributes) {
423 if ($attributes->name == "ref") {
424 $item['conversation-uri'] = $attributes->textContent;
426 if ($attributes->name == "href") {
427 $item['conversation-href'] = $attributes->textContent;
434 $inreplyto = $xpath->query('thr:in-reply-to', $entry);
435 if (is_object($inreplyto->item(0))) {
436 foreach ($inreplyto->item(0)->attributes AS $attributes) {
437 if ($attributes->name == "ref") {
438 $item["parent-uri"] = $attributes->textContent;
440 if ($attributes->name == "href") {
441 $related = $attributes->textContent;
446 $georsspoint = $xpath->query('georss:point', $entry);
448 $item["coord"] = $georsspoint->item(0)->nodeValue;
450 $categories = $xpath->query('atom:category', $entry);
452 foreach ($categories AS $category) {
453 foreach ($category->attributes AS $attributes) {
454 if ($attributes->name == "term") {
455 $term = $attributes->textContent;
456 if (strlen($item["tag"])) {
459 $item["tag"] .= "#[url=".App::get_baseurl()."/search?tag=".$term."]".$term."[/url]";
468 $links = $xpath->query('atom:link', $entry);
470 foreach ($links AS $link) {
471 $attribute = self::read_attributes($link);
473 if (($attribute['rel'] != "") && ($attribute['href'] != "")) {
474 switch ($attribute['rel']) {
476 $item["plink"] = $attribute['href'];
477 if (($item["object-type"] == ACTIVITY_OBJ_QUESTION) ||
478 ($item["object-type"] == ACTIVITY_OBJ_EVENT)) {
479 $item["body"] .= add_page_info($attribute['href']);
482 case "ostatus:conversation":
483 $conversation = $attribute['href'];
484 $item['conversation-href'] = $conversation;
485 if (!isset($item['conversation-uri'])) {
486 $item['conversation-uri'] = $item['conversation-href'];
490 $enclosure = $attribute['href'];
491 if (strlen($item["attach"])) {
492 $item["attach"] .= ',';
494 if (!isset($attribute['length'])) {
495 $attribute['length'] = "0";
497 $item["attach"] .= '[attach]href="'.$attribute['href'].'" length="'.$attribute['length'].'" type="'.$attribute['type'].'" title="'.$attribute['title'].'"[/attach]';
500 if ($item["object-type"] != ACTIVITY_OBJ_BOOKMARK) {
501 if (!isset($item["parent-uri"])) {
502 $item["parent-uri"] = $attribute['href'];
504 if ($related == "") {
505 $related = $attribute['href'];
508 $item["body"] .= add_page_info($attribute['href']);
512 $self = $attribute['href'];
515 // Notification check
516 if ($importer["nurl"] == normalise_link($attribute['href'])) {
528 $notice_info = $xpath->query('statusnet:notice_info', $entry);
529 if ($notice_info && ($notice_info->length > 0)) {
530 foreach ($notice_info->item(0)->attributes AS $attributes) {
531 if ($attributes->name == "source") {
532 $item["app"] = strip_tags($attributes->textContent);
534 if ($attributes->name == "local_id") {
535 $local_id = $attributes->textContent;
537 if ($attributes->name == "repeat_of") {
538 $repeat_of = $attributes->textContent;
543 // Is it a repeated post?
544 if (($repeat_of != "") || ($item["verb"] == ACTIVITY_SHARE)) {
545 $activityobjects = $xpath->query('activity:object', $entry)->item(0);
547 if (is_object($activityobjects)) {
549 $orig_uri = $xpath->query("activity:object/atom:id", $activityobjects)->item(0)->nodeValue;
550 if (!isset($orig_uri)) {
551 $orig_uri = $xpath->query('atom:id/text()', $activityobjects)->item(0)->nodeValue;
553 $orig_links = $xpath->query("activity:object/atom:link[@rel='alternate']", $activityobjects);
554 if ($orig_links && ($orig_links->length > 0)) {
555 foreach ($orig_links->item(0)->attributes AS $attributes) {
556 if ($attributes->name == "href") {
557 $orig_link = $attributes->textContent;
561 if (!isset($orig_link)) {
562 $orig_link = $xpath->query("atom:link[@rel='alternate']", $activityobjects)->item(0)->nodeValue;
564 if (!isset($orig_link)) {
565 $orig_link = self::convert_href($orig_uri);
567 $orig_body = $xpath->query('activity:object/atom:content/text()', $activityobjects)->item(0)->nodeValue;
568 if (!isset($orig_body)) {
569 $orig_body = $xpath->query('atom:content/text()', $activityobjects)->item(0)->nodeValue;
571 $orig_created = $xpath->query('atom:published/text()', $activityobjects)->item(0)->nodeValue;
572 $orig_edited = $xpath->query('atom:updated/text()', $activityobjects)->item(0)->nodeValue;
574 $orig_contact = $contact;
575 $orig_author = self::fetchauthor($xpath, $activityobjects, $importer, $orig_contact, false);
577 $item["author-name"] = $orig_author["author-name"];
578 $item["author-link"] = $orig_author["author-link"];
579 $item["author-avatar"] = $orig_author["author-avatar"];
581 $item["body"] = add_page_info_to_body(html2bbcode($orig_body));
582 $item["created"] = $orig_created;
583 $item["edited"] = $orig_edited;
585 $item["uri"] = $orig_uri;
587 if (!isset($item["plink"])) {
588 $item["plink"] = $orig_link;
591 $item["verb"] = $xpath->query('activity:verb/text()', $activityobjects)->item(0)->nodeValue;
593 $item["object-type"] = $xpath->query('activity:object/activity:object-type/text()', $activityobjects)->item(0)->nodeValue;
594 if (!isset($item["object-type"])) {
595 $item["object-type"] = $xpath->query('activity:object-type/text()', $activityobjects)->item(0)->nodeValue;
598 $enclosures = $xpath->query("atom:link[@rel='alternate']", $activityobjects);
600 foreach ($enclosures AS $link) {
601 $attribute = self::read_attributes($link);
603 $enclosure = $attribute['href'];
604 if (strlen($item["attach"])) {
605 $item["attach"] .= ',';
607 if (!isset($attribute['length'])) {
608 $attribute['length'] = "0";
610 $item["attach"] .= '[attach]href="'.$attribute['href'].'" length="'.$attribute['length'].'" type="'.$attribute['type'].'" title="'.$attribute['title'].'"[/attach]';
617 //if ($enclosure != "")
618 // $item["body"] .= add_page_info($enclosure);
620 if (isset($item["parent-uri"])) {
621 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s'",
622 intval($importer["uid"]), dbesc($item["parent-uri"]));
624 // Only fetch missing stuff if it is a comment or reshare.
625 if (in_array($item["verb"], array(ACTIVITY_POST, ACTIVITY_SHARE)) &&
626 !dbm::is_result($r) && ($related != "")) {
627 $reply_path = str_replace("/notice/", "/api/statuses/show/", $related).".atom";
629 if ($reply_path != $related) {
630 logger("Fetching related items for user ".$importer["uid"]." from ".$reply_path, LOGGER_DEBUG);
631 $reply_xml = fetch_url($reply_path);
633 $reply_contact = $contact;
634 self::import($reply_xml,$importer,$reply_contact, $reply_hub);
636 // After the import try to fetch the parent item again
637 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s'",
638 intval($importer["uid"]), dbesc($item["parent-uri"]));
641 if (dbm::is_result($r)) {
642 $item["type"] = 'remote-comment';
643 $item["gravity"] = GRAVITY_COMMENT;
646 $item["parent-uri"] = $item["uri"];
648 $item_id = self::completion($conversation, $importer["uid"], $item, $self);
651 // Store the conversation data. This is normally done in "item_store"
652 // but since something went wrong, we want to be sure to save the data.
653 store_conversation($item);
654 logger("Error storing item", LOGGER_DEBUG);
658 logger("Item was stored with id ".$item_id, LOGGER_DEBUG);
663 * @brief Create an url out of an uri
665 * @param string $href URI in the format "parameter1:parameter1:..."
667 * @return string URL in the format http(s)://....
669 public static function convert_href($href) {
670 $elements = explode(":",$href);
672 if ((count($elements) <= 2) || ($elements[0] != "tag"))
675 $server = explode(",", $elements[1]);
676 $conversation = explode("=", $elements[2]);
678 if ((count($elements) == 4) && ($elements[2] == "post"))
679 return "http://".$server[0]."/notice/".$elements[3];
681 if ((count($conversation) != 2) || ($conversation[1] =="")) {
684 if ($elements[3] == "objectType=thread") {
685 return "http://".$server[0]."/conversation/".$conversation[1];
687 return "http://".$server[0]."/notice/".$conversation[1];
693 * @brief Checks if there are entries in conversations that aren't present on our side
695 * @param bool $mentions Fetch conversations where we are mentioned
696 * @param bool $override Override the interval setting
698 public static function check_conversations($mentions = false, $override = false) {
699 $last = get_config('system','ostatus_last_poll');
701 $poll_interval = intval(get_config('system','ostatus_poll_interval'));
702 if (!$poll_interval) {
703 $poll_interval = self::OSTATUS_DEFAULT_POLL_INTERVAL;
706 // Don't poll if the interval is set negative
707 if (($poll_interval < 0) && !$override) {
712 $poll_timeframe = intval(get_config('system','ostatus_poll_timeframe'));
713 if (!$poll_timeframe) {
714 $poll_timeframe = self::OSTATUS_DEFAULT_POLL_TIMEFRAME;
717 $poll_timeframe = intval(get_config('system','ostatus_poll_timeframe'));
718 if (!$poll_timeframe) {
719 $poll_timeframe = self::OSTATUS_DEFAULT_POLL_TIMEFRAME_MENTIONS;
724 if ($last && !$override) {
725 $next = $last + ($poll_interval * 60);
726 if ($next > time()) {
727 logger('poll interval not reached');
732 logger('cron_start');
734 $start = date("Y-m-d H:i:s", time() - ($poll_timeframe * 60));
737 $conversations = q("SELECT `term`.`oid`, `term`.`url`, `term`.`uid` FROM `term`
738 STRAIGHT_JOIN `thread` ON `thread`.`iid` = `term`.`oid` AND `thread`.`uid` = `term`.`uid`
739 WHERE `term`.`type` = 7 AND `term`.`term` > '%s' AND `thread`.`mention`
740 GROUP BY `term`.`url`, `term`.`uid`, `term`.`oid`, `term`.`term` ORDER BY `term`.`term` DESC", dbesc($start));
742 $conversations = q("SELECT `oid`, `url`, `uid` FROM `term`
743 WHERE `type` = 7 AND `term` > '%s'
744 GROUP BY `url`, `uid`, `oid`, `term` ORDER BY `term` DESC", dbesc($start));
747 foreach ($conversations AS $conversation) {
748 self::completion($conversation['url'], $conversation['uid']);
753 set_config('system','ostatus_last_poll', time());
757 * @brief Updates the gcontact table with actor data from the conversation
759 * @param object $actor The actor object that contains the contact data
761 private static function conv_fetch_actor($actor) {
763 // We set the generation to "3" since the data here is not as reliable as the data we get on other occasions
764 $contact = array("network" => NETWORK_OSTATUS, "generation" => 3);
766 if (isset($actor->url))
767 $contact["url"] = $actor->url;
769 if (isset($actor->displayName))
770 $contact["name"] = $actor->displayName;
772 if (isset($actor->portablecontacts_net->displayName))
773 $contact["name"] = $actor->portablecontacts_net->displayName;
775 if (isset($actor->portablecontacts_net->preferredUsername))
776 $contact["nick"] = $actor->portablecontacts_net->preferredUsername;
778 if (isset($actor->id))
779 $contact["alias"] = $actor->id;
781 if (isset($actor->summary))
782 $contact["about"] = $actor->summary;
784 if (isset($actor->portablecontacts_net->note))
785 $contact["about"] = $actor->portablecontacts_net->note;
787 if (isset($actor->portablecontacts_net->addresses->formatted))
788 $contact["location"] = $actor->portablecontacts_net->addresses->formatted;
791 if (isset($actor->image->url))
792 $contact["photo"] = $actor->image->url;
794 if (isset($actor->image->width))
795 $avatarwidth = $actor->image->width;
797 if (is_array($actor->status_net->avatarLinks))
798 foreach ($actor->status_net->avatarLinks AS $avatar) {
799 if ($avatarsize < $avatar->width) {
800 $contact["photo"] = $avatar->url;
801 $avatarsize = $avatar->width;
805 $contact["hide"] = false; // OStatus contacts are never hidden
806 update_gcontact($contact);
810 * @brief Fetches the conversation url for a given item link or conversation id
812 * @param string $self The link to the posting
813 * @param string $conversation_id The conversation id
815 * @return string The conversation url
817 private static function fetch_conversation($self, $conversation_id = "") {
819 if ($conversation_id != "") {
820 $elements = explode(":", $conversation_id);
822 if ((count($elements) <= 2) || ($elements[0] != "tag"))
823 return $conversation_id;
829 $json = str_replace(".atom", ".json", $self);
831 $raw = fetch_url($json);
835 $data = json_decode($raw);
836 if (!is_object($data))
839 $conversation_id = $data->statusnet_conversation_id;
841 $pos = strpos($self, "/api/statuses/show/");
842 $base_url = substr($self, 0, $pos);
844 return $base_url."/conversation/".$conversation_id;
848 * @brief Fetches a shared object from a given conversation object
850 * Sometimes GNU Social seems to fail when returning shared objects.
851 * Then they don't contains all needed data.
852 * We then try to find this object in the conversation
854 * @param string $id Message id
855 * @param object $conversation Conversation object
857 * @return object The shared object
859 private static function shared_object($id, $conversation) {
860 if (!is_array($conversation->items)) {
863 foreach ($conversation->items AS $single_conv) {
864 if ($single_conv->id == $id) {
872 * @brief Fetches actor details of a given actor and user id
874 * @param string $actor The actor url
875 * @param int $uid The user id
876 * @param int $contact_id The default contact-id
878 * @return array Array with actor details
880 private static function get_actor_details($actor, $uid, $contact_id) {
884 $contact = q("SELECT `id`, `rel`, `network` FROM `contact` WHERE `uid` = %d AND `nurl` = '%s' AND `network` != '%s'",
885 $uid, normalise_link($actor), NETWORK_STATUSNET);
888 $contact = q("SELECT `id`, `rel`, `network` FROM `contact` WHERE `uid` = %d AND `alias` IN ('%s', '%s') AND `network` != '%s'",
889 $uid, $actor, normalise_link($actor), NETWORK_STATUSNET);
892 logger("Found contact for url ".$actor, LOGGER_DEBUG);
893 $details["contact_id"] = $contact[0]["id"];
894 $details["network"] = $contact[0]["network"];
896 $details["not_following"] = !in_array($contact[0]["rel"], array(CONTACT_IS_SHARING, CONTACT_IS_FRIEND));
898 logger("No contact found for user ".$uid." and url ".$actor, LOGGER_DEBUG);
900 // Adding a global contact
901 /// @TODO Use this data for the post
902 $details["global_contact_id"] = get_contact($actor, 0);
904 logger("Global contact ".$global_contact_id." found for url ".$actor, LOGGER_DEBUG);
906 $details["contact_id"] = $contact_id;
907 $details["network"] = NETWORK_OSTATUS;
909 $details["not_following"] = true;
916 * @brief Stores an item and completes the thread
918 * @param string $conversation_url The URI of the conversation
919 * @param integer $uid The user id
920 * @param array $item Data of the item that is to be posted
922 * @return integer The item id of the posted item array
924 private static function completion($conversation_url, $uid, $item = array(), $self = "") {
926 /// @todo This function is totally ugly and has to be rewritten totally
928 // Import all threads or only threads that were started by our followers?
929 $all_threads = !get_config('system','ostatus_full_threads');
933 $conversation_url = self::fetch_conversation($self, $conversation_url);
935 // If the thread shouldn't be completed then store the item and go away
936 // Don't do a completion on liked content
937 if (((intval(get_config('system','ostatus_poll_interval')) == -2) && (count($item) > 0)) ||
938 ($item["verb"] == ACTIVITY_LIKE) || ($conversation_url == "")) {
939 $item_stored = item_store($item, $all_threads);
944 $parents = q("SELECT `item`.`id`, `item`.`parent`, `item`.`uri`, `item`.`contact-id`, `item`.`type`,
945 `item`.`verb`, `item`.`visible` FROM `term`
946 STRAIGHT_JOIN `item` AS `thritem` ON `thritem`.`parent` = `term`.`oid`
947 STRAIGHT_JOIN `item` ON `item`.`parent` = `thritem`.`parent`
948 WHERE `term`.`uid` = %d AND `term`.`otype` = %d AND `term`.`type` = %d AND `term`.`url` = '%s'",
949 intval($uid), intval(TERM_OBJ_POST), intval(TERM_CONVERSATION), dbesc($conversation_url));
951 $parent = $parents[0];
952 } elseif (count($item) > 0) {
954 $parent["type"] = "remote";
955 $parent["verb"] = ACTIVITY_POST;
956 $parent["visible"] = 1;
959 $r = q("SELECT `id` FROM `contact` WHERE `self` AND `uid`=%d", $uid);
960 if (!dbm::is_result($r)) {
965 $parent["parent"] = 0;
967 $parent["contact-id"] = $r[0]["id"];
968 $parent["type"] = "remote";
969 $parent["verb"] = ACTIVITY_POST;
970 $parent["visible"] = 1;
973 $conv = str_replace("/conversation/", "/api/statusnet/conversation/", $conversation_url).".as";
977 logger('fetching conversation url '.$conv.' (Self: '.$self.') for user '.$uid);
980 $conv_arr = z_fetch_url($conv."?page=".$pageno);
982 // If it is a non-ssl site and there is an error, then try ssl or vice versa
983 if (!$conv_arr["success"] && (substr($conv, 0, 7) == "http://")) {
984 $conv = str_replace("http://", "https://", $conv);
985 $conv_as = fetch_url($conv."?page=".$pageno);
986 } elseif (!$conv_arr["success"] && (substr($conv, 0, 8) == "https://")) {
987 $conv = str_replace("https://", "http://", $conv);
988 $conv_as = fetch_url($conv."?page=".$pageno);
990 $conv_as = $conv_arr["body"];
992 $conv_as = str_replace(',"statusnet:notice_info":', ',"statusnet_notice_info":', $conv_as);
993 $conv_as = json_decode($conv_as);
995 $no_of_items = sizeof($items);
997 if (@is_array($conv_as->items))
998 foreach ($conv_as->items AS $single_item)
999 $items[$single_item->id] = $single_item;
1001 if ($no_of_items == sizeof($items))
1008 logger('fetching conversation done. Found '.count($items).' items');
1010 if (!sizeof($items)) {
1011 if (count($item) > 0) {
1012 $item_stored = item_store($item, $all_threads);
1015 logger("Conversation ".$conversation_url." couldn't be fetched. Item uri ".$item["uri"]." stored: ".$item_stored, LOGGER_DEBUG);
1016 self::store_conversation($item_id, $conversation_url);
1019 return $item_stored;
1025 $items = array_reverse($items);
1027 $r = q("SELECT `nurl` FROM `contact` WHERE `uid` = %d AND `self`", intval($uid));
1032 foreach ($items as $single_conv) {
1034 // Update the gcontact table
1035 self::conv_fetch_actor($single_conv->actor);
1037 // Test - remove before flight
1038 //$tempfile = tempnam(get_temppath(), "conversation");
1039 //file_put_contents($tempfile, json_encode($single_conv));
1043 if (isset($single_conv->object->id))
1044 $single_conv->id = $single_conv->object->id;
1046 $plink = self::convert_href($single_conv->id);
1047 if (isset($single_conv->object->url))
1048 $plink = self::convert_href($single_conv->object->url);
1050 if (@!$single_conv->id)
1053 logger("Got id ".$single_conv->id, LOGGER_DEBUG);
1055 if ($first_id == "") {
1056 $first_id = $single_conv->id;
1058 // The first post of the conversation isn't our first post. There are three options:
1059 // 1. Our conversation hasn't the "real" thread starter
1060 // 2. This first post is a post inside our thread
1061 // 3. This first post is a post inside another thread
1062 if (($first_id != $parent["uri"]) && ($parent["uri"] != "")) {
1066 $new_parents = q("SELECT `id`, `parent`, `uri`, `contact-id`, `type`, `verb`, `visible` FROM `item` WHERE `id` IN
1067 (SELECT `parent` FROM `item`
1068 WHERE `uid` = %d AND `uri` = '%s' AND `network` IN ('%s','%s')) LIMIT 1",
1069 intval($uid), dbesc($first_id), dbesc(NETWORK_OSTATUS), dbesc(NETWORK_DFRN));
1071 if ($new_parents[0]["parent"] == $parent["parent"]) {
1072 // Option 2: This post is already present inside our thread - but not as thread starter
1073 logger("Option 2: uri present in our thread: ".$first_id, LOGGER_DEBUG);
1074 $first_id = $parent["uri"];
1076 // Option 3: Not so good. We have mixed parents. We have to see how to clean this up.
1077 // For now just take the new parent.
1078 $parent = $new_parents[0];
1079 $first_id = $parent["uri"];
1080 logger("Option 3: mixed parents for uri ".$first_id, LOGGER_DEBUG);
1083 // Option 1: We hadn't got the real thread starter
1084 // We have to clean up our existing messages.
1086 $parent["uri"] = $first_id;
1087 logger("Option 1: we have a new parent: ".$first_id, LOGGER_DEBUG);
1089 } elseif ($parent["uri"] == "") {
1091 $parent["uri"] = $first_id;
1095 $parent_uri = $parent["uri"];
1097 // "context" only seems to exist on older servers
1098 if (isset($single_conv->context->inReplyTo->id)) {
1099 $parent_exists = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `network` IN ('%s','%s') LIMIT 1",
1100 intval($uid), dbesc($single_conv->context->inReplyTo->id), dbesc(NETWORK_OSTATUS), dbesc(NETWORK_DFRN));
1102 $parent_uri = $single_conv->context->inReplyTo->id;
1105 // This is the current way
1106 if (isset($single_conv->object->inReplyTo->id)) {
1107 $parent_exists = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `network` IN ('%s','%s') LIMIT 1",
1108 intval($uid), dbesc($single_conv->object->inReplyTo->id), dbesc(NETWORK_OSTATUS), dbesc(NETWORK_DFRN));
1110 $parent_uri = $single_conv->object->inReplyTo->id;
1113 $message_exists = q("SELECT `id`, `parent`, `uri` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `network` IN ('%s','%s') LIMIT 1",
1114 intval($uid), dbesc($single_conv->id),
1115 dbesc(NETWORK_OSTATUS), dbesc(NETWORK_DFRN));
1116 if ($message_exists) {
1117 logger("Message ".$single_conv->id." already existed on the system", LOGGER_DEBUG);
1119 if ($parent["id"] != 0) {
1120 $existing_message = $message_exists[0];
1122 // We improved the way we fetch OStatus messages, this shouldn't happen very often now
1123 /// @TODO We have to change the shadow copies as well. This way here is really ugly.
1124 if ($existing_message["parent"] != $parent["id"]) {
1125 logger('updating id '.$existing_message["id"].' with parent '.$existing_message["parent"].' to parent '.$parent["id"].' uri '.$parent["uri"].' thread '.$parent_uri, LOGGER_DEBUG);
1127 // Update the parent id of the selected item
1128 $r = q("UPDATE `item` SET `parent` = %d, `parent-uri` = '%s' WHERE `id` = %d",
1129 intval($parent["id"]), dbesc($parent["uri"]), intval($existing_message["id"]));
1131 // Update the parent uri in the thread - but only if it points to itself
1132 $r = q("UPDATE `item` SET `thr-parent` = '%s' WHERE `id` = %d AND `uri` = `thr-parent`",
1133 dbesc($parent_uri), intval($existing_message["id"]));
1135 // try to change all items of the same parent
1136 $r = q("UPDATE `item` SET `parent` = %d, `parent-uri` = '%s' WHERE `parent` = %d",
1137 intval($parent["id"]), dbesc($parent["uri"]), intval($existing_message["parent"]));
1139 // Update the parent uri in the thread - but only if it points to itself
1140 $r = q("UPDATE `item` SET `thr-parent` = '%s' WHERE (`parent` = %d) AND (`uri` = `thr-parent`)",
1141 dbesc($parent["uri"]), intval($existing_message["parent"]));
1143 // Now delete the thread
1144 delete_thread($existing_message["parent"]);
1148 // The item we are having on the system is the one that we wanted to store via the item array
1149 if (isset($item["uri"]) && ($item["uri"] == $existing_message["uri"])) {
1157 if (is_array($single_conv->to))
1158 foreach ($single_conv->to AS $to)
1159 if ($importer["nurl"] == normalise_link($to->id))
1162 $actor = $single_conv->actor->id;
1163 if (isset($single_conv->actor->url))
1164 $actor = $single_conv->actor->url;
1166 $details = self::get_actor_details($actor, $uid, $parent["contact-id"]);
1168 // Do we only want to import threads that were started by our contacts?
1169 if ($details["not_following"] && $new_parent && get_config('system','ostatus_full_threads')) {
1170 logger("Don't import uri ".$first_id." because user ".$uid." doesn't follow the person ".$actor, LOGGER_DEBUG);
1174 /// @TODO One statment is okay (until if () )
1176 $arr["network"] = $details["network"];
1177 $arr["uri"] = $single_conv->id;
1178 $arr["plink"] = $plink;
1180 $arr["contact-id"] = $details["contact_id"];
1181 $arr["parent-uri"] = $parent_uri;
1182 $arr["created"] = $single_conv->published;
1183 $arr["edited"] = $single_conv->published;
1184 $arr["owner-name"] = $single_conv->actor->displayName;
1185 if ($arr["owner-name"] == '')
1186 $arr["owner-name"] = $single_conv->actor->contact->displayName;
1187 if ($arr["owner-name"] == '')
1188 $arr["owner-name"] = $single_conv->actor->portablecontacts_net->displayName;
1190 $arr["owner-link"] = $actor;
1191 $arr["owner-avatar"] = Probe::fixAvatar($single_conv->actor->image->url, $arr["owner-link"]);
1193 $arr["author-name"] = $arr["owner-name"];
1194 $arr["author-link"] = $arr["owner-link"];
1195 $arr["author-avatar"] = $arr["owner-avatar"];
1196 $arr["body"] = add_page_info_to_body(html2bbcode($single_conv->content));
1198 if (isset($single_conv->status_net->conversation)) {
1199 $arr['conversation-uri'] = $single_conv->status_net->conversation;
1202 if (isset($single_conv->status_net->notice_info->source)) {
1203 $arr["app"] = strip_tags($single_conv->status_net->notice_info->source);
1204 } elseif (isset($single_conv->statusnet->notice_info->source)) {
1205 $arr["app"] = strip_tags($single_conv->statusnet->notice_info->source);
1206 } elseif (isset($single_conv->statusnet_notice_info->source)) {
1207 $arr["app"] = strip_tags($single_conv->statusnet_notice_info->source);
1208 } elseif (isset($single_conv->provider->displayName)) {
1209 $arr["app"] = $single_conv->provider->displayName;
1211 $arr["app"] = "OStatus";
1214 $arr["source"] = json_encode($single_conv);
1215 $arr["protocol"] = PROTOCOL_GS_CONVERSATION;
1217 $arr["verb"] = $parent["verb"];
1218 $arr["visible"] = $parent["visible"];
1219 $arr["location"] = $single_conv->location->displayName;
1220 $arr["coord"] = trim($single_conv->location->lat." ".$single_conv->location->lon);
1222 // Is it a reshared item?
1223 if (isset($single_conv->verb) && ($single_conv->verb == "share") && isset($single_conv->object)) {
1224 if (is_array($single_conv->object))
1225 $single_conv->object = $single_conv->object[0];
1227 // Sometimes GNU Social doesn't returns a complete object
1228 if (!isset($single_conv->object->actor->url)) {
1229 $object = self::shared_object($single_conv->object->id, $conversation);
1230 if (is_object($object)) {
1231 $single_conv->object = $object;
1235 if (isset($single_conv->object->actor->url)) {
1236 logger("Found reshared item ".$single_conv->object->id);
1238 // $single_conv->object->context->conversation;
1240 if (isset($single_conv->object->object->id)) {
1241 $arr["uri"] = $single_conv->object->object->id;
1243 $arr["uri"] = $single_conv->object->id;
1245 if (isset($single_conv->object->object->url)) {
1246 $plink = self::convert_href($single_conv->object->object->url);
1248 $plink = self::convert_href($single_conv->object->url);
1250 if (isset($single_conv->object->object->content)) {
1251 $arr["body"] = add_page_info_to_body(html2bbcode($single_conv->object->object->content));
1253 $arr["body"] = add_page_info_to_body(html2bbcode($single_conv->object->content));
1255 $arr["plink"] = $plink;
1257 $arr["created"] = $single_conv->object->published;
1258 $arr["edited"] = $single_conv->object->published;
1260 $arr["author-name"] = $single_conv->object->actor->displayName;
1261 if ($arr["owner-name"] == '') {
1262 $arr["author-name"] = $single_conv->object->actor->contact->displayName;
1264 $arr["author-link"] = $single_conv->object->actor->url;
1265 $arr["author-avatar"] = Probe::fixAvatar($single_conv->object->actor->image->url, $arr["author-link"]);
1267 $arr["app"] = $single_conv->object->provider->displayName."#";
1268 //$arr["verb"] = $single_conv->object->verb;
1270 $arr["location"] = $single_conv->object->location->displayName;
1271 $arr["coord"] = trim($single_conv->object->location->lat." ".$single_conv->object->location->lon);
1275 if ($arr["location"] == "")
1276 unset($arr["location"]);
1278 if ($arr["coord"] == "")
1279 unset($arr["coord"]);
1281 // Copy fields from given item array
1282 if (isset($item["uri"]) && (($item["uri"] == $arr["uri"]) || ($item["uri"] == $single_conv->id))) {
1283 logger('Use stored item array for item with URI '.$item["uri"], LOGGER_DEBUG);
1284 $newitem = item_store($item);
1286 $item_stored = $newitem;
1288 $newitem = item_store($arr);
1292 logger("Item wasn't stored ".print_r($arr, true), LOGGER_DEBUG);
1296 logger('Stored new item '.$plink.' for parent '.$arr["parent-uri"].' under id '.$newitem, LOGGER_DEBUG);
1298 // Add the conversation entry (but don't fetch the whole conversation)
1299 self::store_conversation($newitem, $conversation_url);
1301 // If the newly created item is the top item then change the parent settings of the thread
1302 // This shouldn't happen anymore. This is supposed to be absolote.
1303 if ($arr["uri"] == $first_id) {
1304 logger('setting new parent to id '.$newitem);
1305 $new_parents = q("SELECT `id`, `uri`, `contact-id`, `type`, `verb`, `visible` FROM `item` WHERE `uid` = %d AND `id` = %d LIMIT 1",
1306 intval($uid), intval($newitem));
1308 $parent = $new_parents[0];
1312 if (($item_stored < 0) && (count($item) > 0)) {
1314 if (get_config('system','ostatus_full_threads')) {
1315 $details = self::get_actor_details($item["owner-link"], $uid, $item["contact-id"]);
1316 if ($details["not_following"]) {
1317 logger("Don't import uri ".$item["uri"]." because user ".$uid." doesn't follow the person ".$item["owner-link"], LOGGER_DEBUG);
1322 $item_stored = item_store($item, $all_threads);
1324 logger("Uri ".$item["uri"]." wasn't found in conversation ".$conversation_url, LOGGER_DEBUG);
1325 self::store_conversation($item_stored, $conversation_url);
1329 return $item_stored;
1333 * @brief Stores conversation data into the database
1335 * @param integer $itemid The id of the item
1336 * @param string $conversation_url The uri of the conversation
1338 private static function store_conversation($itemid, $conversation_url) {
1340 $conversation_url = self::convert_href($conversation_url);
1342 $messages = q("SELECT `uid`, `parent`, `created`, `received`, `guid` FROM `item` WHERE `id` = %d LIMIT 1", intval($itemid));
1345 $message = $messages[0];
1347 // Store conversation url if not done before
1348 $conversation = q("SELECT `url` FROM `term` WHERE `uid` = %d AND `oid` = %d AND `otype` = %d AND `type` = %d",
1349 intval($message["uid"]), intval($itemid), intval(TERM_OBJ_POST), intval(TERM_CONVERSATION));
1351 if (!$conversation) {
1352 $r = q("INSERT INTO `term` (`uid`, `oid`, `otype`, `type`, `term`, `url`, `created`, `received`, `guid`) VALUES (%d, %d, %d, %d, '%s', '%s', '%s', '%s', '%s')",
1353 intval($message["uid"]), intval($itemid), intval(TERM_OBJ_POST), intval(TERM_CONVERSATION),
1354 dbesc($message["created"]), dbesc($conversation_url), dbesc($message["created"]), dbesc($message["received"]), dbesc($message["guid"]));
1355 logger('Storing conversation url '.$conversation_url.' for id '.$itemid);
1360 * @brief Checks if the current post is a reshare
1362 * @param array $item The item array of thw post
1364 * @return string The guid if the post is a reshare
1366 private static function get_reshared_guid($item) {
1367 $body = trim($item["body"]);
1369 // Skip if it isn't a pure repeated messages
1370 // Does it start with a share?
1371 if (strpos($body, "[share") > 0)
1374 // Does it end with a share?
1375 if (strlen($body) > (strrpos($body, "[/share]") + 8))
1378 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$1",$body);
1379 // Skip if there is no shared message in there
1380 if ($body == $attributes)
1384 preg_match("/guid='(.*?)'/ism", $attributes, $matches);
1385 if ($matches[1] != "")
1386 $guid = $matches[1];
1388 preg_match('/guid="(.*?)"/ism', $attributes, $matches);
1389 if ($matches[1] != "")
1390 $guid = $matches[1];
1396 * @brief Cleans the body of a post if it contains picture links
1398 * @param string $body The body
1400 * @return string The cleaned body
1402 private static function format_picture_post($body) {
1403 $siteinfo = get_attached_data($body);
1405 if (($siteinfo["type"] == "photo")) {
1406 if (isset($siteinfo["preview"]))
1407 $preview = $siteinfo["preview"];
1409 $preview = $siteinfo["image"];
1411 // Is it a remote picture? Then make a smaller preview here
1412 $preview = proxy_url($preview, false, PROXY_SIZE_SMALL);
1414 // Is it a local picture? Then make it smaller here
1415 $preview = str_replace(array("-0.jpg", "-0.png"), array("-2.jpg", "-2.png"), $preview);
1416 $preview = str_replace(array("-1.jpg", "-1.png"), array("-2.jpg", "-2.png"), $preview);
1418 if (isset($siteinfo["url"]))
1419 $url = $siteinfo["url"];
1421 $url = $siteinfo["image"];
1423 $body = trim($siteinfo["text"])." [url]".$url."[/url]\n[img]".$preview."[/img]";
1430 * @brief Adds the header elements to the XML document
1432 * @param object $doc XML document
1433 * @param array $owner Contact data of the poster
1435 * @return object header root element
1437 private static function add_header($doc, $owner) {
1441 $root = $doc->createElementNS(NAMESPACE_ATOM1, 'feed');
1442 $doc->appendChild($root);
1444 $root->setAttribute("xmlns:thr", NAMESPACE_THREAD);
1445 $root->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
1446 $root->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
1447 $root->setAttribute("xmlns:media", NAMESPACE_MEDIA);
1448 $root->setAttribute("xmlns:poco", NAMESPACE_POCO);
1449 $root->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
1450 $root->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
1451 $root->setAttribute("xmlns:mastodon", NAMESPACE_MASTODON);
1453 $attributes = array("uri" => "https://friendi.ca", "version" => FRIENDICA_VERSION."-".DB_UPDATE_VERSION);
1454 xml::add_element($doc, $root, "generator", FRIENDICA_PLATFORM, $attributes);
1455 xml::add_element($doc, $root, "id", App::get_baseurl()."/profile/".$owner["nick"]);
1456 xml::add_element($doc, $root, "title", sprintf("%s timeline", $owner["name"]));
1457 xml::add_element($doc, $root, "subtitle", sprintf("Updates from %s on %s", $owner["name"], $a->config["sitename"]));
1458 xml::add_element($doc, $root, "logo", $owner["photo"]);
1459 xml::add_element($doc, $root, "updated", datetime_convert("UTC", "UTC", "now", ATOM_TIME));
1461 $author = self::add_author($doc, $owner);
1462 $root->appendChild($author);
1464 $attributes = array("href" => $owner["url"], "rel" => "alternate", "type" => "text/html");
1465 xml::add_element($doc, $root, "link", "", $attributes);
1467 /// @TODO We have to find out what this is
1468 /// $attributes = array("href" => App::get_baseurl()."/sup",
1469 /// "rel" => "http://api.friendfeed.com/2008/03#sup",
1470 /// "type" => "application/json");
1471 /// xml::add_element($doc, $root, "link", "", $attributes);
1473 self::hublinks($doc, $root, $owner["nick"]);
1475 $attributes = array("href" => App::get_baseurl()."/salmon/".$owner["nick"], "rel" => "salmon");
1476 xml::add_element($doc, $root, "link", "", $attributes);
1478 $attributes = array("href" => App::get_baseurl()."/salmon/".$owner["nick"], "rel" => "http://salmon-protocol.org/ns/salmon-replies");
1479 xml::add_element($doc, $root, "link", "", $attributes);
1481 $attributes = array("href" => App::get_baseurl()."/salmon/".$owner["nick"], "rel" => "http://salmon-protocol.org/ns/salmon-mention");
1482 xml::add_element($doc, $root, "link", "", $attributes);
1484 $attributes = array("href" => App::get_baseurl()."/api/statuses/user_timeline/".$owner["nick"].".atom",
1485 "rel" => "self", "type" => "application/atom+xml");
1486 xml::add_element($doc, $root, "link", "", $attributes);
1492 * @brief Add the link to the push hubs to the XML document
1494 * @param object $doc XML document
1495 * @param object $root XML root element where the hub links are added
1497 public static function hublinks($doc, $root, $nick) {
1498 $h = App::get_baseurl() . '/pubsubhubbub/'.$nick;
1499 xml::add_element($doc, $root, "link", "", array("href" => $h, "rel" => "hub"));
1503 * @brief Adds attachement data to the XML document
1505 * @param object $doc XML document
1506 * @param object $root XML root element where the hub links are added
1507 * @param array $item Data of the item that is to be posted
1509 private static function get_attachment($doc, $root, $item) {
1511 $siteinfo = get_attached_data($item["body"]);
1513 switch ($siteinfo["type"]) {
1515 $imgdata = get_photo_info($siteinfo["image"]);
1516 $attributes = array("rel" => "enclosure",
1517 "href" => $siteinfo["image"],
1518 "type" => $imgdata["mime"],
1519 "length" => intval($imgdata["size"]));
1520 xml::add_element($doc, $root, "link", "", $attributes);
1523 $attributes = array("rel" => "enclosure",
1524 "href" => $siteinfo["url"],
1525 "type" => "text/html; charset=UTF-8",
1527 "title" => $siteinfo["title"]);
1528 xml::add_element($doc, $root, "link", "", $attributes);
1534 if (!Config::get('system', 'ostatus_not_attach_preview') && ($siteinfo["type"] != "photo") && isset($siteinfo["image"])) {
1535 $imgdata = get_photo_info($siteinfo["image"]);
1536 $attributes = array("rel" => "enclosure",
1537 "href" => $siteinfo["image"],
1538 "type" => $imgdata["mime"],
1539 "length" => intval($imgdata["size"]));
1541 xml::add_element($doc, $root, "link", "", $attributes);
1544 $arr = explode('[/attach],', $item['attach']);
1546 foreach ($arr as $r) {
1548 $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"|', $r, $matches);
1550 $attributes = array("rel" => "enclosure",
1551 "href" => $matches[1],
1552 "type" => $matches[3]);
1554 if (intval($matches[2])) {
1555 $attributes["length"] = intval($matches[2]);
1557 if (trim($matches[4]) != "") {
1558 $attributes["title"] = trim($matches[4]);
1560 xml::add_element($doc, $root, "link", "", $attributes);
1567 * @brief Adds the author element to the XML document
1569 * @param object $doc XML document
1570 * @param array $owner Contact data of the poster
1572 * @return object author element
1574 private static function add_author($doc, $owner) {
1576 $r = q("SELECT `homepage`, `publish` FROM `profile` WHERE `uid` = %d AND `is-default` LIMIT 1", intval($owner["uid"]));
1577 if (dbm::is_result($r)) {
1580 $author = $doc->createElement("author");
1581 xml::add_element($doc, $author, "id", $owner["url"]);
1582 xml::add_element($doc, $author, "activity:object-type", ACTIVITY_OBJ_PERSON);
1583 xml::add_element($doc, $author, "uri", $owner["url"]);
1584 xml::add_element($doc, $author, "name", $owner["nick"]);
1585 xml::add_element($doc, $author, "email", $owner["addr"]);
1586 xml::add_element($doc, $author, "summary", bbcode($owner["about"], false, false, 7));
1588 $attributes = array("rel" => "alternate", "type" => "text/html", "href" => $owner["url"]);
1589 xml::add_element($doc, $author, "link", "", $attributes);
1591 $attributes = array(
1593 "type" => "image/jpeg", // To-Do?
1594 "media:width" => 175,
1595 "media:height" => 175,
1596 "href" => $owner["photo"]);
1597 xml::add_element($doc, $author, "link", "", $attributes);
1599 if (isset($owner["thumb"])) {
1600 $attributes = array(
1602 "type" => "image/jpeg", // To-Do?
1603 "media:width" => 80,
1604 "media:height" => 80,
1605 "href" => $owner["thumb"]);
1606 xml::add_element($doc, $author, "link", "", $attributes);
1609 xml::add_element($doc, $author, "poco:preferredUsername", $owner["nick"]);
1610 xml::add_element($doc, $author, "poco:displayName", $owner["name"]);
1611 xml::add_element($doc, $author, "poco:note", bbcode($owner["about"], false, false, 7));
1613 if (trim($owner["location"]) != "") {
1614 $element = $doc->createElement("poco:address");
1615 xml::add_element($doc, $element, "poco:formatted", $owner["location"]);
1616 $author->appendChild($element);
1619 if (trim($profile["homepage"]) != "") {
1620 $urls = $doc->createElement("poco:urls");
1621 xml::add_element($doc, $urls, "poco:type", "homepage");
1622 xml::add_element($doc, $urls, "poco:value", $profile["homepage"]);
1623 xml::add_element($doc, $urls, "poco:primary", "true");
1624 $author->appendChild($urls);
1627 if (count($profile)) {
1628 xml::add_element($doc, $author, "followers", "", array("url" => App::get_baseurl()."/viewcontacts/".$owner["nick"]));
1629 xml::add_element($doc, $author, "statusnet:profile_info", "", array("local_id" => $owner["uid"]));
1632 if ($profile["publish"]) {
1633 xml::add_element($doc, $author, "mastodon:scope", "public");
1639 * @TODO Picture attachments should look like this:
1640 * <a href="https://status.pirati.ca/attachment/572819" title="https://status.pirati.ca/file/heluecht-20151202T222602-rd3u49p.gif"
1641 * class="attachment thumbnail" id="attachment-572819" rel="nofollow external">https://status.pirati.ca/attachment/572819</a>
1646 * @brief Returns the given activity if present - otherwise returns the "post" activity
1648 * @param array $item Data of the item that is to be posted
1650 * @return string activity
1652 function construct_verb($item) {
1654 return $item['verb'];
1655 return ACTIVITY_POST;
1659 * @brief Returns the given object type if present - otherwise returns the "note" object type
1661 * @param array $item Data of the item that is to be posted
1663 * @return string Object type
1665 function construct_objecttype($item) {
1666 if (in_array($item['object-type'], array(ACTIVITY_OBJ_NOTE, ACTIVITY_OBJ_COMMENT)))
1667 return $item['object-type'];
1668 return ACTIVITY_OBJ_NOTE;
1672 * @brief Adds an entry element to the XML document
1674 * @param object $doc XML document
1675 * @param array $item Data of the item that is to be posted
1676 * @param array $owner Contact data of the poster
1677 * @param bool $toplevel
1679 * @return object Entry element
1681 private static function entry($doc, $item, $owner, $toplevel = false) {
1682 $repeated_guid = self::get_reshared_guid($item);
1683 if ($repeated_guid != "")
1684 $xml = self::reshare_entry($doc, $item, $owner, $repeated_guid, $toplevel);
1689 if ($item["verb"] == ACTIVITY_LIKE) {
1690 return self::like_entry($doc, $item, $owner, $toplevel);
1691 } elseif (in_array($item["verb"], array(ACTIVITY_FOLLOW, NAMESPACE_OSTATUS."/unfollow"))) {
1692 return self::follow_entry($doc, $item, $owner, $toplevel);
1694 return self::note_entry($doc, $item, $owner, $toplevel);
1699 * @brief Adds a source entry to the XML document
1701 * @param object $doc XML document
1702 * @param array $contact Array of the contact that is added
1704 * @return object Source element
1706 private static function source_entry($doc, $contact) {
1707 $source = $doc->createElement("source");
1708 xml::add_element($doc, $source, "id", $contact["poll"]);
1709 xml::add_element($doc, $source, "title", $contact["name"]);
1710 xml::add_element($doc, $source, "link", "", array("rel" => "alternate",
1711 "type" => "text/html",
1712 "href" => $contact["alias"]));
1713 xml::add_element($doc, $source, "link", "", array("rel" => "self",
1714 "type" => "application/atom+xml",
1715 "href" => $contact["poll"]));
1716 xml::add_element($doc, $source, "icon", $contact["photo"]);
1717 xml::add_element($doc, $source, "updated", datetime_convert("UTC","UTC",$contact["success_update"]."+00:00",ATOM_TIME));
1723 * @brief Fetches contact data from the contact or the gcontact table
1725 * @param string $url URL of the contact
1726 * @param array $owner Contact data of the poster
1728 * @return array Contact array
1730 private static function contact_entry($url, $owner) {
1732 $r = q("SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` IN (0, %d) ORDER BY `uid` DESC LIMIT 1",
1733 dbesc(normalise_link($url)), intval($owner["uid"]));
1734 if (dbm::is_result($r)) {
1736 $contact["uid"] = -1;
1739 if (!dbm::is_result($r)) {
1740 $r = q("SELECT * FROM `gcontact` WHERE `nurl` = '%s' LIMIT 1",
1741 dbesc(normalise_link($url)));
1742 if (dbm::is_result($r)) {
1744 $contact["uid"] = -1;
1745 $contact["success_update"] = $contact["updated"];
1749 if (!dbm::is_result($r))
1752 if (!isset($contact["poll"])) {
1753 $data = probe_url($url);
1754 $contact["poll"] = $data["poll"];
1756 if (!$contact["alias"])
1757 $contact["alias"] = $data["alias"];
1760 if (!isset($contact["alias"]))
1761 $contact["alias"] = $contact["url"];
1767 * @brief Adds an entry element with reshared content
1769 * @param object $doc XML document
1770 * @param array $item Data of the item that is to be posted
1771 * @param array $owner Contact data of the poster
1772 * @param $repeated_guid
1773 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1775 * @return object Entry element
1777 private static function reshare_entry($doc, $item, $owner, $repeated_guid, $toplevel) {
1779 if (($item["id"] != $item["parent"]) && (normalise_link($item["author-link"]) != normalise_link($owner["url"]))) {
1780 logger("OStatus entry is from author ".$owner["url"]." - not from ".$item["author-link"].". Quitting.", LOGGER_DEBUG);
1783 $title = self::entry_header($doc, $entry, $owner, $toplevel);
1785 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' AND NOT `private` AND `network` IN ('%s', '%s', '%s') LIMIT 1",
1786 intval($owner["uid"]), dbesc($repeated_guid),
1787 dbesc(NETWORK_DFRN), dbesc(NETWORK_DIASPORA), dbesc(NETWORK_OSTATUS));
1788 if (dbm::is_result($r)) {
1789 $repeated_item = $r[0];
1793 $contact = self::contact_entry($repeated_item['author-link'], $owner);
1795 $parent_item = (($item['thr-parent']) ? $item['thr-parent'] : $item['parent-uri']);
1797 $title = $owner["nick"]." repeated a notice by ".$contact["nick"];
1799 self::entry_content($doc, $entry, $item, $owner, $title, ACTIVITY_SHARE, false);
1801 $as_object = $doc->createElement("activity:object");
1803 xml::add_element($doc, $as_object, "activity:object-type", NAMESPACE_ACTIVITY_SCHEMA."activity");
1805 self::entry_content($doc, $as_object, $repeated_item, $owner, "", "", false);
1807 $author = self::add_author($doc, $contact);
1808 $as_object->appendChild($author);
1810 $as_object2 = $doc->createElement("activity:object");
1812 xml::add_element($doc, $as_object2, "activity:object-type", self::construct_objecttype($repeated_item));
1814 $title = sprintf("New comment by %s", $contact["nick"]);
1816 self::entry_content($doc, $as_object2, $repeated_item, $owner, $title);
1818 $as_object->appendChild($as_object2);
1820 self::entry_footer($doc, $as_object, $item, $owner, false);
1822 $source = self::source_entry($doc, $contact);
1824 $as_object->appendChild($source);
1826 $entry->appendChild($as_object);
1828 self::entry_footer($doc, $entry, $item, $owner);
1834 * @brief Adds an entry element with a "like"
1836 * @param object $doc XML document
1837 * @param array $item Data of the item that is to be posted
1838 * @param array $owner Contact data of the poster
1839 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1841 * @return object Entry element with "like"
1843 private static function like_entry($doc, $item, $owner, $toplevel) {
1845 if (($item["id"] != $item["parent"]) && (normalise_link($item["author-link"]) != normalise_link($owner["url"]))) {
1846 logger("OStatus entry is from author ".$owner["url"]." - not from ".$item["author-link"].". Quitting.", LOGGER_DEBUG);
1849 $title = self::entry_header($doc, $entry, $owner, $toplevel);
1851 $verb = NAMESPACE_ACTIVITY_SCHEMA."favorite";
1852 self::entry_content($doc, $entry, $item, $owner, "Favorite", $verb, false);
1854 $as_object = $doc->createElement("activity:object");
1856 $parent = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d",
1857 dbesc($item["thr-parent"]), intval($item["uid"]));
1858 $parent_item = (($item['thr-parent']) ? $item['thr-parent'] : $item['parent-uri']);
1860 xml::add_element($doc, $as_object, "activity:object-type", self::construct_objecttype($parent[0]));
1862 self::entry_content($doc, $as_object, $parent[0], $owner, "New entry");
1864 $entry->appendChild($as_object);
1866 self::entry_footer($doc, $entry, $item, $owner);
1872 * @brief Adds the person object element to the XML document
1874 * @param object $doc XML document
1875 * @param array $owner Contact data of the poster
1876 * @param array $contact Contact data of the target
1878 * @return object author element
1880 private static function add_person_object($doc, $owner, $contact) {
1882 $object = $doc->createElement("activity:object");
1883 xml::add_element($doc, $object, "activity:object-type", ACTIVITY_OBJ_PERSON);
1885 if ($contact['network'] == NETWORK_PHANTOM) {
1886 xml::add_element($doc, $object, "id", $contact['url']);
1890 xml::add_element($doc, $object, "id", $contact["alias"]);
1891 xml::add_element($doc, $object, "title", $contact["nick"]);
1893 $attributes = array("rel" => "alternate", "type" => "text/html", "href" => $contact["url"]);
1894 xml::add_element($doc, $object, "link", "", $attributes);
1896 $attributes = array(
1898 "type" => "image/jpeg", // To-Do?
1899 "media:width" => 175,
1900 "media:height" => 175,
1901 "href" => $contact["photo"]);
1902 xml::add_element($doc, $object, "link", "", $attributes);
1904 xml::add_element($doc, $object, "poco:preferredUsername", $contact["nick"]);
1905 xml::add_element($doc, $object, "poco:displayName", $contact["name"]);
1907 if (trim($contact["location"]) != "") {
1908 $element = $doc->createElement("poco:address");
1909 xml::add_element($doc, $element, "poco:formatted", $contact["location"]);
1910 $object->appendChild($element);
1917 * @brief Adds a follow/unfollow entry element
1919 * @param object $doc XML document
1920 * @param array $item Data of the follow/unfollow message
1921 * @param array $owner Contact data of the poster
1922 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1924 * @return object Entry element
1926 private static function follow_entry($doc, $item, $owner, $toplevel) {
1928 $item["id"] = $item["parent"] = 0;
1929 $item["created"] = $item["edited"] = date("c");
1930 $item["private"] = true;
1932 $contact = Probe::uri($item['follow']);
1934 if ($contact['alias'] == '') {
1935 $contact['alias'] = $contact["url"];
1937 $item['follow'] = $contact['alias'];
1940 $r = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `nurl` = '%s'",
1941 intval($owner['uid']), dbesc(normalise_link($contact["url"])));
1943 if (dbm::is_result($r)) {
1944 $connect_id = $r[0]['id'];
1949 if ($item['verb'] == ACTIVITY_FOLLOW) {
1950 $message = t('%s is now following %s.');
1951 $title = t('following');
1952 $action = "subscription";
1954 $message = t('%s stopped following %s.');
1955 $title = t('stopped following');
1956 $action = "unfollow";
1959 $item["uri"] = $item['parent-uri'] = $item['thr-parent'] =
1960 'tag:'.get_app()->get_hostname().
1961 ','.date('Y-m-d').':'.$action.':'.$owner['uid'].
1962 ':person:'.$connect_id.':'.$item['created'];
1964 $item["body"] = sprintf($message, $owner["nick"], $contact["nick"]);
1966 self::entry_header($doc, $entry, $owner, $toplevel);
1968 self::entry_content($doc, $entry, $item, $owner, $title);
1970 $object = self::add_person_object($doc, $owner, $contact);
1971 $entry->appendChild($object);
1973 self::entry_footer($doc, $entry, $item, $owner);
1979 * @brief Adds a regular entry element
1981 * @param object $doc XML document
1982 * @param array $item Data of the item that is to be posted
1983 * @param array $owner Contact data of the poster
1984 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1986 * @return object Entry element
1988 private static function note_entry($doc, $item, $owner, $toplevel) {
1990 if (($item["id"] != $item["parent"]) && (normalise_link($item["author-link"]) != normalise_link($owner["url"]))) {
1991 logger("OStatus entry is from author ".$owner["url"]." - not from ".$item["author-link"].". Quitting.", LOGGER_DEBUG);
1994 $title = self::entry_header($doc, $entry, $owner, $toplevel);
1996 xml::add_element($doc, $entry, "activity:object-type", ACTIVITY_OBJ_NOTE);
1998 self::entry_content($doc, $entry, $item, $owner, $title);
2000 self::entry_footer($doc, $entry, $item, $owner);
2006 * @brief Adds a header element to the XML document
2008 * @param object $doc XML document
2009 * @param object $entry The entry element where the elements are added
2010 * @param array $owner Contact data of the poster
2011 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
2013 * @return string The title for the element
2015 private static function entry_header($doc, &$entry, $owner, $toplevel) {
2016 /// @todo Check if this title stuff is really needed (I guess not)
2018 $entry = $doc->createElement("entry");
2019 $title = sprintf("New note by %s", $owner["nick"]);
2021 $entry = $doc->createElementNS(NAMESPACE_ATOM1, "entry");
2023 $entry->setAttribute("xmlns:thr", NAMESPACE_THREAD);
2024 $entry->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
2025 $entry->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
2026 $entry->setAttribute("xmlns:media", NAMESPACE_MEDIA);
2027 $entry->setAttribute("xmlns:poco", NAMESPACE_POCO);
2028 $entry->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
2029 $entry->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
2030 $entry->setAttribute("xmlns:mastodon", NAMESPACE_MASTODON);
2032 $author = self::add_author($doc, $owner);
2033 $entry->appendChild($author);
2035 $title = sprintf("New comment by %s", $owner["nick"]);
2041 * @brief Adds elements to the XML document
2043 * @param object $doc XML document
2044 * @param object $entry Entry element where the content is added
2045 * @param array $item Data of the item that is to be posted
2046 * @param array $owner Contact data of the poster
2047 * @param string $title Title for the post
2048 * @param string $verb The activity verb
2049 * @param bool $complete Add the "status_net" element?
2051 private static function entry_content($doc, $entry, $item, $owner, $title, $verb = "", $complete = true) {
2054 $verb = self::construct_verb($item);
2056 xml::add_element($doc, $entry, "id", $item["uri"]);
2057 xml::add_element($doc, $entry, "title", $title);
2059 $body = self::format_picture_post($item['body']);
2061 if ($item['title'] != "")
2062 $body = "[b]".$item['title']."[/b]\n\n".$body;
2064 $body = bbcode($body, false, false, 7);
2066 xml::add_element($doc, $entry, "content", $body, array("type" => "html"));
2068 xml::add_element($doc, $entry, "link", "", array("rel" => "alternate", "type" => "text/html",
2069 "href" => App::get_baseurl()."/display/".$item["guid"]));
2071 if ($complete && ($item["id"] > 0))
2072 xml::add_element($doc, $entry, "status_net", "", array("notice_id" => $item["id"]));
2074 xml::add_element($doc, $entry, "activity:verb", $verb);
2076 xml::add_element($doc, $entry, "published", datetime_convert("UTC","UTC",$item["created"]."+00:00",ATOM_TIME));
2077 xml::add_element($doc, $entry, "updated", datetime_convert("UTC","UTC",$item["edited"]."+00:00",ATOM_TIME));
2081 * @brief Adds the elements at the foot of an entry to the XML document
2083 * @param object $doc XML document
2084 * @param object $entry The entry element where the elements are added
2085 * @param array $item Data of the item that is to be posted
2086 * @param array $owner Contact data of the poster
2089 private static function entry_footer($doc, $entry, $item, $owner, $complete = true) {
2091 $mentioned = array();
2093 if (($item['parent'] != $item['id']) || ($item['parent-uri'] !== $item['uri']) || (($item['thr-parent'] !== '') && ($item['thr-parent'] !== $item['uri']))) {
2094 $parent = q("SELECT `guid`, `author-link`, `owner-link` FROM `item` WHERE `id` = %d", intval($item["parent"]));
2095 $parent_item = (($item['thr-parent']) ? $item['thr-parent'] : $item['parent-uri']);
2097 $thrparent = q("SELECT `guid`, `author-link`, `owner-link`, `plink` FROM `item` WHERE `uid` = %d AND `uri` = '%s'",
2098 intval($owner["uid"]),
2099 dbesc($parent_item));
2101 $mentioned[$thrparent[0]["author-link"]] = $thrparent[0]["author-link"];
2102 $mentioned[$thrparent[0]["owner-link"]] = $thrparent[0]["owner-link"];
2103 $parent_plink = $thrparent[0]["plink"];
2105 $mentioned[$parent[0]["author-link"]] = $parent[0]["author-link"];
2106 $mentioned[$parent[0]["owner-link"]] = $parent[0]["owner-link"];
2107 $parent_plink = App::get_baseurl()."/display/".$parent[0]["guid"];
2110 $attributes = array(
2111 "ref" => $parent_item,
2112 "href" => $parent_plink);
2113 xml::add_element($doc, $entry, "thr:in-reply-to", "", $attributes);
2115 $attributes = array(
2117 "href" => $parent_plink);
2118 xml::add_element($doc, $entry, "link", "", $attributes);
2121 if (intval($item["parent"]) > 0) {
2122 $conversation_href = App::get_baseurl()."/display/".$owner["nick"]."/".$item["parent"];
2123 $conversation_uri = $conversation_href;
2125 if (isset($parent_item)) {
2126 $r = dba::fetch_first("SELECT `conversation-uri`, `conversation-href` FROM `conversation` WHERE `item-uri` = ?", $parent_item);
2127 if (dbm::is_result($r)) {
2128 if ($r['conversation-uri'] != '') {
2129 $conversation_uri = $r['conversation-uri'];
2131 if ($r['conversation-href'] != '') {
2132 $conversation_href = $r['conversation-href'];
2137 xml::add_element($doc, $entry, "link", "", array("rel" => "ostatus:conversation", "href" => $conversation_href));
2139 $attributes = array(
2140 "href" => $conversation_href,
2141 "local_id" => $item["parent"],
2142 "ref" => $conversation_uri);
2144 xml::add_element($doc, $entry, "ostatus:conversation", $conversation_uri, $attributes);
2147 $tags = item_getfeedtags($item);
2150 foreach ($tags as $t)
2152 $mentioned[$t[1]] = $t[1];
2154 // Make sure that mentions are accepted (GNU Social has problems with mixing HTTP and HTTPS)
2155 $newmentions = array();
2156 foreach ($mentioned AS $mention) {
2157 $newmentions[str_replace("http://", "https://", $mention)] = str_replace("http://", "https://", $mention);
2158 $newmentions[str_replace("https://", "http://", $mention)] = str_replace("https://", "http://", $mention);
2160 $mentioned = $newmentions;
2162 foreach ($mentioned AS $mention) {
2163 $r = q("SELECT `forum`, `prv` FROM `contact` WHERE `uid` = %d AND `nurl` = '%s'",
2164 intval($owner["uid"]),
2165 dbesc(normalise_link($mention)));
2166 if ($r[0]["forum"] || $r[0]["prv"])
2167 xml::add_element($doc, $entry, "link", "", array("rel" => "mentioned",
2168 "ostatus:object-type" => ACTIVITY_OBJ_GROUP,
2169 "href" => $mention));
2171 xml::add_element($doc, $entry, "link", "", array("rel" => "mentioned",
2172 "ostatus:object-type" => ACTIVITY_OBJ_PERSON,
2173 "href" => $mention));
2176 if (!$item["private"]) {
2177 xml::add_element($doc, $entry, "link", "", array("rel" => "ostatus:attention",
2178 "href" => "http://activityschema.org/collection/public"));
2179 xml::add_element($doc, $entry, "link", "", array("rel" => "mentioned",
2180 "ostatus:object-type" => "http://activitystrea.ms/schema/1.0/collection",
2181 "href" => "http://activityschema.org/collection/public"));
2182 xml::add_element($doc, $entry, "mastodon:scope", "public");
2186 foreach ($tags as $t)
2188 xml::add_element($doc, $entry, "category", "", array("term" => $t[2]));
2190 self::get_attachment($doc, $entry, $item);
2192 if ($complete && ($item["id"] > 0)) {
2193 $app = $item["app"];
2197 $attributes = array("local_id" => $item["id"], "source" => $app);
2199 if (isset($parent["id"]))
2200 $attributes["repeat_of"] = $parent["id"];
2202 if ($item["coord"] != "")
2203 xml::add_element($doc, $entry, "georss:point", $item["coord"]);
2205 xml::add_element($doc, $entry, "statusnet:notice_info", "", $attributes);
2210 * @brief Creates the XML feed for a given nickname
2212 * @param App $a The application class
2213 * @param string $owner_nick Nickname of the feed owner
2214 * @param string $last_update Date of the last update
2215 * @param integer $max_items Number of maximum items to fetch
2217 * @return string XML feed
2219 public static function feed(App $a, $owner_nick, &$last_update, $max_items = 300) {
2220 $stamp = microtime(true);
2222 $cachekey = "ostatus:feed:".$owner_nick.":".$last_update;
2224 $previous_created = $last_update;
2226 $result = Cache::get($cachekey);
2227 if (!is_null($result)) {
2228 logger('Feed duration: '.number_format(microtime(true) - $stamp, 3).' - '.$owner_nick.' - '.$previous_created.' (cached)', LOGGER_DEBUG);
2229 $last_update = $result['last_update'];
2230 return $result['feed'];
2233 $r = q("SELECT `contact`.*, `user`.`nickname`, `user`.`timezone`, `user`.`page-flags`
2234 FROM `contact` INNER JOIN `user` ON `user`.`uid` = `contact`.`uid`
2235 WHERE `contact`.`self` AND `user`.`nickname` = '%s' LIMIT 1",
2236 dbesc($owner_nick));
2237 if (!dbm::is_result($r)) {
2243 if (!strlen($last_update)) {
2244 $last_update = 'now -30 days';
2247 $check_date = datetime_convert('UTC','UTC',$last_update,'Y-m-d H:i:s');
2248 $authorid = get_contact($owner["url"], 0);
2250 $items = q("SELECT `item`.*, `item`.`id` AS `item_id` FROM `item` USE INDEX (`uid_contactid_created`)
2251 STRAIGHT_JOIN `thread` ON `thread`.`iid` = `item`.`parent`
2252 WHERE `item`.`uid` = %d AND `item`.`contact-id` = %d AND
2253 `item`.`author-id` = %d AND `item`.`created` > '%s' AND
2254 NOT `item`.`deleted` AND NOT `item`.`private` AND
2255 `thread`.`network` IN ('%s', '%s')
2256 ORDER BY `item`.`created` DESC LIMIT %d",
2257 intval($owner["uid"]), intval($owner["id"]),
2258 intval($authorid), dbesc($check_date),
2259 dbesc(NETWORK_OSTATUS), dbesc(NETWORK_DFRN), intval($max_items));
2261 $doc = new DOMDocument('1.0', 'utf-8');
2262 $doc->formatOutput = true;
2264 $root = self::add_header($doc, $owner);
2266 foreach ($items AS $item) {
2267 if (Config::get('system', 'ostatus_debug')) {
2268 $item['body'] .= '🍼';
2270 $entry = self::entry($doc, $item, $owner);
2271 $root->appendChild($entry);
2273 if ($last_update < $item['created']) {
2274 $last_update = $item['created'];
2278 $feeddata = trim($doc->saveXML());
2280 $msg = array('feed' => $feeddata, 'last_update' => $last_update);
2281 Cache::set($cachekey, $msg, CACHE_QUARTER_HOUR);
2283 logger('Feed duration: '.number_format(microtime(true) - $stamp, 3).' - '.$owner_nick.' - '.$previous_created, LOGGER_DEBUG);
2289 * @brief Creates the XML for a salmon message
2291 * @param array $item Data of the item that is to be posted
2292 * @param array $owner Contact data of the poster
2294 * @return string XML for the salmon
2296 public static function salmon($item,$owner) {
2298 $doc = new DOMDocument('1.0', 'utf-8');
2299 $doc->formatOutput = true;
2301 if (Config::get('system', 'ostatus_debug')) {
2302 $item['body'] .= '🐟';
2305 $entry = self::entry($doc, $item, $owner, true);
2307 $doc->appendChild($entry);
2309 return trim($doc->saveXML());