2 require_once("include/Contact.php");
3 require_once("include/threads.php");
4 require_once("include/html2bbcode.php");
5 require_once("include/bbcode.php");
6 require_once("include/items.php");
7 require_once("mod/share.php");
8 require_once("include/enotify.php");
9 require_once("include/socgraph.php");
10 require_once("include/Photo.php");
11 require_once("include/Scrape.php");
12 require_once("include/follow.php");
13 require_once("include/api.php");
14 require_once("mod/proxy.php");
15 require_once("include/ostatus2.php");
17 define('OSTATUS_DEFAULT_POLL_INTERVAL', 30); // given in minutes
18 define('OSTATUS_DEFAULT_POLL_TIMEFRAME', 1440); // given in minutes
19 define('OSTATUS_DEFAULT_POLL_TIMEFRAME_MENTIONS', 14400); // given in minutes
21 function ostatus_check_follow_friends() {
22 $r = q("SELECT `uid`,`v` FROM `pconfig` WHERE `cat`='system' AND `k`='ostatus_legacy_contact' AND `v` != ''");
27 foreach ($r AS $contact) {
28 ostatus_follow_friends($contact["uid"], $contact["v"]);
29 set_pconfig($contact["uid"], "system", "ostatus_legacy_contact", "");
33 // This function doesn't work reliable by now.
34 function ostatus_follow_friends($uid, $url) {
35 $contact = probe_url($url);
40 $api = $contact["baseurl"]."/api/";
43 $data = z_fetch_url($api."statuses/friends.json?screen_name=".$contact["nick"]);
45 if (!$data["success"])
48 $friends = json_decode($data["body"]);
50 foreach ($friends AS $friend) {
51 $url = $friend->statusnet_profile_url;
52 $r = q("SELECT `url` FROM `contact` WHERE `uid` = %d AND
53 (`nurl` = '%s' OR `alias` = '%s' OR `alias` = '%s') AND
54 `network` != '%s' LIMIT 1",
55 intval($uid), dbesc(normalise_link($url)),
56 dbesc(normalise_link($url)), dbesc($url), dbesc(NETWORK_STATUSNET));
58 $data = probe_url($friend->statusnet_profile_url);
59 if ($data["network"] == NETWORK_OSTATUS) {
60 $result = new_contact($uid,$friend->statusnet_profile_url);
61 if ($result["success"])
62 logger($friend->name." ".$url." - success", LOGGER_DEBUG);
64 logger($friend->name." ".$url." - failed", LOGGER_DEBUG);
66 logger($friend->name." ".$url." - not OStatus", LOGGER_DEBUG);
71 function ostatus_fetchauthor($xpath, $context, $importer, &$contact, $onlyfetch) {
74 $author["author-link"] = $xpath->evaluate('atom:author/atom:uri/text()', $context)->item(0)->nodeValue;
75 $author["author-name"] = $xpath->evaluate('atom:author/atom:name/text()', $context)->item(0)->nodeValue;
78 $authorlink = $author["author-link"];
80 $alternate = $xpath->query("atom:author/atom:link[@rel='alternate']", $context)->item(0)->attributes;
81 if (is_object($alternate))
82 foreach($alternate AS $attributes)
83 if ($attributes->name == "href")
84 $author["author-link"] = $attributes->textContent;
86 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `nurl` IN ('%s', '%s') AND `network` != '%s'",
87 intval($importer["uid"]), dbesc(normalise_link($author["author-link"])),
88 dbesc(normalise_link($authorlink)), dbesc(NETWORK_STATUSNET));
91 $author["contact-id"] = $r[0]["id"];
93 $author["contact-id"] = $contact["id"];
95 $avatarlist = array();
96 $avatars = $xpath->query("atom:author/atom:link[@rel='avatar']", $context);
97 foreach($avatars AS $avatar) {
100 foreach($avatar->attributes AS $attributes) {
101 if ($attributes->name == "href")
102 $href = $attributes->textContent;
103 if ($attributes->name == "width")
104 $width = $attributes->textContent;
106 if (($width > 0) AND ($href != ""))
107 $avatarlist[$width] = $href;
109 if (count($avatarlist) > 0) {
111 $author["author-avatar"] = current($avatarlist);
114 $displayname = $xpath->evaluate('atom:author/poco:displayName/text()', $context)->item(0)->nodeValue;
115 if ($displayname != "")
116 $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 AND !$onlyfetch AND ($contact["network"] == NETWORK_OSTATUS)) {
124 // Update contact data
126 $value = $xpath->query("atom:link[@rel='salmon']", $context)->item(0)->nodeValue;
128 $contact["notify"] = $value;
130 $value = $xpath->evaluate('atom:author/uri/text()', $context)->item(0)->nodeValue;
132 $contact["alias"] = $value;
134 $value = $xpath->evaluate('atom:author/poco:displayName/text()', $context)->item(0)->nodeValue;
136 $contact["name"] = $value;
138 $value = $xpath->evaluate('atom:author/poco:preferredUsername/text()', $context)->item(0)->nodeValue;
140 $contact["nick"] = $value;
142 $value = $xpath->evaluate('atom:author/poco:note/text()', $context)->item(0)->nodeValue;
144 $contact["about"] = html2bbcode($value);
146 $value = $xpath->evaluate('atom:author/poco:address/poco:formatted/text()', $context)->item(0)->nodeValue;
148 $contact["location"] = $value;
150 if (($contact["name"] != $r[0]["name"]) OR ($contact["nick"] != $r[0]["nick"]) OR ($contact["about"] != $r[0]["about"]) OR ($contact["location"] != $r[0]["location"])) {
152 logger("Update contact data for contact ".$contact["id"], LOGGER_DEBUG);
154 q("UPDATE `contact` SET `name` = '%s', `nick` = '%s', `about` = '%s', `location` = '%s', `name-date` = '%s' WHERE `id` = %d",
155 dbesc($contact["name"]), dbesc($contact["nick"]), dbesc($contact["about"]), dbesc($contact["location"]),
156 dbesc(datetime_convert()), intval($contact["id"]));
158 poco_check($contact["url"], $contact["name"], $contact["network"], $author["author-avatar"], $contact["about"], $contact["location"],
159 "", "", "", datetime_convert(), 2, $contact["id"], $contact["uid"]);
162 if (isset($author["author-avatar"]) AND ($author["author-avatar"] != $r[0]['avatar'])) {
163 logger("Update profile picture for contact ".$contact["id"], LOGGER_DEBUG);
165 update_contact_avatar($author["author-avatar"], $importer["uid"], $contact["id"]);
168 $contact["generation"] = 2;
169 $contact["photo"] = $author["author-avatar"];
170 update_gcontact($contact);
176 function ostatus_salmon_author($xml, $importer) {
182 $doc = new DOMDocument();
183 @$doc->loadXML($xml);
185 $xpath = new DomXPath($doc);
186 $xpath->registerNamespace('atom', NAMESPACE_ATOM1);
187 $xpath->registerNamespace('thr', NAMESPACE_THREAD);
188 $xpath->registerNamespace('georss', NAMESPACE_GEORSS);
189 $xpath->registerNamespace('activity', NAMESPACE_ACTIVITY);
190 $xpath->registerNamespace('media', NAMESPACE_MEDIA);
191 $xpath->registerNamespace('poco', NAMESPACE_POCO);
192 $xpath->registerNamespace('ostatus', NAMESPACE_OSTATUS);
193 $xpath->registerNamespace('statusnet', NAMESPACE_STATUSNET);
195 $entries = $xpath->query('/atom:entry');
197 foreach ($entries AS $entry) {
199 $author = ostatus_fetchauthor($xpath, $entry, $importer, $contact, true);
204 function ostatus_import($xml,$importer,&$contact, &$hub) {
208 logger("Import OStatus message", LOGGER_DEBUG);
213 $doc = new DOMDocument();
214 @$doc->loadXML($xml);
216 $xpath = new DomXPath($doc);
217 $xpath->registerNamespace('atom', NAMESPACE_ATOM1);
218 $xpath->registerNamespace('thr', NAMESPACE_THREAD);
219 $xpath->registerNamespace('georss', NAMESPACE_GEORSS);
220 $xpath->registerNamespace('activity', NAMESPACE_ACTIVITY);
221 $xpath->registerNamespace('media', NAMESPACE_MEDIA);
222 $xpath->registerNamespace('poco', NAMESPACE_POCO);
223 $xpath->registerNamespace('ostatus', NAMESPACE_OSTATUS);
224 $xpath->registerNamespace('statusnet', NAMESPACE_STATUSNET);
227 $hub_attributes = $xpath->query("/atom:feed/atom:link[@rel='hub']")->item(0)->attributes;
228 if (is_object($hub_attributes))
229 foreach($hub_attributes AS $hub_attribute)
230 if ($hub_attribute->name == "href") {
231 $hub = $hub_attribute->textContent;
232 logger("Found hub ".$hub, LOGGER_DEBUG);
236 $header["uid"] = $importer["uid"];
237 $header["network"] = NETWORK_OSTATUS;
238 $header["type"] = "remote";
240 $header["origin"] = 0;
241 $header["gravity"] = GRAVITY_PARENT;
243 // it could either be a received post or a post we fetched by ourselves
244 // depending on that, the first node is different
245 $first_child = $doc->firstChild->tagName;
247 if ($first_child == "feed")
248 $entries = $xpath->query('/atom:feed/atom:entry');
250 $entries = $xpath->query('/atom:entry');
253 $conversationlist = array();
256 // Reverse the order of the entries
257 $entrylist = array();
259 foreach ($entries AS $entry)
260 $entrylist[] = $entry;
262 foreach (array_reverse($entrylist) AS $entry) {
267 if ($first_child == "feed")
268 $author = ostatus_fetchauthor($xpath, $doc->firstChild, $importer, $contact, false);
270 $author = ostatus_fetchauthor($xpath, $entry, $importer, $contact, false);
272 $value = $xpath->evaluate('atom:author/poco:preferredUsername/text()', $context)->item(0)->nodeValue;
276 $nickname = $author["author-name"];
278 $item = array_merge($header, $author);
281 $item["uri"] = $xpath->query('atom:id/text()', $entry)->item(0)->nodeValue;
283 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s'",
284 intval($importer["uid"]), dbesc($item["uri"]));
286 logger("Item with uri ".$item["uri"]." for user ".$importer["uid"]." already existed under id ".$r[0]["id"], LOGGER_DEBUG);
290 $item["body"] = add_page_info_to_body(html2bbcode($xpath->query('atom:content/text()', $entry)->item(0)->nodeValue));
291 $item["object-type"] = $xpath->query('activity:object-type/text()', $entry)->item(0)->nodeValue;
293 if (($item["object-type"] == ACTIVITY_OBJ_BOOKMARK) OR ($item["object-type"] == ACTIVITY_OBJ_EVENT)) {
294 $item["title"] = $xpath->query('atom:title/text()', $entry)->item(0)->nodeValue;
295 $item["body"] = $xpath->query('atom:summary/text()', $entry)->item(0)->nodeValue;
296 } elseif ($item["object-type"] == ACTIVITY_OBJ_QUESTION)
297 $item["title"] = $xpath->query('atom:title/text()', $entry)->item(0)->nodeValue;
299 $item["object"] = $xml;
300 $item["verb"] = $xpath->query('activity:verb/text()', $entry)->item(0)->nodeValue;
304 if ($item["verb"] == "qvitter-delete-notice") {
305 // ignore "Delete" messages (by now)
306 logger("Ignore delete message ".print_r($item, true));
310 if ($item["verb"] == ACTIVITY_JOIN) {
311 // ignore "Join" messages
312 logger("Ignore join message ".print_r($item, true));
316 if ($item["verb"] == ACTIVITY_FOLLOW) {
317 new_follower($importer, $contact, $item, $nickname);
321 if ($item["verb"] == NAMESPACE_OSTATUS."/unfollow") {
322 lose_follower($importer, $contact, $item, $dummy);
326 if ($item["verb"] == ACTIVITY_FAVORITE) {
327 $orig_uri = $xpath->query("activity:object/atom:id", $entry)->item(0)->nodeValue;
328 logger("Favorite ".$orig_uri." ".print_r($item, true));
330 $item["verb"] = ACTIVITY_LIKE;
331 $item["parent-uri"] = $orig_uri;
332 $item["gravity"] = GRAVITY_LIKE;
335 if ($item["verb"] == NAMESPACE_OSTATUS."/unfavorite") {
336 // Ignore "Unfavorite" message
337 logger("Ignore unfavorite message ".print_r($item, true));
341 // http://activitystrea.ms/schema/1.0/rsvp-yes
342 if (!in_array($item["verb"], array(ACTIVITY_POST, ACTIVITY_LIKE, ACTIVITY_SHARE)))
343 logger("Unhandled verb ".$item["verb"]." ".print_r($item, true));
345 $item["created"] = $xpath->query('atom:published/text()', $entry)->item(0)->nodeValue;
346 $item["edited"] = $xpath->query('atom:updated/text()', $entry)->item(0)->nodeValue;
347 $conversation = $xpath->query('ostatus:conversation/text()', $entry)->item(0)->nodeValue;
351 $inreplyto = $xpath->query('thr:in-reply-to', $entry);
352 if (is_object($inreplyto->item(0))) {
353 foreach($inreplyto->item(0)->attributes AS $attributes) {
354 if ($attributes->name == "ref")
355 $item["parent-uri"] = $attributes->textContent;
356 if ($attributes->name == "href")
357 $related = $attributes->textContent;
361 $georsspoint = $xpath->query('georss:point', $entry);
363 $item["coord"] = $georsspoint->item(0)->nodeValue;
366 /// $item["location"] =
368 $categories = $xpath->query('atom:category', $entry);
370 foreach ($categories AS $category) {
371 foreach($category->attributes AS $attributes)
372 if ($attributes->name == "term") {
373 $term = $attributes->textContent;
374 if(strlen($item["tag"]))
376 $item["tag"] .= "#[url=".$a->get_baseurl()."/search?tag=".$term."]".$term."[/url]";
384 $links = $xpath->query('atom:link', $entry);
391 foreach ($links AS $link) {
392 foreach($link->attributes AS $attributes) {
393 if ($attributes->name == "href")
394 $href = $attributes->textContent;
395 if ($attributes->name == "rel")
396 $rel = $attributes->textContent;
397 if ($attributes->name == "type")
398 $type = $attributes->textContent;
399 if ($attributes->name == "length")
400 $length = $attributes->textContent;
401 if ($attributes->name == "title")
402 $title = $attributes->textContent;
404 if (($rel != "") AND ($href != ""))
407 $item["plink"] = $href;
408 if (($item["object-type"] == ACTIVITY_OBJ_QUESTION) OR
409 ($item["object-type"] == ACTIVITY_OBJ_EVENT))
410 $item["body"] .= add_page_info($href);
412 case "ostatus:conversation":
413 $conversation = $href;
417 if(strlen($item["attach"]))
418 $item["attach"] .= ',';
420 $item["attach"] .= '[attach]href="'.$href.'" length="'.$length.'" type="'.$type.'" title="'.$title.'"[/attach]';
423 if ($item["object-type"] != ACTIVITY_OBJ_BOOKMARK) {
424 if (!isset($item["parent-uri"]))
425 $item["parent-uri"] = $href;
430 $item["body"] .= add_page_info($href);
436 // Notification check
437 if ($importer["nurl"] == normalise_link($href))
447 $notice_info = $xpath->query('statusnet:notice_info', $entry);
448 if ($notice_info AND ($notice_info->length > 0)) {
449 foreach($notice_info->item(0)->attributes AS $attributes) {
450 if ($attributes->name == "source")
451 $item["app"] = strip_tags($attributes->textContent);
452 if ($attributes->name == "local_id")
453 $local_id = $attributes->textContent;
454 if ($attributes->name == "repeat_of")
455 $repeat_of = $attributes->textContent;
459 // Is it a repeated post?
460 if ($repeat_of != "") {
461 $activityobjects = $xpath->query('activity:object', $entry)->item(0);
463 if (is_object($activityobjects)) {
465 $orig_uri = $xpath->query("activity:object/atom:id", $activityobjects)->item(0)->nodeValue;
466 if (!isset($orig_uri))
467 $orig_uri = $xpath->query('atom:id/text()', $activityobjects)->item(0)->nodeValue;
469 $orig_links = $xpath->query("activity:object/atom:link[@rel='alternate']", $activityobjects);
470 if ($orig_links AND ($orig_links->length > 0))
471 foreach($orig_links->item(0)->attributes AS $attributes)
472 if ($attributes->name == "href")
473 $orig_link = $attributes->textContent;
475 if (!isset($orig_link))
476 $orig_link = $xpath->query("atom:link[@rel='alternate']", $activityobjects)->item(0)->nodeValue;
478 if (!isset($orig_link))
479 $orig_link = ostatus_convert_href($orig_uri);
481 $orig_body = $xpath->query('activity:object/atom:content/text()', $activityobjects)->item(0)->nodeValue;
482 if (!isset($orig_body))
483 $orig_body = $xpath->query('atom:content/text()', $activityobjects)->item(0)->nodeValue;
485 $orig_created = $xpath->query('atom:published/text()', $activityobjects)->item(0)->nodeValue;
487 $orig_contact = $contact;
488 $orig_author = ostatus_fetchauthor($xpath, $activityobjects, $importer, $orig_contact, false);
490 //if (!intval(get_config('system','wall-to-wall_share'))) {
491 // $prefix = share_header($orig_author['author-name'], $orig_author['author-link'], $orig_author['author-avatar'], "", $orig_created, $orig_link);
492 // $item["body"] = $prefix.add_page_info_to_body(html2bbcode($orig_body))."[/share]";
494 $item["author-name"] = $orig_author["author-name"];
495 $item["author-link"] = $orig_author["author-link"];
496 $item["author-avatar"] = $orig_author["author-avatar"];
497 $item["body"] = add_page_info_to_body(html2bbcode($orig_body));
498 $item["created"] = $orig_created;
500 $item["uri"] = $orig_uri;
501 $item["plink"] = $orig_link;
504 $item["verb"] = $xpath->query('activity:verb/text()', $activityobjects)->item(0)->nodeValue;
506 $item["object-type"] = $xpath->query('activity:object/activity:object-type/text()', $activityobjects)->item(0)->nodeValue;
507 if (!isset($item["object-type"]))
508 $item["object-type"] = $xpath->query('activity:object-type/text()', $activityobjects)->item(0)->nodeValue;
512 //if ($enclosure != "")
513 // $item["body"] .= add_page_info($enclosure);
515 if (isset($item["parent-uri"])) {
516 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s'",
517 intval($importer["uid"]), dbesc($item["parent-uri"]));
519 if (!$r AND ($related != "")) {
520 $reply_path = str_replace("/notice/", "/api/statuses/show/", $related).".atom";
522 if ($reply_path != $related) {
523 logger("Fetching related items for user ".$importer["uid"]." from ".$reply_path, LOGGER_DEBUG);
524 $reply_xml = fetch_url($reply_path);
526 $reply_contact = $contact;
527 ostatus_import($reply_xml,$importer,$reply_contact, $reply_hub);
529 // After the import try to fetch the parent item again
530 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s'",
531 intval($importer["uid"]), dbesc($item["parent-uri"]));
535 $item["type"] = 'remote-comment';
536 $item["gravity"] = GRAVITY_COMMENT;
539 $item["parent-uri"] = $item["uri"];
541 $item_id = ostatus_completion($conversation, $importer["uid"], $item, $self);
544 logger("Error storing item", LOGGER_DEBUG);
548 logger("Item was stored with id ".$item_id, LOGGER_DEBUG);
552 function ostatus_convert_href($href) {
553 $elements = explode(":",$href);
555 if ((count($elements) <= 2) OR ($elements[0] != "tag"))
558 $server = explode(",", $elements[1]);
559 $conversation = explode("=", $elements[2]);
561 if ((count($elements) == 4) AND ($elements[2] == "post"))
562 return "http://".$server[0]."/notice/".$elements[3];
564 if ((count($conversation) != 2) OR ($conversation[1] ==""))
567 if ($elements[3] == "objectType=thread")
568 return "http://".$server[0]."/conversation/".$conversation[1];
570 return "http://".$server[0]."/notice/".$conversation[1];
575 function check_conversations($mentions = false, $override = false) {
576 $last = get_config('system','ostatus_last_poll');
578 $poll_interval = intval(get_config('system','ostatus_poll_interval'));
580 $poll_interval = OSTATUS_DEFAULT_POLL_INTERVAL;
582 // Don't poll if the interval is set negative
583 if (($poll_interval < 0) AND !$override)
587 $poll_timeframe = intval(get_config('system','ostatus_poll_timeframe'));
588 if (!$poll_timeframe)
589 $poll_timeframe = OSTATUS_DEFAULT_POLL_TIMEFRAME;
591 $poll_timeframe = intval(get_config('system','ostatus_poll_timeframe'));
592 if (!$poll_timeframe)
593 $poll_timeframe = OSTATUS_DEFAULT_POLL_TIMEFRAME_MENTIONS;
597 if ($last AND !$override) {
598 $next = $last + ($poll_interval * 60);
599 if ($next > time()) {
600 logger('poll interval not reached');
605 logger('cron_start');
607 $start = date("Y-m-d H:i:s", time() - ($poll_timeframe * 60));
610 $conversations = q("SELECT `term`.`oid`, `term`.`url`, `term`.`uid` FROM `term`
611 STRAIGHT_JOIN `thread` ON `thread`.`iid` = `term`.`oid` AND `thread`.`uid` = `term`.`uid`
612 WHERE `term`.`type` = 7 AND `term`.`term` > '%s' AND `thread`.`mention`
613 GROUP BY `term`.`url`, `term`.`uid` ORDER BY `term`.`term` DESC", dbesc($start));
615 $conversations = q("SELECT `oid`, `url`, `uid` FROM `term`
616 WHERE `type` = 7 AND `term` > '%s'
617 GROUP BY `url`, `uid` ORDER BY `term` DESC", dbesc($start));
619 foreach ($conversations AS $conversation) {
620 ostatus_completion($conversation['url'], $conversation['uid']);
625 set_config('system','ostatus_last_poll', time());
629 * @brief Updates the gcontact table with actor data from the conversation
631 * @param object $actor The actor object that contains the contact data
633 function ostatus_conv_fetch_actor($actor) {
635 // We set the generation to "3" since the data here is not as reliable as the data we get on other occasions
636 $contact = array("network" => NETWORK_OSTATUS, "generation" => 3);
638 if (isset($actor->url))
639 $contact["url"] = $actor->url;
641 if (isset($actor->displayName))
642 $contact["name"] = $actor->displayName;
644 if (isset($actor->portablecontacts_net->displayName))
645 $contact["name"] = $actor->portablecontacts_net->displayName;
647 if (isset($actor->portablecontacts_net->preferredUsername))
648 $contact["nick"] = $actor->portablecontacts_net->preferredUsername;
650 if (isset($actor->id))
651 $contact["alias"] = $actor->id;
653 if (isset($actor->summary))
654 $contact["about"] = $actor->summary;
656 if (isset($actor->portablecontacts_net->note))
657 $contact["about"] = $actor->portablecontacts_net->note;
659 if (isset($actor->portablecontacts_net->addresses->formatted))
660 $contact["location"] = $actor->portablecontacts_net->addresses->formatted;
663 if (isset($actor->image->url))
664 $contact["photo"] = $actor->image->url;
666 if (isset($actor->image->width))
667 $avatarwidth = $actor->image->width;
669 if (is_array($actor->status_net->avatarLinks))
670 foreach ($actor->status_net->avatarLinks AS $avatar) {
671 if ($avatarsize < $avatar->width) {
672 $contact["photo"] = $avatar->url;
673 $avatarsize = $avatar->width;
677 update_gcontact($contact);
681 * @brief Fetches the conversation url for a given item link or conversation id
683 * @param string $self The link to the posting
684 * @param string $conversation_id The conversation id
686 * @return string The conversation url
688 function ostatus_fetch_conversation($self, $conversation_id = "") {
690 if ($conversation_id != "") {
691 $elements = explode(":", $conversation_id);
693 if ((count($elements) <= 2) OR ($elements[0] != "tag"))
694 return $conversation_id;
700 $json = str_replace(".atom", ".json", $self);
702 $raw = fetch_url($json);
706 $data = json_decode($raw);
707 if (!is_object($data))
710 $conversation_id = $data->statusnet_conversation_id;
712 $pos = strpos($self, "/api/statuses/show/");
713 $base_url = substr($self, 0, $pos);
715 return $base_url."/conversation/".$conversation_id;
719 * @brief Fetches actor details of a given actor and user id
721 * @param string $actor The actor url
722 * @param int $uid The user id
723 * @param int $contact_id The default contact-id
725 * @return array Array with actor details
727 function ostatus_get_actor_details($actor, $uid, $contact_id) {
731 $contact = q("SELECT `id`, `rel`, `network` FROM `contact` WHERE `uid` = %d AND `nurl` = '%s' AND `network` != '%s'",
732 $uid, normalise_link($actor), NETWORK_STATUSNET);
735 $contact = q("SELECT `id`, `rel`, `network` FROM `contact` WHERE `uid` = %d AND `alias` IN ('%s', '%s') AND `network` != '%s'",
736 $uid, $actor, normalise_link($actor), NETWORK_STATUSNET);
739 logger("Found contact for url ".$actor, LOGGER_DEBUG);
740 $details["contact_id"] = $contact[0]["id"];
741 $details["network"] = $contact[0]["network"];
743 $details["not_following"] = !in_array($contact[0]["rel"], array(CONTACT_IS_SHARING, CONTACT_IS_FRIEND));
745 logger("No contact found for user ".$uid." and url ".$actor, LOGGER_DEBUG);
747 // Adding a global contact
748 /// @TODO Use this data for the post
749 $details["global_contact_id"] = get_contact($actor, 0);
751 logger("Global contact ".$global_contact_id." found for url ".$actor, LOGGER_DEBUG);
753 $details["contact_id"] = $contact_id;
754 $details["network"] = NETWORK_OSTATUS;
756 $details["not_following"] = true;
762 function ostatus_completion($conversation_url, $uid, $item = array(), $self = "") {
768 //$conversation_url = ostatus_convert_href($conversation_url);
769 $conversation_url = ostatus_fetch_conversation($self, $conversation_url);
771 // If the thread shouldn't be completed then store the item and go away
772 // Don't do a completion on liked content
773 if (((intval(get_config('system','ostatus_poll_interval')) == -2) AND (count($item) > 0)) OR
774 ($item["verb"] == ACTIVITY_LIKE) OR ($conversation_url == "")) {
775 //$arr["app"] .= " (OStatus-NoCompletion)";
776 $item_stored = item_store($item, true);
777 return($item_stored);
781 $parents = q("SELECT `id`, `parent`, `uri`, `contact-id`, `type`, `verb`, `visible` FROM `item` WHERE `id` IN
782 (SELECT `parent` FROM `item` WHERE `id` IN
783 (SELECT `oid` FROM `term` WHERE `uid` = %d AND `otype` = %d AND `type` = %d AND `url` = '%s'))",
784 intval($uid), intval(TERM_OBJ_POST), intval(TERM_CONVERSATION), dbesc($conversation_url));
787 $parent = $parents[0];
788 elseif (count($item) > 0) {
790 $parent["type"] = "remote";
791 $parent["verb"] = ACTIVITY_POST;
792 $parent["visible"] = 1;
795 $r = q("SELECT `id` FROM `contact` WHERE `self` AND `uid`=%d", $uid);
801 $parent["parent"] = 0;
803 $parent["contact-id"] = $r[0]["id"];
804 $parent["type"] = "remote";
805 $parent["verb"] = ACTIVITY_POST;
806 $parent["visible"] = 1;
809 $conv = str_replace("/conversation/", "/api/statusnet/conversation/", $conversation_url).".as";
813 logger('fetching conversation url '.$conv.' (Self: '.$self.') for user '.$uid);
816 $conv_arr = z_fetch_url($conv."?page=".$pageno);
818 // If it is a non-ssl site and there is an error, then try ssl or vice versa
819 if (!$conv_arr["success"] AND (substr($conv, 0, 7) == "http://")) {
820 $conv = str_replace("http://", "https://", $conv);
821 $conv_as = fetch_url($conv."?page=".$pageno);
822 } elseif (!$conv_arr["success"] AND (substr($conv, 0, 8) == "https://")) {
823 $conv = str_replace("https://", "http://", $conv);
824 $conv_as = fetch_url($conv."?page=".$pageno);
826 $conv_as = $conv_arr["body"];
828 $conv_as = str_replace(',"statusnet:notice_info":', ',"statusnet_notice_info":', $conv_as);
829 $conv_as = json_decode($conv_as);
831 $no_of_items = sizeof($items);
833 if (@is_array($conv_as->items))
834 foreach ($conv_as->items AS $single_item)
835 $items[$single_item->id] = $single_item;
837 if ($no_of_items == sizeof($items))
844 logger('fetching conversation done. Found '.count($items).' items');
846 if (!sizeof($items)) {
847 if (count($item) > 0) {
848 //$arr["app"] .= " (OStatus-NoConvFetched)";
849 $item_stored = item_store($item, true);
852 logger("Conversation ".$conversation_url." couldn't be fetched. Item uri ".$item["uri"]." stored: ".$item_stored, LOGGER_DEBUG);
853 ostatus_store_conversation($item_id, $conversation_url);
856 return($item_stored);
861 $items = array_reverse($items);
863 $r = q("SELECT `nurl` FROM `contact` WHERE `uid` = %d AND `self`", intval($uid));
868 foreach ($items as $single_conv) {
870 // Update the gcontact table
871 ostatus_conv_fetch_actor($single_conv->actor);
873 // Test - remove before flight
874 //$tempfile = tempnam(get_temppath(), "conversation");
875 //file_put_contents($tempfile, json_encode($single_conv));
879 if (isset($single_conv->object->id))
880 $single_conv->id = $single_conv->object->id;
882 $plink = ostatus_convert_href($single_conv->id);
883 if (isset($single_conv->object->url))
884 $plink = ostatus_convert_href($single_conv->object->url);
886 if (@!$single_conv->id)
889 logger("Got id ".$single_conv->id, LOGGER_DEBUG);
891 if ($first_id == "") {
892 $first_id = $single_conv->id;
894 // The first post of the conversation isn't our first post. There are three options:
895 // 1. Our conversation hasn't the "real" thread starter
896 // 2. This first post is a post inside our thread
897 // 3. This first post is a post inside another thread
898 if (($first_id != $parent["uri"]) AND ($parent["uri"] != "")) {
902 $new_parents = q("SELECT `id`, `parent`, `uri`, `contact-id`, `type`, `verb`, `visible` FROM `item` WHERE `id` IN
903 (SELECT `parent` FROM `item`
904 WHERE `uid` = %d AND `uri` = '%s' AND `network` IN ('%s','%s')) LIMIT 1",
905 intval($uid), dbesc($first_id), dbesc(NETWORK_OSTATUS), dbesc(NETWORK_DFRN));
907 if ($new_parents[0]["parent"] == $parent["parent"]) {
908 // Option 2: This post is already present inside our thread - but not as thread starter
909 logger("Option 2: uri present in our thread: ".$first_id, LOGGER_DEBUG);
910 $first_id = $parent["uri"];
912 // Option 3: Not so good. We have mixed parents. We have to see how to clean this up.
913 // For now just take the new parent.
914 $parent = $new_parents[0];
915 $first_id = $parent["uri"];
916 logger("Option 3: mixed parents for uri ".$first_id, LOGGER_DEBUG);
919 // Option 1: We hadn't got the real thread starter
920 // We have to clean up our existing messages.
922 $parent["uri"] = $first_id;
923 logger("Option 1: we have a new parent: ".$first_id, LOGGER_DEBUG);
925 } elseif ($parent["uri"] == "") {
927 $parent["uri"] = $first_id;
931 $parent_uri = $parent["uri"];
933 // "context" only seems to exist on older servers
934 if (isset($single_conv->context->inReplyTo->id)) {
935 $parent_exists = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `network` IN ('%s','%s') LIMIT 1",
936 intval($uid), dbesc($single_conv->context->inReplyTo->id), dbesc(NETWORK_OSTATUS), dbesc(NETWORK_DFRN));
938 $parent_uri = $single_conv->context->inReplyTo->id;
941 // This is the current way
942 if (isset($single_conv->object->inReplyTo->id)) {
943 $parent_exists = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `network` IN ('%s','%s') LIMIT 1",
944 intval($uid), dbesc($single_conv->object->inReplyTo->id), dbesc(NETWORK_OSTATUS), dbesc(NETWORK_DFRN));
946 $parent_uri = $single_conv->object->inReplyTo->id;
949 $message_exists = q("SELECT `id`, `parent`, `uri` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `network` IN ('%s','%s') LIMIT 1",
950 intval($uid), dbesc($single_conv->id),
951 dbesc(NETWORK_OSTATUS), dbesc(NETWORK_DFRN));
952 if ($message_exists) {
953 logger("Message ".$single_conv->id." already existed on the system", LOGGER_DEBUG);
955 if ($parent["id"] != 0) {
956 $existing_message = $message_exists[0];
958 // We improved the way we fetch OStatus messages, this shouldn't happen very often now
959 /// @TODO We have to change the shadow copies as well. This way here is really ugly.
960 if ($existing_message["parent"] != $parent["id"]) {
961 logger('updating id '.$existing_message["id"].' with parent '.$existing_message["parent"].' to parent '.$parent["id"].' uri '.$parent["uri"].' thread '.$parent_uri, LOGGER_DEBUG);
963 // Update the parent id of the selected item
964 $r = q("UPDATE `item` SET `parent` = %d, `parent-uri` = '%s' WHERE `id` = %d",
965 intval($parent["id"]), dbesc($parent["uri"]), intval($existing_message["id"]));
967 // Update the parent uri in the thread - but only if it points to itself
968 $r = q("UPDATE `item` SET `thr-parent` = '%s' WHERE `id` = %d AND `uri` = `thr-parent`",
969 dbesc($parent_uri), intval($existing_message["id"]));
971 // try to change all items of the same parent
972 $r = q("UPDATE `item` SET `parent` = %d, `parent-uri` = '%s' WHERE `parent` = %d",
973 intval($parent["id"]), dbesc($parent["uri"]), intval($existing_message["parent"]));
975 // Update the parent uri in the thread - but only if it points to itself
976 $r = q("UPDATE `item` SET `thr-parent` = '%s' WHERE (`parent` = %d) AND (`uri` = `thr-parent`)",
977 dbesc($parent["uri"]), intval($existing_message["parent"]));
979 // Now delete the thread
980 delete_thread($existing_message["parent"]);
984 // The item we are having on the system is the one that we wanted to store via the item array
985 if (isset($item["uri"]) AND ($item["uri"] == $existing_message["uri"])) {
993 if (is_array($single_conv->to))
994 foreach($single_conv->to AS $to)
995 if ($importer["nurl"] == normalise_link($to->id))
998 $actor = $single_conv->actor->id;
999 if (isset($single_conv->actor->url))
1000 $actor = $single_conv->actor->url;
1002 $details = ostatus_get_actor_details($actor, $uid, $parent["contact-id"]);
1004 // Do we only want to import threads that were started by our contacts?
1005 if ($details["not_following"] AND $new_parent AND get_config('system','ostatus_full_threads')) {
1006 logger("Don't import uri ".$first_id." because user ".$uid." doesn't follow the person ".$actor, LOGGER_DEBUG);
1011 $arr["network"] = $details["network"];
1012 $arr["uri"] = $single_conv->id;
1013 $arr["plink"] = $plink;
1015 $arr["contact-id"] = $details["contact_id"];
1016 $arr["parent-uri"] = $parent_uri;
1017 $arr["created"] = $single_conv->published;
1018 $arr["edited"] = $single_conv->published;
1019 $arr["owner-name"] = $single_conv->actor->displayName;
1020 if ($arr["owner-name"] == '')
1021 $arr["owner-name"] = $single_conv->actor->contact->displayName;
1022 if ($arr["owner-name"] == '')
1023 $arr["owner-name"] = $single_conv->actor->portablecontacts_net->displayName;
1025 $arr["owner-link"] = $actor;
1026 $arr["owner-avatar"] = $single_conv->actor->image->url;
1027 $arr["author-name"] = $arr["owner-name"];
1028 $arr["author-link"] = $actor;
1029 $arr["author-avatar"] = $single_conv->actor->image->url;
1030 $arr["body"] = add_page_info_to_body(html2bbcode($single_conv->content));
1032 if (isset($single_conv->status_net->notice_info->source))
1033 $arr["app"] = strip_tags($single_conv->status_net->notice_info->source);
1034 elseif (isset($single_conv->statusnet->notice_info->source))
1035 $arr["app"] = strip_tags($single_conv->statusnet->notice_info->source);
1036 elseif (isset($single_conv->statusnet_notice_info->source))
1037 $arr["app"] = strip_tags($single_conv->statusnet_notice_info->source);
1038 elseif (isset($single_conv->provider->displayName))
1039 $arr["app"] = $single_conv->provider->displayName;
1041 $arr["app"] = "OStatus";
1043 //$arr["app"] .= " (Conversation)";
1045 $arr["object"] = json_encode($single_conv);
1046 $arr["verb"] = $parent["verb"];
1047 $arr["visible"] = $parent["visible"];
1048 $arr["location"] = $single_conv->location->displayName;
1049 $arr["coord"] = trim($single_conv->location->lat." ".$single_conv->location->lon);
1051 // Is it a reshared item?
1052 if (isset($single_conv->verb) AND ($single_conv->verb == "share") AND isset($single_conv->object)) {
1053 if (is_array($single_conv->object))
1054 $single_conv->object = $single_conv->object[0];
1056 logger("Found reshared item ".$single_conv->object->id);
1058 // $single_conv->object->context->conversation;
1060 if (isset($single_conv->object->object->id))
1061 $arr["uri"] = $single_conv->object->object->id;
1063 $arr["uri"] = $single_conv->object->id;
1065 if (isset($single_conv->object->object->url))
1066 $plink = ostatus_convert_href($single_conv->object->object->url);
1068 $plink = ostatus_convert_href($single_conv->object->url);
1070 if (isset($single_conv->object->object->content))
1071 $arr["body"] = add_page_info_to_body(html2bbcode($single_conv->object->object->content));
1073 $arr["body"] = add_page_info_to_body(html2bbcode($single_conv->object->content));
1075 $arr["plink"] = $plink;
1077 $arr["created"] = $single_conv->object->published;
1078 $arr["edited"] = $single_conv->object->published;
1080 $arr["author-name"] = $single_conv->object->actor->displayName;
1081 if ($arr["owner-name"] == '')
1082 $arr["author-name"] = $single_conv->object->actor->contact->displayName;
1084 $arr["author-link"] = $single_conv->object->actor->url;
1085 $arr["author-avatar"] = $single_conv->object->actor->image->url;
1087 $arr["app"] = $single_conv->object->provider->displayName."#";
1088 //$arr["verb"] = $single_conv->object->verb;
1090 $arr["location"] = $single_conv->object->location->displayName;
1091 $arr["coord"] = trim($single_conv->object->location->lat." ".$single_conv->object->location->lon);
1094 if ($arr["location"] == "")
1095 unset($arr["location"]);
1097 if ($arr["coord"] == "")
1098 unset($arr["coord"]);
1100 // Copy fields from given item array
1101 if (isset($item["uri"]) AND (($item["uri"] == $arr["uri"]) OR ($item["uri"] == $single_conv->id))) {
1102 $copy_fields = array("owner-name", "owner-link", "owner-avatar", "author-name", "author-link", "author-avatar",
1103 "gravity", "body", "object-type", "object", "verb", "created", "edited", "coord", "tag",
1104 "title", "attach", "app", "type", "location", "contact-id", "uri");
1105 foreach ($copy_fields AS $field)
1106 if (isset($item[$field]))
1107 $arr[$field] = $item[$field];
1109 //$arr["app"] .= " (OStatus)";
1112 $newitem = item_store($arr);
1114 logger("Item wasn't stored ".print_r($arr, true), LOGGER_DEBUG);
1118 if (isset($item["uri"]) AND ($item["uri"] == $arr["uri"])) {
1120 $item_stored = $newitem;
1123 logger('Stored new item '.$plink.' for parent '.$arr["parent-uri"].' under id '.$newitem, LOGGER_DEBUG);
1125 // Add the conversation entry (but don't fetch the whole conversation)
1126 ostatus_store_conversation($newitem, $conversation_url);
1128 // If the newly created item is the top item then change the parent settings of the thread
1129 // This shouldn't happen anymore. This is supposed to be absolote.
1130 if ($arr["uri"] == $first_id) {
1131 logger('setting new parent to id '.$newitem);
1132 $new_parents = q("SELECT `id`, `uri`, `contact-id`, `type`, `verb`, `visible` FROM `item` WHERE `uid` = %d AND `id` = %d LIMIT 1",
1133 intval($uid), intval($newitem));
1135 $parent = $new_parents[0];
1139 if (($item_stored < 0) AND (count($item) > 0)) {
1140 //$arr["app"] .= " (OStatus-NoConvFound)";
1142 if (get_config('system','ostatus_full_threads')) {
1143 $details = ostatus_get_actor_details($item["owner-link"], $uid, $item["contact-id"]);
1144 if ($details["not_following"]) {
1145 logger("Don't import uri ".$item["uri"]." because user ".$uid." doesn't follow the person ".$item["owner-link"], LOGGER_DEBUG);
1150 $item_stored = item_store($item, true);
1152 logger("Uri ".$item["uri"]." wasn't found in conversation ".$conversation_url, LOGGER_DEBUG);
1153 ostatus_store_conversation($item_stored, $conversation_url);
1157 return($item_stored);
1160 function ostatus_store_conversation($itemid, $conversation_url) {
1163 $conversation_url = ostatus_convert_href($conversation_url);
1165 $messages = q("SELECT `uid`, `parent`, `created`, `received`, `guid` FROM `item` WHERE `id` = %d LIMIT 1", intval($itemid));
1168 $message = $messages[0];
1170 // Store conversation url if not done before
1171 $conversation = q("SELECT `url` FROM `term` WHERE `uid` = %d AND `oid` = %d AND `otype` = %d AND `type` = %d",
1172 intval($message["uid"]), intval($itemid), intval(TERM_OBJ_POST), intval(TERM_CONVERSATION));
1174 if (!$conversation) {
1175 $r = q("INSERT INTO `term` (`uid`, `oid`, `otype`, `type`, `term`, `url`, `created`, `received`, `guid`) VALUES (%d, %d, %d, %d, '%s', '%s', '%s', '%s', '%s')",
1176 intval($message["uid"]), intval($itemid), intval(TERM_OBJ_POST), intval(TERM_CONVERSATION),
1177 dbesc($message["created"]), dbesc($conversation_url), dbesc($message["created"]), dbesc($message["received"]), dbesc($message["guid"]));
1178 logger('Storing conversation url '.$conversation_url.' for id '.$itemid);
1182 function get_reshared_guid($item) {
1183 $body = trim($item["body"]);
1185 // Skip if it isn't a pure repeated messages
1186 // Does it start with a share?
1187 if (strpos($body, "[share") > 0)
1190 // Does it end with a share?
1191 if (strlen($body) > (strrpos($body, "[/share]") + 8))
1194 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$1",$body);
1195 // Skip if there is no shared message in there
1196 if ($body == $attributes)
1200 preg_match("/guid='(.*?)'/ism", $attributes, $matches);
1201 if ($matches[1] != "")
1202 $guid = $matches[1];
1204 preg_match('/guid="(.*?)"/ism', $attributes, $matches);
1205 if ($matches[1] != "")
1206 $guid = $matches[1];
1211 function xml_create_element($doc, $element, $value = "", $attributes = array()) {
1212 $element = $doc->createElement($element, xmlify($value));
1214 foreach ($attributes AS $key => $value) {
1215 $attribute = $doc->createAttribute($key);
1216 $attribute->value = xmlify($value);
1217 $element->appendChild($attribute);
1222 function xml_add_element($doc, $parent, $element, $value = "", $attributes = array()) {
1223 $element = xml_create_element($doc, $element, $value, $attributes);
1224 $parent->appendChild($element);
1227 function ostatus_format_picture_post($body) {
1228 $siteinfo = get_attached_data($body);
1230 if (($siteinfo["type"] == "photo")) {
1231 if (isset($siteinfo["preview"]))
1232 $preview = $siteinfo["preview"];
1234 $preview = $siteinfo["image"];
1236 // Is it a remote picture? Then make a smaller preview here
1237 $preview = proxy_url($preview, false, PROXY_SIZE_SMALL);
1239 // Is it a local picture? Then make it smaller here
1240 $preview = str_replace(array("-0.jpg", "-0.png"), array("-2.jpg", "-2.png"), $preview);
1241 $preview = str_replace(array("-1.jpg", "-1.png"), array("-2.jpg", "-2.png"), $preview);
1243 if (isset($siteinfo["url"]))
1244 $url = $siteinfo["url"];
1246 $url = $siteinfo["image"];
1248 $body = trim($siteinfo["text"])." [url]".$url."[/url]\n[img]".$preview."[/img]";
1254 function ostatus_add_header($doc, $owner) {
1257 $root = $doc->createElementNS(NAMESPACE_ATOM1, 'feed');
1258 $doc->appendChild($root);
1260 $root->setAttribute("xmlns:thr", NAMESPACE_THREAD);
1261 $root->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
1262 $root->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
1263 $root->setAttribute("xmlns:media", NAMESPACE_MEDIA);
1264 $root->setAttribute("xmlns:poco", NAMESPACE_POCO);
1265 $root->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
1266 $root->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
1268 $attributes = array("uri" => "https://friendi.ca", "version" => FRIENDICA_VERSION."-".DB_UPDATE_VERSION);
1269 xml_add_element($doc, $root, "generator", FRIENDICA_PLATFORM, $attributes);
1270 xml_add_element($doc, $root, "id", $a->get_baseurl()."/profile/".$owner["nick"]);
1271 xml_add_element($doc, $root, "title", sprintf("%s timeline", $owner["name"]));
1272 xml_add_element($doc, $root, "subtitle", sprintf("Updates from %s on %s", $owner["name"], $a->config["sitename"]));
1273 xml_add_element($doc, $root, "logo", $owner["photo"]);
1274 xml_add_element($doc, $root, "updated", datetime_convert("UTC", "UTC", "now", ATOM_TIME));
1276 $author = ostatus_add_author($doc, $owner);
1277 $root->appendChild($author);
1279 $attributes = array("href" => $owner["url"], "rel" => "alternate", "type" => "text/html");
1280 xml_add_element($doc, $root, "link", "", $attributes);
1282 /// @TODO We have to find out what this is
1283 /// $attributes = array("href" => $a->get_baseurl()."/sup",
1284 /// "rel" => "http://api.friendfeed.com/2008/03#sup",
1285 /// "type" => "application/json");
1286 /// xml_add_element($doc, $root, "link", "", $attributes);
1288 ostatus_hublinks($doc, $root);
1290 $attributes = array("href" => $a->get_baseurl()."/salmon/".$owner["nick"], "rel" => "salmon");
1291 xml_add_element($doc, $root, "link", "", $attributes);
1293 $attributes = array("href" => $a->get_baseurl()."/salmon/".$owner["nick"], "rel" => "http://salmon-protocol.org/ns/salmon-replies");
1294 xml_add_element($doc, $root, "link", "", $attributes);
1296 $attributes = array("href" => $a->get_baseurl()."/salmon/".$owner["nick"], "rel" => "http://salmon-protocol.org/ns/salmon-mention");
1297 xml_add_element($doc, $root, "link", "", $attributes);
1299 $attributes = array("href" => $a->get_baseurl()."/api/statuses/user_timeline/".$owner["nick"].".atom",
1300 "rel" => "self", "type" => "application/atom+xml");
1301 xml_add_element($doc, $root, "link", "", $attributes);
1306 function ostatus_hublinks($doc, $root) {
1308 $hub = get_config('system','huburl');
1312 $hubs = explode(',', $hub);
1314 foreach($hubs as $h) {
1318 if ($h === '[internal]')
1319 $h = $a->get_baseurl() . '/pubsubhubbub';
1320 xml_add_element($doc, $root, "link", "", array("href" => $h, "rel" => "hub"));
1326 function ostatus_get_attachment($doc, $root, $item) {
1328 $siteinfo = get_attached_data($item["body"]);
1330 switch($siteinfo["type"]) {
1332 $attributes = array("rel" => "enclosure",
1333 "href" => $siteinfo["url"],
1334 "type" => "text/html; charset=UTF-8",
1336 "title" => $siteinfo["title"]);
1337 xml_add_element($doc, $root, "link", "", $attributes);
1340 $imgdata = get_photo_info($siteinfo["image"]);
1341 $attributes = array("rel" => "enclosure",
1342 "href" => $siteinfo["image"],
1343 "type" => $imgdata["mime"],
1344 "length" => intval($imgdata["size"]));
1345 xml_add_element($doc, $root, "link", "", $attributes);
1348 $attributes = array("rel" => "enclosure",
1349 "href" => $siteinfo["url"],
1350 "type" => "text/html; charset=UTF-8",
1352 "title" => $siteinfo["title"]);
1353 xml_add_element($doc, $root, "link", "", $attributes);
1359 if (($siteinfo["type"] != "photo") AND isset($siteinfo["image"])) {
1360 $photodata = get_photo_info($siteinfo["image"]);
1362 $attributes = array("rel" => "preview", "href" => $siteinfo["image"], "media:width" => $photodata[0], "media:height" => $photodata[1]);
1363 xml_add_element($doc, $root, "link", "", $attributes);
1367 $arr = explode('[/attach],',$item['attach']);
1369 foreach($arr as $r) {
1371 $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"|',$r,$matches);
1373 $attributes = array("rel" => "enclosure",
1374 "href" => $matches[1],
1375 "type" => $matches[3]);
1377 if(intval($matches[2]))
1378 $attributes["length"] = intval($matches[2]);
1380 if(trim($matches[4]) != "")
1381 $attributes["title"] = trim($matches[4]);
1383 xml_add_element($doc, $root, "link", "", $attributes);
1389 function ostatus_add_author($doc, $owner) {
1392 $r = q("SELECT `homepage` FROM `profile` WHERE `uid` = %d AND `is-default` LIMIT 1", intval($owner["uid"]));
1396 $author = $doc->createElement("author");
1397 xml_add_element($doc, $author, "activity:object-type", ACTIVITY_OBJ_PERSON);
1398 xml_add_element($doc, $author, "uri", $owner["url"]);
1399 xml_add_element($doc, $author, "name", $owner["name"]);
1401 $attributes = array("rel" => "alternate", "type" => "text/html", "href" => $owner["url"]);
1402 xml_add_element($doc, $author, "link", "", $attributes);
1404 $attributes = array(
1406 "type" => "image/jpeg", // To-Do?
1407 "media:width" => 175,
1408 "media:height" => 175,
1409 "href" => $owner["photo"]);
1410 xml_add_element($doc, $author, "link", "", $attributes);
1412 if (isset($owner["thumb"])) {
1413 $attributes = array(
1415 "type" => "image/jpeg", // To-Do?
1416 "media:width" => 80,
1417 "media:height" => 80,
1418 "href" => $owner["thumb"]);
1419 xml_add_element($doc, $author, "link", "", $attributes);
1422 xml_add_element($doc, $author, "poco:preferredUsername", $owner["nick"]);
1423 xml_add_element($doc, $author, "poco:displayName", $owner["name"]);
1424 xml_add_element($doc, $author, "poco:note", $owner["about"]);
1426 if (trim($owner["location"]) != "") {
1427 $element = $doc->createElement("poco:address");
1428 xml_add_element($doc, $element, "poco:formatted", $owner["location"]);
1429 $author->appendChild($element);
1432 if (trim($profile["homepage"]) != "") {
1433 $urls = $doc->createElement("poco:urls");
1434 xml_add_element($doc, $urls, "poco:type", "homepage");
1435 xml_add_element($doc, $urls, "poco:value", $profile["homepage"]);
1436 xml_add_element($doc, $urls, "poco:primary", "true");
1437 $author->appendChild($urls);
1440 if (count($profile)) {
1441 xml_add_element($doc, $author, "followers", "", array("url" => $a->get_baseurl()."/viewcontacts/".$owner["nick"]));
1442 xml_add_element($doc, $author, "statusnet:profile_info", "", array("local_id" => $owner["uid"]));
1449 * @TODO Picture attachments should look like this:
1450 * <a href="https://status.pirati.ca/attachment/572819" title="https://status.pirati.ca/file/heluecht-20151202T222602-rd3u49p.gif"
1451 * class="attachment thumbnail" id="attachment-572819" rel="nofollow external">https://status.pirati.ca/attachment/572819</a>
1455 function ostatus_entry($doc, $item, $owner, $toplevel = false, $repeat = false) {
1458 if (($item["id"] != $item["parent"]) AND (normalise_link($item["author-link"]) != normalise_link($owner["url"]))) {
1459 logger("OStatus entry is from author ".$owner["url"]." - not from ".$item["author-link"].". Quitting.", LOGGER_DEBUG);
1465 $repeated_guid = get_reshared_guid($item);
1467 if ($repeated_guid != "") {
1468 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1469 intval($owner["uid"]), dbesc($repeated_guid));
1471 $repeated_item = $r[0];
1477 if (!$toplevel AND !$repeat) {
1478 $entry = $doc->createElement("entry");
1479 $title = sprintf("New note by %s", $owner["nick"]);
1480 } elseif (!$toplevel AND $repeat) {
1481 $entry = $doc->createElement("activity:object");
1482 $title = sprintf("New note by %s", $owner["nick"]);
1484 $entry = $doc->createElementNS(NAMESPACE_ATOM1, "entry");
1486 $entry->setAttribute("xmlns:thr", NAMESPACE_THREAD);
1487 $entry->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
1488 $entry->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
1489 $entry->setAttribute("xmlns:media", NAMESPACE_MEDIA);
1490 $entry->setAttribute("xmlns:poco", NAMESPACE_POCO);
1491 $entry->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
1492 $entry->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
1494 $author = ostatus_add_author($doc, $owner);
1495 $entry->appendChild($author);
1497 $title = sprintf("New comment by %s", $owner["nick"]);
1500 // To use the object-type "bookmark" we have to implement these elements:
1502 // <activity:object-type>http://activitystrea.ms/schema/1.0/bookmark</activity:object-type>
1503 // <title>Historic Rocket Landing</title>
1504 // <summary>Nur ein Testbeitrag.</summary>
1505 // <link rel="related" href="https://www.youtube.com/watch?v=9pillaOxGCo"/>
1506 // <link rel="preview" href="https://pirati.cc/file/thumb-4526-450x338-b48c8055f0c2fed0c3f67adc234c4b99484a90c42ed3cac73dc1081a4d0a7bc1.jpg.jpg" media:width="450" media:height="338"/>
1508 // But: it seems as if it doesn't federate well between the GS servers
1509 // So we just set it to "note" to be sure that it reaches their target systems
1512 xml_add_element($doc, $entry, "activity:object-type", ACTIVITY_OBJ_NOTE);
1514 xml_add_element($doc, $entry, "activity:object-type", NAMESPACE_ACTIVITY_SCHEMA.'activity');
1516 xml_add_element($doc, $entry, "id", $item["uri"]);
1517 xml_add_element($doc, $entry, "title", $title);
1519 if($item['allow_cid'] || $item['allow_gid'] || $item['deny_cid'] || $item['deny_gid'])
1520 $body = fix_private_photos($item['body'],$owner['uid'],$item, 0);
1522 $body = $item['body'];
1524 $body = ostatus_format_picture_post($body);
1526 if ($item['title'] != "")
1527 $body = "[b]".$item['title']."[/b]\n\n".$body;
1529 //$body = bb_remove_share_information($body);
1530 $body = bbcode($body, false, false, 7);
1532 xml_add_element($doc, $entry, "content", $body, array("type" => "html"));
1534 xml_add_element($doc, $entry, "link", "", array("rel" => "alternate", "type" => "text/html",
1535 "href" => $a->get_baseurl()."/display/".$item["guid"]));
1537 xml_add_element($doc, $entry, "status_net", "", array("notice_id" => $item["id"]));
1540 xml_add_element($doc, $entry, "activity:verb", construct_verb($item));
1542 xml_add_element($doc, $entry, "activity:verb", ACTIVITY_SHARE);
1544 xml_add_element($doc, $entry, "published", datetime_convert("UTC","UTC",$item["created"]."+00:00",ATOM_TIME));
1545 xml_add_element($doc, $entry, "updated", datetime_convert("UTC","UTC",$item["edited"]."+00:00",ATOM_TIME));
1548 $repeated_owner = array();
1549 $repeated_owner["name"] = $repeated_item["author-name"];
1550 $repeated_owner["url"] = $repeated_item["author-link"];
1551 $repeated_owner["photo"] = $repeated_item["author-avatar"];
1552 $repeated_owner["nick"] = $repeated_owner["name"];
1553 $repeated_owner["location"] = "";
1554 $repeated_owner["about"] = "";
1555 $repeated_owner["uid"] = 0;
1557 // Fetch the missing data from the global contacts
1558 $r =q("SELECT * FROM `gcontact` WHERE `nurl` = '%s'", normalise_link($repeated_item["author-link"]));
1560 if ($r[0]["nick"] != "")
1561 $repeated_owner["nick"] = $r[0]["nick"];
1563 $repeated_owner["location"] = $r[0]["location"];
1564 $repeated_owner["about"] = $r[0]["about"];
1567 $entry_repeat = ostatus_entry($doc, $repeated_item, $repeated_owner, false, true);
1568 $entry->appendChild($entry_repeat);
1569 } elseif ($repeat) {
1570 $author = ostatus_add_author($doc, $owner);
1571 $entry->appendChild($author);
1574 $mentioned = array();
1576 if (($item['parent'] != $item['id']) || ($item['parent-uri'] !== $item['uri']) || (($item['thr-parent'] !== '') && ($item['thr-parent'] !== $item['uri']))) {
1577 $parent = q("SELECT `guid`, `author-link`, `owner-link` FROM `item` WHERE `id` = %d", intval($item["parent"]));
1578 $parent_item = (($item['thr-parent']) ? $item['thr-parent'] : $item['parent-uri']);
1580 $attributes = array(
1581 "ref" => $parent_item,
1582 "type" => "text/html",
1583 "href" => $a->get_baseurl()."/display/".$parent[0]["guid"]);
1584 xml_add_element($doc, $entry, "thr:in-reply-to", "", $attributes);
1586 $attributes = array(
1588 "href" => $a->get_baseurl()."/display/".$parent[0]["guid"]);
1589 xml_add_element($doc, $entry, "link", "", $attributes);
1591 $mentioned[$parent[0]["author-link"]] = $parent[0]["author-link"];
1592 $mentioned[$parent[0]["owner-link"]] = $parent[0]["owner-link"];
1594 $thrparent = q("SELECT `guid`, `author-link`, `owner-link` FROM `item` WHERE `uid` = %d AND `uri` = '%s'",
1595 intval($owner["uid"]),
1596 dbesc($parent_item));
1598 $mentioned[$thrparent[0]["author-link"]] = $thrparent[0]["author-link"];
1599 $mentioned[$thrparent[0]["owner-link"]] = $thrparent[0]["owner-link"];
1603 xml_add_element($doc, $entry, "link", "", array("rel" => "ostatus:conversation",
1604 "href" => $a->get_baseurl()."/display/".$owner["nick"]."/".$item["parent"]));
1605 xml_add_element($doc, $entry, "ostatus:conversation", $a->get_baseurl()."/display/".$owner["nick"]."/".$item["parent"]);
1607 $tags = item_getfeedtags($item);
1610 foreach($tags as $t)
1612 $mentioned[$t[1]] = $t[1];
1614 // Make sure that mentions are accepted (GNU Social has problems with mixing HTTP and HTTPS)
1615 $newmentions = array();
1616 foreach ($mentioned AS $mention) {
1617 $newmentions[str_replace("http://", "https://", $mention)] = str_replace("http://", "https://", $mention);
1618 $newmentions[str_replace("https://", "http://", $mention)] = str_replace("https://", "http://", $mention);
1620 $mentioned = $newmentions;
1622 foreach ($mentioned AS $mention) {
1623 $r = q("SELECT `forum`, `prv` FROM `contact` WHERE `uid` = %d AND `nurl` = '%s'",
1624 intval($owner["uid"]),
1625 dbesc(normalise_link($mention)));
1626 if ($r[0]["forum"] OR $r[0]["prv"])
1627 xml_add_element($doc, $entry, "link", "", array("rel" => "mentioned",
1628 "ostatus:object-type" => ACTIVITY_OBJ_GROUP,
1629 "href" => $mention));
1631 xml_add_element($doc, $entry, "link", "", array("rel" => "mentioned",
1632 "ostatus:object-type" => ACTIVITY_OBJ_PERSON,
1633 "href" => $mention));
1636 if (!$item["private"])
1637 xml_add_element($doc, $entry, "link", "", array("rel" => "mentioned",
1638 "ostatus:object-type" => "http://activitystrea.ms/schema/1.0/collection",
1639 "href" => "http://activityschema.org/collection/public"));
1642 foreach($tags as $t)
1644 xml_add_element($doc, $entry, "category", "", array("term" => $t[2]));
1646 ostatus_get_attachment($doc, $entry, $item);
1649 /// The API call has yet to be implemented
1650 //$attributes = array("href" => $a->get_baseurl()."/api/statuses/show/".$item["id"].".atom",
1651 // "rel" => "self", "type" => "application/atom+xml");
1652 //xml_add_element($doc, $entry, "link", "", $attributes);
1654 //$attributes = array("href" => $a->get_baseurl()."/api/statuses/show/".$item["id"].".atom",
1655 // "rel" => "edit", "type" => "application/atom+xml");
1656 //xml_add_element($doc, $entry, "link", "", $attributes);
1658 $app = $item["app"];
1663 $attributes = array("local_id" => $item["id"], "source" => $app);
1665 $attributes["repeat_of"] = $repeated_item["id"];
1667 xml_add_element($doc, $entry, "statusnet:notice_info", "", $attributes);
1672 function ostatus_feed(&$a, $owner_nick, $last_update) {
1674 $r = q("SELECT `contact`.*, `user`.`nickname`, `user`.`timezone`, `user`.`page-flags`
1675 FROM `contact` INNER JOIN `user` ON `user`.`uid` = `contact`.`uid`
1676 WHERE `contact`.`self` AND `user`.`nickname` = '%s' LIMIT 1",
1677 dbesc($owner_nick));
1683 if(!strlen($last_update))
1684 $last_update = 'now -30 days';
1686 $check_date = datetime_convert('UTC','UTC',$last_update,'Y-m-d H:i:s');
1688 $items = q("SELECT STRAIGHT_JOIN `item`.*, `item`.`id` AS `item_id` FROM `item`
1689 INNER JOIN `thread` ON `thread`.`iid` = `item`.`parent`
1690 LEFT JOIN `item` AS `thritem` ON `thritem`.`uri`=`item`.`thr-parent` AND `thritem`.`uid`=`item`.`uid`
1691 WHERE `item`.`uid` = %d AND `item`.`received` > '%s' AND NOT `item`.`private` AND NOT `item`.`deleted`
1692 AND `item`.`allow_cid` = '' AND `item`.`allow_gid` = '' AND `item`.`deny_cid` = '' AND `item`.`deny_gid` = ''
1693 AND ((`item`.`wall` AND (`item`.`parent` = `item`.`id`))
1694 OR (`item`.`network` = '%s' AND ((`thread`.`network` IN ('%s', '%s')) OR (`thritem`.`network` IN ('%s', '%s')))) AND `thread`.`mention`)
1695 AND ((`item`.`owner-link` IN ('%s', '%s') AND (`item`.`parent` = `item`.`id`))
1696 OR (`item`.`author-link` IN ('%s', '%s')))
1697 ORDER BY `item`.`received` DESC
1699 intval($owner["uid"]), dbesc($check_date), dbesc(NETWORK_DFRN),
1700 //dbesc(NETWORK_OSTATUS), dbesc(NETWORK_OSTATUS),
1701 //dbesc(NETWORK_OSTATUS), dbesc(NETWORK_OSTATUS),
1702 dbesc(NETWORK_OSTATUS), dbesc(NETWORK_DFRN),
1703 dbesc(NETWORK_OSTATUS), dbesc(NETWORK_DFRN),
1704 dbesc($owner["nurl"]), dbesc(str_replace("http://", "https://", $owner["nurl"])),
1705 dbesc($owner["nurl"]), dbesc(str_replace("http://", "https://", $owner["nurl"]))
1708 $doc = new DOMDocument('1.0', 'utf-8');
1709 $doc->formatOutput = true;
1711 $root = ostatus_add_header($doc, $owner);
1713 foreach ($items AS $item) {
1714 $entry = ostatus_entry($doc, $item, $owner);
1715 $root->appendChild($entry);
1718 return(trim($doc->saveXML()));
1721 function ostatus_salmon($item,$owner) {
1723 $doc = new DOMDocument('1.0', 'utf-8');
1724 $doc->formatOutput = true;
1726 $entry = ostatus_entry($doc, $item, $owner, true);
1728 $doc->appendChild($entry);
1730 return(trim($doc->saveXML()));