2 require_once("include/Contact.php");
3 require_once("include/threads.php");
4 require_once("include/html2bbcode.php");
5 require_once("include/items.php");
6 require_once("mod/share.php");
7 require_once("include/enotify.php");
8 require_once("include/socgraph.php");
9 require_once("include/Photo.php");
10 require_once("include/Scrape.php");
11 require_once("include/follow.php");
13 define('OSTATUS_DEFAULT_POLL_INTERVAL', 30); // given in minutes
14 define('OSTATUS_DEFAULT_POLL_TIMEFRAME', 1440); // given in minutes
15 define('OSTATUS_DEFAULT_POLL_TIMEFRAME_MENTIONS', 14400); // given in minutes
17 function ostatus_check_follow_friends() {
18 $r = q("SELECT `uid`,`v` FROM `pconfig` WHERE `cat`='system' AND `k`='ostatus_legacy_contact' AND `v` != ''");
23 foreach ($r AS $contact) {
24 ostatus_follow_friends($contact["uid"], $contact["v"]);
25 set_pconfig($contact["uid"], "system", "ostatus_legacy_contact", "");
29 // This function doesn't work reliable by now.
30 function ostatus_follow_friends($uid, $url) {
31 $contact = probe_url($url);
36 $api = $contact["baseurl"]."/api/";
39 $data = z_fetch_url($api."statuses/friends.json?screen_name=".$contact["nick"]);
41 if (!$data["success"])
44 $friends = json_decode($data["body"]);
46 foreach ($friends AS $friend) {
47 $url = $friend->statusnet_profile_url;
48 $r = q("SELECT `url` FROM `contact` WHERE `uid` = %d AND
49 (`nurl` = '%s' OR `alias` = '%s' OR `alias` = '%s') AND
50 `network` != '%s' LIMIT 1",
51 intval($uid), dbesc(normalise_link($url)),
52 dbesc(normalise_link($url)), dbesc($url), dbesc(NETWORK_STATUSNET));
54 $data = probe_url($friend->statusnet_profile_url);
55 if ($data["network"] == NETWORK_OSTATUS) {
56 $result = new_contact($uid,$friend->statusnet_profile_url);
57 if ($result["success"])
58 logger($friend->name." ".$url." - success", LOGGER_DEBUG);
60 logger($friend->name." ".$url." - failed", LOGGER_DEBUG);
62 logger($friend->name." ".$url." - not OStatus", LOGGER_DEBUG);
67 function ostatus_fetchauthor($xpath, $context, $importer, &$contact, $onlyfetch) {
70 $author["author-link"] = $xpath->evaluate('atom:author/atom:uri/text()', $context)->item(0)->nodeValue;
71 $author["author-name"] = $xpath->evaluate('atom:author/atom:name/text()', $context)->item(0)->nodeValue;
74 $authorlink = $author["author-link"];
76 $alternate = $xpath->query("atom:author/atom:link[@rel='alternate']", $context)->item(0)->attributes;
77 if (is_object($alternate))
78 foreach($alternate AS $attributes)
79 if ($attributes->name == "href")
80 $author["author-link"] = $attributes->textContent;
82 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `nurl` IN ('%s', '%s') AND `network` != '%s'",
83 intval($importer["uid"]), dbesc(normalise_link($author["author-link"])),
84 dbesc(normalise_link($authorlink)), dbesc(NETWORK_STATUSNET));
87 $author["contact-id"] = $r[0]["id"];
89 $author["contact-id"] = $contact["id"];
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;
99 if ($attributes->name == "width")
100 $width = $attributes->textContent;
102 if (($width > 0) AND ($href != ""))
103 $avatarlist[$width] = $href;
105 if (count($avatarlist) > 0) {
107 $author["author-avatar"] = current($avatarlist);
110 $displayname = $xpath->evaluate('atom:author/poco:displayName/text()', $context)->item(0)->nodeValue;
111 if ($displayname != "")
112 $author["author-name"] = $displayname;
114 $author["owner-name"] = $author["author-name"];
115 $author["owner-link"] = $author["author-link"];
116 $author["owner-avatar"] = $author["author-avatar"];
118 if ($r AND !$onlyfetch) {
119 // Update contact data
120 $update_contact = ($r[0]['name-date'] < datetime_convert('','','now -12 hours'));
121 if ($update_contact) {
122 logger("Update contact data for contact ".$contact["id"], LOGGER_DEBUG);
124 $value = $xpath->evaluate('atom:author/poco:displayName/text()', $context)->item(0)->nodeValue;
126 $contact["name"] = $value;
128 $value = $xpath->evaluate('atom:author/poco:preferredUsername/text()', $context)->item(0)->nodeValue;
130 $contact["nick"] = $value;
132 $value = $xpath->evaluate('atom:author/poco:note/text()', $context)->item(0)->nodeValue;
134 $contact["about"] = $value;
136 $value = $xpath->evaluate('atom:author/poco:address/poco:formatted/text()', $context)->item(0)->nodeValue;
138 $contact["location"] = $value;
140 q("UPDATE `contact` SET `name` = '%s', `nick` = '%s', `about` = '%s', `location` = '%s', `name-date` = '%s' WHERE `id` = %d",
141 dbesc($contact["name"]), dbesc($contact["nick"]), dbesc($contact["about"]), dbesc($contact["location"]),
142 dbesc(datetime_convert()), intval($contact["id"]));
144 poco_check($contact["url"], $contact["name"], $contact["network"], $author["author-avatar"], $contact["about"], $contact["location"],
145 "", "", "", datetime_convert(), 2, $contact["id"], $contact["uid"]);
148 $update_photo = ($r[0]['avatar-date'] < datetime_convert('','','now -12 hours'));
150 if ($update_photo AND isset($author["author-avatar"])) {
151 logger("Update profile picture for contact ".$contact["id"], LOGGER_DEBUG);
153 $photos = import_profile_photo($author["author-avatar"], $importer["uid"], $contact["id"]);
155 q("UPDATE `contact` SET `photo` = '%s', `thumb` = '%s', `micro` = '%s', `avatar-date` = '%s' WHERE `id` = %d",
156 dbesc($photos[0]), dbesc($photos[1]), dbesc($photos[2]),
157 dbesc(datetime_convert()), intval($contact["id"]));
164 function ostatus_salmon_author($xml, $importer) {
170 $doc = new DOMDocument();
171 @$doc->loadXML($xml);
173 $xpath = new DomXPath($doc);
174 $xpath->registerNamespace('atom', "http://www.w3.org/2005/Atom");
175 $xpath->registerNamespace('thr', "http://purl.org/syndication/thread/1.0");
176 $xpath->registerNamespace('georss', "http://www.georss.org/georss");
177 $xpath->registerNamespace('activity', "http://activitystrea.ms/spec/1.0/");
178 $xpath->registerNamespace('media', "http://purl.org/syndication/atommedia");
179 $xpath->registerNamespace('poco', "http://portablecontacts.net/spec/1.0");
180 $xpath->registerNamespace('ostatus', "http://ostatus.org/schema/1.0");
181 $xpath->registerNamespace('statusnet', "http://status.net/schema/api/1/");
183 $entries = $xpath->query('/atom:entry');
185 foreach ($entries AS $entry) {
187 $author = ostatus_fetchauthor($xpath, $entry, $importer, $contact, true);
192 function ostatus_import($xml,$importer,&$contact, &$hub) {
196 logger("Import OStatus message", LOGGER_DEBUG);
201 $doc = new DOMDocument();
202 @$doc->loadXML($xml);
204 $xpath = new DomXPath($doc);
205 $xpath->registerNamespace('atom', "http://www.w3.org/2005/Atom");
206 $xpath->registerNamespace('thr', "http://purl.org/syndication/thread/1.0");
207 $xpath->registerNamespace('georss', "http://www.georss.org/georss");
208 $xpath->registerNamespace('activity', "http://activitystrea.ms/spec/1.0/");
209 $xpath->registerNamespace('media', "http://purl.org/syndication/atommedia");
210 $xpath->registerNamespace('poco', "http://portablecontacts.net/spec/1.0");
211 $xpath->registerNamespace('ostatus', "http://ostatus.org/schema/1.0");
212 $xpath->registerNamespace('statusnet', "http://status.net/schema/api/1/");
215 $hub_attributes = $xpath->query("/atom:feed/atom:link[@rel='hub']")->item(0)->attributes;
216 if (is_object($hub_attributes))
217 foreach($hub_attributes AS $hub_attribute)
218 if ($hub_attribute->name == "href") {
219 $hub = $hub_attribute->textContent;
220 logger("Found hub ".$hub, LOGGER_DEBUG);
224 $header["uid"] = $importer["uid"];
225 $header["network"] = NETWORK_OSTATUS;
226 $header["type"] = "remote";
228 $header["origin"] = 0;
229 $header["gravity"] = GRAVITY_PARENT;
231 // it could either be a received post or a post we fetched by ourselves
232 // depending on that, the first node is different
233 $first_child = $doc->firstChild->tagName;
235 if ($first_child == "feed")
236 $entries = $xpath->query('/atom:feed/atom:entry');
238 $entries = $xpath->query('/atom:entry');
241 $conversationlist = array();
244 // Reverse the order of the entries
245 $entrylist = array();
247 foreach ($entries AS $entry)
248 $entrylist[] = $entry;
250 foreach (array_reverse($entrylist) AS $entry) {
255 if ($first_child == "feed")
256 $author = ostatus_fetchauthor($xpath, $doc->firstChild, $importer, $contact, false);
258 $author = ostatus_fetchauthor($xpath, $entry, $importer, $contact, false);
260 $value = $xpath->evaluate('atom:author/poco:preferredUsername/text()', $context)->item(0)->nodeValue;
264 $nickname = $author["author-name"];
266 $item = array_merge($header, $author);
269 $item["uri"] = $xpath->query('atom:id/text()', $entry)->item(0)->nodeValue;
271 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s'",
272 intval($importer["uid"]), dbesc($item["uri"]));
274 logger("Item with uri ".$item["uri"]." for user ".$importer["uid"]." already existed under id ".$r[0]["id"], LOGGER_DEBUG);
278 $item["body"] = add_page_info_to_body(html2bbcode($xpath->query('atom:content/text()', $entry)->item(0)->nodeValue));
279 $item["object-type"] = $xpath->query('activity:object-type/text()', $entry)->item(0)->nodeValue;
281 if (($item["object-type"] == ACTIVITY_OBJ_BOOKMARK) OR ($item["object-type"] == ACTIVITY_OBJ_EVENT)) {
282 $item["title"] = $xpath->query('atom:title/text()', $entry)->item(0)->nodeValue;
283 $item["body"] = $xpath->query('atom:summary/text()', $entry)->item(0)->nodeValue;
284 } elseif ($item["object-type"] == ACTIVITY_OBJ_QUESTION)
285 $item["title"] = $xpath->query('atom:title/text()', $entry)->item(0)->nodeValue;
287 $item["object"] = $xml;
288 $item["verb"] = $xpath->query('activity:verb/text()', $entry)->item(0)->nodeValue;
292 if ($item["verb"] == "qvitter-delete-notice") {
293 // ignore "Delete" messages (by now)
294 logger("Ignore delete message ".print_r($item, true));
298 if ($item["verb"] == ACTIVITY_JOIN) {
299 // ignore "Join" messages
300 logger("Ignore join message ".print_r($item, true));
304 if ($item["verb"] == ACTIVITY_FOLLOW) {
305 new_follower($importer, $contact, $item, $nickname);
309 if ($item["verb"] == NAMESPACE_OSTATUS."/unfollow") {
310 lose_follower($importer, $contact, $item, $dummy);
314 if ($item["verb"] == ACTIVITY_FAVORITE) {
315 $orig_uri = $xpath->query("activity:object/atom:id", $entry)->item(0)->nodeValue;
316 logger("Favorite ".$orig_uri." ".print_r($item, true));
318 $item["verb"] = ACTIVITY_LIKE;
319 $item["parent-uri"] = $orig_uri;
320 $item["gravity"] = GRAVITY_LIKE;
323 if ($item["verb"] == NAMESPACE_OSTATUS."/unfavorite") {
324 // Ignore "Unfavorite" message
325 logger("Ignore unfavorite message ".print_r($item, true));
329 // http://activitystrea.ms/schema/1.0/rsvp-yes
330 if (!in_array($item["verb"], array(ACTIVITY_POST, ACTIVITY_LIKE, ACTIVITY_SHARE)))
331 logger("Unhandled verb ".$item["verb"]." ".print_r($item, true));
333 $item["created"] = $xpath->query('atom:published/text()', $entry)->item(0)->nodeValue;
334 $item["edited"] = $xpath->query('atom:updated/text()', $entry)->item(0)->nodeValue;
335 $conversation = $xpath->query('ostatus:conversation/text()', $entry)->item(0)->nodeValue;
339 $inreplyto = $xpath->query('thr:in-reply-to', $entry);
340 if (is_object($inreplyto->item(0))) {
341 foreach($inreplyto->item(0)->attributes AS $attributes) {
342 if ($attributes->name == "ref")
343 $item["parent-uri"] = $attributes->textContent;
344 if ($attributes->name == "href")
345 $related = $attributes->textContent;
349 $georsspoint = $xpath->query('georss:point', $entry);
351 $item["coord"] = $georsspoint->item(0)->nodeValue;
354 // $item["location"] =
356 $categories = $xpath->query('atom:category', $entry);
358 foreach ($categories AS $category) {
359 foreach($category->attributes AS $attributes)
360 if ($attributes->name == "term") {
361 $term = $attributes->textContent;
362 if(strlen($item["tag"]))
364 $item["tag"] .= "#[url=".$a->get_baseurl()."/search?tag=".$term."]".$term."[/url]";
372 $links = $xpath->query('atom:link', $entry);
379 foreach ($links AS $link) {
380 foreach($link->attributes AS $attributes) {
381 if ($attributes->name == "href")
382 $href = $attributes->textContent;
383 if ($attributes->name == "rel")
384 $rel = $attributes->textContent;
385 if ($attributes->name == "type")
386 $type = $attributes->textContent;
387 if ($attributes->name == "length")
388 $length = $attributes->textContent;
389 if ($attributes->name == "title")
390 $title = $attributes->textContent;
392 if (($rel != "") AND ($href != ""))
395 $item["plink"] = $href;
396 if (($item["object-type"] == ACTIVITY_OBJ_QUESTION) OR
397 ($item["object-type"] == ACTIVITY_OBJ_EVENT))
398 $item["body"] .= add_page_info($href);
400 case "ostatus:conversation":
401 $conversation = $href;
405 if(strlen($item["attach"]))
406 $item["attach"] .= ',';
408 $item["attach"] .= '[attach]href="'.$href.'" length="'.$length.'" type="'.$type.'" title="'.$title.'"[/attach]';
411 if ($item["object-type"] != ACTIVITY_OBJ_BOOKMARK) {
412 if (!isset($item["parent-uri"]))
413 $item["parent-uri"] = $href;
418 $item["body"] .= add_page_info($href);
424 // Notification check
425 if ($importer["nurl"] == normalise_link($href))
435 $notice_info = $xpath->query('statusnet:notice_info', $entry);
436 if ($notice_info AND ($notice_info->length > 0)) {
437 foreach($notice_info->item(0)->attributes AS $attributes) {
438 if ($attributes->name == "source")
439 $item["app"] = strip_tags($attributes->textContent);
440 if ($attributes->name == "local_id")
441 $local_id = $attributes->textContent;
442 if ($attributes->name == "repeat_of")
443 $repeat_of = $attributes->textContent;
447 // Is it a repeated post?
448 if ($repeat_of != "") {
449 $activityobjects = $xpath->query('activity:object', $entry)->item(0);
451 if (is_object($activityobjects)) {
453 $orig_uri = $xpath->query("activity:object/atom:id", $activityobjects)->item(0)->nodeValue;
454 if (!isset($orig_uri))
455 $orig_uri = $xpath->query('atom:id/text()', $activityobjects)->item(0)->nodeValue;
457 $orig_links = $xpath->query("activity:object/atom:link[@rel='alternate']", $activityobjects);
458 if ($orig_links AND ($orig_links->length > 0))
459 foreach($orig_links->item(0)->attributes AS $attributes)
460 if ($attributes->name == "href")
461 $orig_link = $attributes->textContent;
463 if (!isset($orig_link))
464 $orig_link = $xpath->query("atom:link[@rel='alternate']", $activityobjects)->item(0)->nodeValue;
466 if (!isset($orig_link))
467 $orig_link = ostatus_convert_href($orig_uri);
469 $orig_body = $xpath->query('activity:object/atom:content/text()', $activityobjects)->item(0)->nodeValue;
470 if (!isset($orig_body))
471 $orig_body = $xpath->query('atom:content/text()', $activityobjects)->item(0)->nodeValue;
473 $orig_created = $xpath->query('atom:published/text()', $activityobjects)->item(0)->nodeValue;
475 $orig_contact = $contact;
476 $orig_author = ostatus_fetchauthor($xpath, $activityobjects, $importer, $orig_contact, false);
478 //if (!intval(get_config('system','wall-to-wall_share'))) {
479 // $prefix = share_header($orig_author['author-name'], $orig_author['author-link'], $orig_author['author-avatar'], "", $orig_created, $orig_link);
480 // $item["body"] = $prefix.add_page_info_to_body(html2bbcode($orig_body))."[/share]";
482 $item["author-name"] = $orig_author["author-name"];
483 $item["author-link"] = $orig_author["author-link"];
484 $item["author-avatar"] = $orig_author["author-avatar"];
485 $item["body"] = add_page_info_to_body(html2bbcode($orig_body));
486 $item["created"] = $orig_created;
488 $item["uri"] = $orig_uri;
489 $item["plink"] = $orig_link;
492 $item["verb"] = $xpath->query('activity:verb/text()', $activityobjects)->item(0)->nodeValue;
494 $item["object-type"] = $xpath->query('activity:object/activity:object-type/text()', $activityobjects)->item(0)->nodeValue;
495 if (!isset($item["object-type"]))
496 $item["object-type"] = $xpath->query('activity:object-type/text()', $activityobjects)->item(0)->nodeValue;
500 //if ($enclosure != "")
501 // $item["body"] .= add_page_info($enclosure);
503 if (isset($item["parent-uri"])) {
504 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s'",
505 intval($importer["uid"]), dbesc($item["parent-uri"]));
507 if (!$r AND ($related != "")) {
508 $reply_path = str_replace("/notice/", "/api/statuses/show/", $related).".atom";
510 if ($reply_path != $related) {
511 logger("Fetching related items for user ".$importer["uid"]." from ".$reply_path, LOGGER_DEBUG);
512 $reply_xml = fetch_url($reply_path);
514 $reply_contact = $contact;
515 ostatus_import($reply_xml,$importer,$reply_contact, $reply_hub);
517 // After the import try to fetch the parent item again
518 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s'",
519 intval($importer["uid"]), dbesc($item["parent-uri"]));
523 $item["type"] = 'remote-comment';
524 $item["gravity"] = GRAVITY_COMMENT;
527 $item["parent-uri"] = $item["uri"];
529 $item_id = ostatus_completion($conversation, $importer["uid"], $item);
532 logger("Error storing item", LOGGER_DEBUG);
536 logger("Item was stored with id ".$item_id, LOGGER_DEBUG);
537 $item["id"] = $item_id;
540 $u = q("SELECT `notify-flags`, `language`, `username`, `email` FROM user WHERE uid = %d LIMIT 1", intval($item['uid']));
541 $r = q("SELECT `parent` FROM `item` WHERE `id` = %d", intval($item_id));
544 'type' => NOTIFY_TAGSELF,
545 'notify_flags' => $u[0]["notify-flags"],
546 'language' => $u[0]["language"],
547 'to_name' => $u[0]["username"],
548 'to_email' => $u[0]["email"],
549 'uid' => $item["uid"],
551 'link' => $a->get_baseurl().'/display/'.urlencode(get_item_guid($item_id)),
552 'source_name' => $item["author-name"],
553 'source_link' => $item["author-link"],
554 'source_photo' => $item["author-avatar"],
555 'verb' => ACTIVITY_TAG,
557 'parent' => $r[0]["parent"]
563 function ostatus_convert_href($href) {
564 $elements = explode(":",$href);
566 if ((count($elements) <= 2) OR ($elements[0] != "tag"))
569 $server = explode(",", $elements[1]);
570 $conversation = explode("=", $elements[2]);
572 if ((count($elements) == 4) AND ($elements[2] == "post"))
573 return "http://".$server[0]."/notice/".$elements[3];
575 if ((count($conversation) != 2) OR ($conversation[1] ==""))
578 if ($elements[3] == "objectType=thread")
579 return "http://".$server[0]."/conversation/".$conversation[1];
581 return "http://".$server[0]."/notice/".$conversation[1];
586 function check_conversations($mentions = false, $override = false) {
587 $last = get_config('system','ostatus_last_poll');
589 $poll_interval = intval(get_config('system','ostatus_poll_interval'));
591 $poll_interval = OSTATUS_DEFAULT_POLL_INTERVAL;
593 // Don't poll if the interval is set negative
594 if (($poll_interval < 0) AND !$override)
598 $poll_timeframe = intval(get_config('system','ostatus_poll_timeframe'));
599 if (!$poll_timeframe)
600 $poll_timeframe = OSTATUS_DEFAULT_POLL_TIMEFRAME;
602 $poll_timeframe = intval(get_config('system','ostatus_poll_timeframe'));
603 if (!$poll_timeframe)
604 $poll_timeframe = OSTATUS_DEFAULT_POLL_TIMEFRAME_MENTIONS;
608 if ($last AND !$override) {
609 $next = $last + ($poll_interval * 60);
610 if ($next > time()) {
611 logger('poll interval not reached');
616 logger('cron_start');
618 $start = date("Y-m-d H:i:s", time() - ($poll_timeframe * 60));
621 $conversations = q("SELECT `term`.`oid`, `term`.`url`, `term`.`uid` FROM `term`
622 STRAIGHT_JOIN `thread` ON `thread`.`iid` = `term`.`oid` AND `thread`.`uid` = `term`.`uid`
623 WHERE `term`.`type` = 7 AND `term`.`term` > '%s' AND `thread`.`mention`
624 GROUP BY `term`.`url`, `term`.`uid` ORDER BY `term`.`term` DESC", dbesc($start));
626 $conversations = q("SELECT `oid`, `url`, `uid` FROM `term`
627 WHERE `type` = 7 AND `term` > '%s'
628 GROUP BY `url`, `uid` ORDER BY `term` DESC", dbesc($start));
630 foreach ($conversations AS $conversation) {
631 ostatus_completion($conversation['url'], $conversation['uid']);
636 set_config('system','ostatus_last_poll', time());
639 function ostatus_completion($conversation_url, $uid, $item = array()) {
645 $conversation_url = ostatus_convert_href($conversation_url);
647 // If the thread shouldn't be completed then store the item and go away
648 if ((intval(get_config('system','ostatus_poll_interval')) == -2) AND (count($item) > 0)) {
649 //$arr["app"] .= " (OStatus-NoCompletion)";
650 $item_stored = item_store($item, true);
651 return($item_stored);
655 $parents = q("SELECT `id`, `parent`, `uri`, `contact-id`, `type`, `verb`, `visible` FROM `item` WHERE `id` IN
656 (SELECT `parent` FROM `item` WHERE `id` IN
657 (SELECT `oid` FROM `term` WHERE `uid` = %d AND `otype` = %d AND `type` = %d AND `url` = '%s'))",
658 intval($uid), intval(TERM_OBJ_POST), intval(TERM_CONVERSATION), dbesc($conversation_url));
661 $parent = $parents[0];
662 elseif (count($item) > 0) {
664 $parent["type"] = "remote";
665 $parent["verb"] = ACTIVITY_POST;
666 $parent["visible"] = 1;
669 $r = q("SELECT `id` FROM `contact` WHERE `self` AND `uid`=%d", $uid);
675 $parent["parent"] = 0;
677 $parent["contact-id"] = $r[0]["id"];
678 $parent["type"] = "remote";
679 $parent["verb"] = ACTIVITY_POST;
680 $parent["visible"] = 1;
683 $conv = str_replace("/conversation/", "/api/statusnet/conversation/", $conversation_url).".as";
687 logger('fetching conversation url '.$conv.' for user '.$uid);
690 $conv_arr = z_fetch_url($conv."?page=".$pageno);
692 // If it is a non-ssl site and there is an error, then try ssl or vice versa
693 if (!$conv_arr["success"] AND (substr($conv, 0, 7) == "http://")) {
694 $conv = str_replace("http://", "https://", $conv);
695 $conv_as = fetch_url($conv."?page=".$pageno);
696 } elseif (!$conv_arr["success"] AND (substr($conv, 0, 8) == "https://")) {
697 $conv = str_replace("https://", "http://", $conv);
698 $conv_as = fetch_url($conv."?page=".$pageno);
700 $conv_as = $conv_arr["body"];
702 $conv_as = str_replace(',"statusnet:notice_info":', ',"statusnet_notice_info":', $conv_as);
703 $conv_as = json_decode($conv_as);
705 if (@is_array($conv_as->items))
706 $items = array_merge($items, $conv_as->items);
714 logger('fetching conversation done. Found '.count($items).' items');
716 if (!sizeof($items)) {
717 if (count($item) > 0) {
718 //$arr["app"] .= " (OStatus-NoConvFetched)";
719 $item_stored = item_store($item, true);
722 logger("Conversation ".$conversation_url." couldn't be fetched. Item uri ".$item["uri"]." stored: ".$item_stored, LOGGER_DEBUG);
723 ostatus_store_conversation($item_id, $conversation_url);
726 return($item_stored);
731 $items = array_reverse($items);
733 $r = q("SELECT `nurl` FROM `contact` WHERE `uid` = %d AND `self`", intval($uid));
736 foreach ($items as $single_conv) {
738 // Test - remove before flight
739 //$tempfile = tempnam(get_temppath(), "conversation");
740 //file_put_contents($tempfile, json_encode($single_conv));
744 if (isset($single_conv->object->id))
745 $single_conv->id = $single_conv->object->id;
747 $plink = ostatus_convert_href($single_conv->id);
748 if (isset($single_conv->object->url))
749 $plink = ostatus_convert_href($single_conv->object->url);
751 if (@!$single_conv->id)
754 logger("Got id ".$single_conv->id, LOGGER_DEBUG);
756 if ($first_id == "") {
757 $first_id = $single_conv->id;
759 // The first post of the conversation isn't our first post. There are three options:
760 // 1. Our conversation hasn't the "real" thread starter
761 // 2. This first post is a post inside our thread
762 // 3. This first post is a post inside another thread
763 if (($first_id != $parent["uri"]) AND ($parent["uri"] != "")) {
764 $new_parents = q("SELECT `id`, `parent`, `uri`, `contact-id`, `type`, `verb`, `visible` FROM `item` WHERE `id` IN
765 (SELECT `parent` FROM `item`
766 WHERE `uid` = %d AND `uri` = '%s' AND `network` IN ('%s','%s')) LIMIT 1",
767 intval($uid), dbesc($first_id), dbesc(NETWORK_OSTATUS), dbesc(NETWORK_DFRN));
769 if ($new_parents[0]["parent"] == $parent["parent"]) {
770 // Option 2: This post is already present inside our thread - but not as thread starter
771 logger("Option 2: uri present in our thread: ".$first_id, LOGGER_DEBUG);
772 $first_id = $parent["uri"];
774 // Option 3: Not so good. We have mixed parents. We have to see how to clean this up.
775 // For now just take the new parent.
776 $parent = $new_parents[0];
777 $first_id = $parent["uri"];
778 logger("Option 3: mixed parents for uri ".$first_id, LOGGER_DEBUG);
781 // Option 1: We hadn't got the real thread starter
782 // We have to clean up our existing messages.
784 $parent["uri"] = $first_id;
785 logger("Option 1: we have a new parent: ".$first_id, LOGGER_DEBUG);
787 } elseif ($parent["uri"] == "") {
789 $parent["uri"] = $first_id;
793 $parent_uri = $parent["uri"];
795 // "context" only seems to exist on older servers
796 if (isset($single_conv->context->inReplyTo->id)) {
797 $parent_exists = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `network` IN ('%s','%s') LIMIT 1",
798 intval($uid), dbesc($single_conv->context->inReplyTo->id), dbesc(NETWORK_OSTATUS), dbesc(NETWORK_DFRN));
800 $parent_uri = $single_conv->context->inReplyTo->id;
803 // This is the current way
804 if (isset($single_conv->object->inReplyTo->id)) {
805 $parent_exists = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `network` IN ('%s','%s') LIMIT 1",
806 intval($uid), dbesc($single_conv->object->inReplyTo->id), dbesc(NETWORK_OSTATUS), dbesc(NETWORK_DFRN));
808 $parent_uri = $single_conv->object->inReplyTo->id;
811 $message_exists = q("SELECT `id`, `parent`, `uri` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `network` IN ('%s','%s') LIMIT 1",
812 intval($uid), dbesc($single_conv->id),
813 dbesc(NETWORK_OSTATUS), dbesc(NETWORK_DFRN));
814 if ($message_exists) {
815 logger("Message ".$single_conv->id." already existed on the system", LOGGER_DEBUG);
817 if ($parent["id"] != 0) {
818 $existing_message = $message_exists[0];
820 // We improved the way we fetch OStatus messages, this shouldn't happen very often now
821 // To-Do: we have to change the shadow copies as well. This way here is really ugly.
822 if ($existing_message["parent"] != $parent["id"]) {
823 logger('updating id '.$existing_message["id"].' with parent '.$existing_message["parent"].' to parent '.$parent["id"].' uri '.$parent["uri"].' thread '.$parent_uri, LOGGER_DEBUG);
825 // Update the parent id of the selected item
826 $r = q("UPDATE `item` SET `parent` = %d, `parent-uri` = '%s' WHERE `id` = %d",
827 intval($parent["id"]), dbesc($parent["uri"]), intval($existing_message["id"]));
829 // Update the parent uri in the thread - but only if it points to itself
830 $r = q("UPDATE `item` SET `thr-parent` = '%s' WHERE `id` = %d AND `uri` = `thr-parent`",
831 dbesc($parent_uri), intval($existing_message["id"]));
833 // try to change all items of the same parent
834 $r = q("UPDATE `item` SET `parent` = %d, `parent-uri` = '%s' WHERE `parent` = %d",
835 intval($parent["id"]), dbesc($parent["uri"]), intval($existing_message["parent"]));
837 // Update the parent uri in the thread - but only if it points to itself
838 $r = q("UPDATE `item` SET `thr-parent` = '%s' WHERE (`parent` = %d) AND (`uri` = `thr-parent`)",
839 dbesc($parent["uri"]), intval($existing_message["parent"]));
841 // Now delete the thread
842 delete_thread($existing_message["parent"]);
846 // The item we are having on the system is the one that we wanted to store via the item array
847 if (isset($item["uri"]) AND ($item["uri"] == $existing_message["uri"])) {
855 if (is_array($single_conv->to))
856 foreach($single_conv->to AS $to)
857 if ($importer["nurl"] == normalise_link($to->id))
860 $actor = $single_conv->actor->id;
861 if (isset($single_conv->actor->url))
862 $actor = $single_conv->actor->url;
864 $contact = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `nurl` = '%s' AND `network` != '%s'",
865 $uid, normalise_link($actor), NETWORK_STATUSNET);
867 if (count($contact)) {
868 logger("Found contact for url ".$actor, LOGGER_DEBUG);
869 $contact_id = $contact[0]["id"];
871 logger("No contact found for url ".$actor, LOGGER_DEBUG);
873 // Adding a global contact
874 // To-Do: Use this data for the post
875 $global_contact_id = get_contact($actor, 0);
877 logger("Global contact ".$global_contact_id." found for url ".$actor, LOGGER_DEBUG);
879 $contact_id = $parent["contact-id"];
883 $arr["network"] = NETWORK_OSTATUS;
884 $arr["uri"] = $single_conv->id;
885 $arr["plink"] = $plink;
887 $arr["contact-id"] = $contact_id;
888 $arr["parent-uri"] = $parent_uri;
889 $arr["created"] = $single_conv->published;
890 $arr["edited"] = $single_conv->published;
891 $arr["owner-name"] = $single_conv->actor->displayName;
892 if ($arr["owner-name"] == '')
893 $arr["owner-name"] = $single_conv->actor->contact->displayName;
894 if ($arr["owner-name"] == '')
895 $arr["owner-name"] = $single_conv->actor->portablecontacts_net->displayName;
897 $arr["owner-link"] = $actor;
898 $arr["owner-avatar"] = $single_conv->actor->image->url;
899 $arr["author-name"] = $arr["owner-name"];
900 $arr["author-link"] = $actor;
901 $arr["author-avatar"] = $single_conv->actor->image->url;
902 $arr["body"] = add_page_info_to_body(html2bbcode($single_conv->content));
904 if (isset($single_conv->status_net->notice_info->source))
905 $arr["app"] = strip_tags($single_conv->status_net->notice_info->source);
906 elseif (isset($single_conv->statusnet->notice_info->source))
907 $arr["app"] = strip_tags($single_conv->statusnet->notice_info->source);
908 elseif (isset($single_conv->statusnet_notice_info->source))
909 $arr["app"] = strip_tags($single_conv->statusnet_notice_info->source);
910 elseif (isset($single_conv->provider->displayName))
911 $arr["app"] = $single_conv->provider->displayName;
913 $arr["app"] = "OStatus";
915 //$arr["app"] .= " (Conversation)";
917 $arr["object"] = json_encode($single_conv);
918 $arr["verb"] = $parent["verb"];
919 $arr["visible"] = $parent["visible"];
920 $arr["location"] = $single_conv->location->displayName;
921 $arr["coord"] = trim($single_conv->location->lat." ".$single_conv->location->lon);
923 // Is it a reshared item?
924 if (isset($single_conv->verb) AND ($single_conv->verb == "share") AND isset($single_conv->object)) {
925 if (is_array($single_conv->object))
926 $single_conv->object = $single_conv->object[0];
928 logger("Found reshared item ".$single_conv->object->id);
930 // $single_conv->object->context->conversation;
932 if (isset($single_conv->object->object->id))
933 $arr["uri"] = $single_conv->object->object->id;
935 $arr["uri"] = $single_conv->object->id;
937 if (isset($single_conv->object->object->url))
938 $plink = ostatus_convert_href($single_conv->object->object->url);
940 $plink = ostatus_convert_href($single_conv->object->url);
942 if (isset($single_conv->object->object->content))
943 $arr["body"] = add_page_info_to_body(html2bbcode($single_conv->object->object->content));
945 $arr["body"] = add_page_info_to_body(html2bbcode($single_conv->object->content));
947 $arr["plink"] = $plink;
949 $arr["created"] = $single_conv->object->published;
950 $arr["edited"] = $single_conv->object->published;
952 $arr["author-name"] = $single_conv->object->actor->displayName;
953 if ($arr["owner-name"] == '')
954 $arr["author-name"] = $single_conv->object->actor->contact->displayName;
956 $arr["author-link"] = $single_conv->object->actor->url;
957 $arr["author-avatar"] = $single_conv->object->actor->image->url;
959 $arr["app"] = $single_conv->object->provider->displayName."#";
960 //$arr["verb"] = $single_conv->object->verb;
962 $arr["location"] = $single_conv->object->location->displayName;
963 $arr["coord"] = trim($single_conv->object->location->lat." ".$single_conv->object->location->lon);
966 if ($arr["location"] == "")
967 unset($arr["location"]);
969 if ($arr["coord"] == "")
970 unset($arr["coord"]);
972 // Copy fields from given item array
973 if (isset($item["uri"]) AND (($item["uri"] == $arr["uri"]) OR ($item["uri"] == $single_conv->id))) {
974 $copy_fields = array("owner-name", "owner-link", "owner-avatar", "author-name", "author-link", "author-avatar",
975 "gravity", "body", "object-type", "object", "verb", "created", "edited", "coord", "tag",
976 "title", "attach", "app", "type", "location", "contact-id", "uri");
977 foreach ($copy_fields AS $field)
978 if (isset($item[$field]))
979 $arr[$field] = $item[$field];
981 //$arr["app"] .= " (OStatus)";
984 $newitem = item_store($arr);
986 logger("Item wasn't stored ".print_r($arr, true), LOGGER_DEBUG);
990 if (isset($item["uri"]) AND ($item["uri"] == $arr["uri"])) {
992 $item_stored = $newitem;
995 logger('Stored new item '.$plink.' for parent '.$arr["parent-uri"].' under id '.$newitem, LOGGER_DEBUG);
997 // Add the conversation entry (but don't fetch the whole conversation)
998 ostatus_store_conversation($newitem, $conversation_url);
1001 $u = q("SELECT `notify-flags`, `language`, `username`, `email` FROM user WHERE uid = %d LIMIT 1", intval($uid));
1002 $r = q("SELECT `parent` FROM `item` WHERE `id` = %d", intval($newitem));
1005 'type' => NOTIFY_TAGSELF,
1006 'notify_flags' => $u[0]["notify-flags"],
1007 'language' => $u[0]["language"],
1008 'to_name' => $u[0]["username"],
1009 'to_email' => $u[0]["email"],
1012 'link' => $a->get_baseurl().'/display/'.urlencode(get_item_guid($newitem)),
1013 'source_name' => $arr["author-name"],
1014 'source_link' => $arr["author-link"],
1015 'source_photo' => $arr["author-avatar"],
1016 'verb' => ACTIVITY_TAG,
1018 'parent' => $r[0]["parent"]
1022 // If the newly created item is the top item then change the parent settings of the thread
1023 // This shouldn't happen anymore. This is supposed to be absolote.
1024 if ($arr["uri"] == $first_id) {
1025 logger('setting new parent to id '.$newitem);
1026 $new_parents = q("SELECT `id`, `uri`, `contact-id`, `type`, `verb`, `visible` FROM `item` WHERE `uid` = %d AND `id` = %d LIMIT 1",
1027 intval($uid), intval($newitem));
1029 $parent = $new_parents[0];
1033 if (($item_stored < 0) AND (count($item) > 0)) {
1034 //$arr["app"] .= " (OStatus-NoConvFound)";
1035 $item_stored = item_store($item, true);
1037 logger("Uri ".$item["uri"]." wasn't found in conversation ".$conversation_url, LOGGER_DEBUG);
1038 ostatus_store_conversation($item_stored, $conversation_url);
1042 return($item_stored);
1045 function ostatus_store_conversation($itemid, $conversation_url) {
1048 $conversation_url = ostatus_convert_href($conversation_url);
1050 $messages = q("SELECT `uid`, `parent`, `created`, `received`, `guid` FROM `item` WHERE `id` = %d LIMIT 1", intval($itemid));
1053 $message = $messages[0];
1055 // Store conversation url if not done before
1056 $conversation = q("SELECT `url` FROM `term` WHERE `uid` = %d AND `oid` = %d AND `otype` = %d AND `type` = %d",
1057 intval($message["uid"]), intval($itemid), intval(TERM_OBJ_POST), intval(TERM_CONVERSATION));
1059 if (!$conversation) {
1060 $r = q("INSERT INTO `term` (`uid`, `oid`, `otype`, `type`, `term`, `url`, `created`, `received`, `guid`) VALUES (%d, %d, %d, %d, '%s', '%s', '%s', '%s', '%s')",
1061 intval($message["uid"]), intval($itemid), intval(TERM_OBJ_POST), intval(TERM_CONVERSATION),
1062 dbesc($message["created"]), dbesc($conversation_url), dbesc($message["created"]), dbesc($message["received"]), dbesc($message["guid"]));
1063 logger('Storing conversation url '.$conversation_url.' for id '.$itemid);