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 function ostatus_follow_friends($uid, $url) {
30 $contact = probe_url($url);
35 $api = $contact["baseurl"]."/api/";
38 $data = z_fetch_url($api."statuses/friends.json?screen_name=".$contact["nick"]);
40 if (!$data["success"])
43 $friends = json_decode($data["body"]);
45 foreach ($friends AS $friend) {
46 $url = $friend->statusnet_profile_url;
47 $r = q("SELECT `url` FROM `contact` WHERE `uid` = %d AND
48 (`nurl` = '%s' OR `alias` = '%s' OR `alias` = '%s') AND
49 `network` != '%s' LIMIT 1",
50 intval($uid), dbesc(normalise_link($url)),
51 dbesc(normalise_link($url)), dbesc($url), dbesc(NETWORK_STATUSNET));
53 $data = probe_url($friend->statusnet_profile_url);
54 if ($data["network"] == NETWORK_OSTATUS) {
55 $result = new_contact($uid,$friend->statusnet_profile_url);
56 if ($result["success"])
57 logger($friend->name." ".$url." - success", LOGGER_DEBUG);
59 logger($friend->name." ".$url." - failed", LOGGER_DEBUG);
61 logger($friend->name." ".$url." - not OStatus", LOGGER_DEBUG);
66 function ostatus_fetchauthor($xpath, $context, $importer, &$contact, $onlyfetch) {
69 $author["author-link"] = $xpath->evaluate('atom:author/atom:uri/text()', $context)->item(0)->nodeValue;
70 $author["author-name"] = $xpath->evaluate('atom:author/atom:name/text()', $context)->item(0)->nodeValue;
73 $authorlink = $author["author-link"];
75 $alternate = $xpath->query("atom:author/atom:link[@rel='alternate']", $context)->item(0)->attributes;
76 if (is_object($alternate))
77 foreach($alternate AS $attributes)
78 if ($attributes->name == "href")
79 $author["author-link"] = $attributes->textContent;
81 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `nurl` IN ('%s', '%s') AND `network` != '%s'",
82 intval($importer["uid"]), dbesc(normalise_link($author["author-link"])),
83 dbesc(normalise_link($authorlink)), dbesc(NETWORK_STATUSNET));
86 $author["contact-id"] = $r[0]["id"];
88 $author["contact-id"] = $contact["id"];
90 $avatarlist = array();
91 $avatars = $xpath->query("atom:author/atom:link[@rel='avatar']", $context);
92 foreach($avatars AS $avatar) {
95 foreach($avatar->attributes AS $attributes) {
96 if ($attributes->name == "href")
97 $href = $attributes->textContent;
98 if ($attributes->name == "width")
99 $width = $attributes->textContent;
101 if (($width > 0) AND ($href != ""))
102 $avatarlist[$width] = $href;
104 if (count($avatarlist) > 0) {
106 $author["author-avatar"] = current($avatarlist);
109 $displayname = $xpath->evaluate('atom:author/poco:displayName/text()', $context)->item(0)->nodeValue;
110 if ($displayname != "")
111 $author["author-name"] = $displayname;
113 $author["owner-name"] = $author["author-name"];
114 $author["owner-link"] = $author["author-link"];
115 $author["owner-avatar"] = $author["author-avatar"];
117 if ($r AND !$onlyfetch) {
118 // Update contact data
119 $update_contact = ($r[0]['name-date'] < datetime_convert('','','now -12 hours'));
120 if ($update_contact) {
121 logger("Update contact data for contact ".$contact["id"], LOGGER_DEBUG);
123 $value = $xpath->evaluate('atom:author/poco:displayName/text()', $context)->item(0)->nodeValue;
125 $contact["name"] = $value;
127 $value = $xpath->evaluate('atom:author/poco:preferredUsername/text()', $context)->item(0)->nodeValue;
129 $contact["nick"] = $value;
131 $value = $xpath->evaluate('atom:author/poco:note/text()', $context)->item(0)->nodeValue;
133 $contact["about"] = $value;
135 $value = $xpath->evaluate('atom:author/poco:address/poco:formatted/text()', $context)->item(0)->nodeValue;
137 $contact["location"] = $value;
139 q("UPDATE `contact` SET `name` = '%s', `nick` = '%s', `about` = '%s', `location` = '%s', `name-date` = '%s' WHERE `id` = %d",
140 dbesc($contact["name"]), dbesc($contact["nick"]), dbesc($contact["about"]), dbesc($contact["location"]),
141 dbesc(datetime_convert()), intval($contact["id"]));
143 poco_check($contact["url"], $contact["name"], $contact["network"], $author["author-avatar"], $contact["about"], $contact["location"],
144 "", "", "", datetime_convert(), 2, $contact["id"], $contact["uid"]);
147 $update_photo = ($r[0]['avatar-date'] < datetime_convert('','','now -12 hours'));
149 if ($update_photo AND isset($author["author-avatar"])) {
150 logger("Update profile picture for contact ".$contact["id"], LOGGER_DEBUG);
152 $photos = import_profile_photo($author["author-avatar"], $importer["uid"], $contact["id"]);
154 q("UPDATE `contact` SET `photo` = '%s', `thumb` = '%s', `micro` = '%s', `avatar-date` = '%s' WHERE `id` = %d",
155 dbesc($photos[0]), dbesc($photos[1]), dbesc($photos[2]),
156 dbesc(datetime_convert()), intval($contact["id"]));
163 function ostatus_salmon_author($xml, $importer) {
169 $doc = new DOMDocument();
170 @$doc->loadXML($xml);
172 $xpath = new DomXPath($doc);
173 $xpath->registerNamespace('atom', "http://www.w3.org/2005/Atom");
174 $xpath->registerNamespace('thr', "http://purl.org/syndication/thread/1.0");
175 $xpath->registerNamespace('georss', "http://www.georss.org/georss");
176 $xpath->registerNamespace('activity', "http://activitystrea.ms/spec/1.0/");
177 $xpath->registerNamespace('media', "http://purl.org/syndication/atommedia");
178 $xpath->registerNamespace('poco', "http://portablecontacts.net/spec/1.0");
179 $xpath->registerNamespace('ostatus', "http://ostatus.org/schema/1.0");
180 $xpath->registerNamespace('statusnet', "http://status.net/schema/api/1/");
182 $entries = $xpath->query('/atom:entry');
184 foreach ($entries AS $entry) {
186 $author = ostatus_fetchauthor($xpath, $entry, $importer, $contact, true);
191 function ostatus_import($xml,$importer,&$contact, &$hub) {
195 logger("Import OStatus message", LOGGER_DEBUG);
200 $doc = new DOMDocument();
201 @$doc->loadXML($xml);
203 $xpath = new DomXPath($doc);
204 $xpath->registerNamespace('atom', "http://www.w3.org/2005/Atom");
205 $xpath->registerNamespace('thr', "http://purl.org/syndication/thread/1.0");
206 $xpath->registerNamespace('georss', "http://www.georss.org/georss");
207 $xpath->registerNamespace('activity', "http://activitystrea.ms/spec/1.0/");
208 $xpath->registerNamespace('media', "http://purl.org/syndication/atommedia");
209 $xpath->registerNamespace('poco', "http://portablecontacts.net/spec/1.0");
210 $xpath->registerNamespace('ostatus', "http://ostatus.org/schema/1.0");
211 $xpath->registerNamespace('statusnet', "http://status.net/schema/api/1/");
214 $hub_attributes = $xpath->query("/atom:feed/atom:link[@rel='hub']")->item(0)->attributes;
215 if (is_object($hub_attributes))
216 foreach($hub_attributes AS $hub_attribute)
217 if ($hub_attribute->name == "href") {
218 $hub = $hub_attribute->textContent;
219 logger("Found hub ".$hub, LOGGER_DEBUG);
223 $header["uid"] = $importer["uid"];
224 $header["network"] = NETWORK_OSTATUS;
225 $header["type"] = "remote";
227 $header["origin"] = 0;
228 $header["gravity"] = GRAVITY_PARENT;
230 // it could either be a received post or a post we fetched by ourselves
231 // depending on that, the first node is different
232 $first_child = $doc->firstChild->tagName;
234 if ($first_child == "feed")
235 $entries = $xpath->query('/atom:feed/atom:entry');
237 $entries = $xpath->query('/atom:entry');
240 $conversationlist = array();
243 // Reverse the order of the entries
244 $entrylist = array();
246 foreach ($entries AS $entry)
247 $entrylist[] = $entry;
249 foreach (array_reverse($entrylist) AS $entry) {
254 if ($first_child == "feed")
255 $author = ostatus_fetchauthor($xpath, $doc->firstChild, $importer, $contact, false);
257 $author = ostatus_fetchauthor($xpath, $entry, $importer, $contact, false);
259 $value = $xpath->evaluate('atom:author/poco:preferredUsername/text()', $context)->item(0)->nodeValue;
263 $nickname = $author["author-name"];
265 $item = array_merge($header, $author);
268 $item["uri"] = $xpath->query('atom:id/text()', $entry)->item(0)->nodeValue;
270 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s'",
271 intval($importer["uid"]), dbesc($item["uri"]));
273 logger("Item with uri ".$item["uri"]." for user ".$importer["uid"]." already existed under id ".$r[0]["id"], LOGGER_DEBUG);
277 $item["body"] = add_page_info_to_body(html2bbcode($xpath->query('atom:content/text()', $entry)->item(0)->nodeValue));
278 $item["object-type"] = $xpath->query('activity:object-type/text()', $entry)->item(0)->nodeValue;
280 if (($item["object-type"] == ACTIVITY_OBJ_BOOKMARK) OR ($item["object-type"] == ACTIVITY_OBJ_EVENT)) {
281 $item["title"] = $xpath->query('atom:title/text()', $entry)->item(0)->nodeValue;
282 $item["body"] = $xpath->query('atom:summary/text()', $entry)->item(0)->nodeValue;
283 } elseif ($item["object-type"] == ACTIVITY_OBJ_QUESTION)
284 $item["title"] = $xpath->query('atom:title/text()', $entry)->item(0)->nodeValue;
286 $item["object"] = $xml;
287 $item["verb"] = $xpath->query('activity:verb/text()', $entry)->item(0)->nodeValue;
291 if ($item["verb"] == "qvitter-delete-notice") {
292 // ignore "Delete" messages (by now)
293 logger("Ignore delete message ".print_r($item, true));
297 if ($item["verb"] == ACTIVITY_JOIN) {
298 // ignore "Join" messages
299 logger("Ignore join message ".print_r($item, true));
303 if ($item["verb"] == ACTIVITY_FOLLOW) {
304 new_follower($importer, $contact, $item, $nickname);
308 if ($item["verb"] == NAMESPACE_OSTATUS."/unfollow") {
309 lose_follower($importer, $contact, $item, $dummy);
313 if ($item["verb"] == ACTIVITY_FAVORITE) {
314 $orig_uri = $xpath->query("activity:object/atom:id", $entry)->item(0)->nodeValue;
315 logger("Favorite ".$orig_uri." ".print_r($item, true));
317 $item["verb"] = ACTIVITY_LIKE;
318 $item["parent-uri"] = $orig_uri;
319 $item["gravity"] = GRAVITY_LIKE;
322 if ($item["verb"] == NAMESPACE_OSTATUS."/unfavorite") {
323 // Ignore "Unfavorite" message
324 logger("Ignore unfavorite message ".print_r($item, true));
328 // http://activitystrea.ms/schema/1.0/rsvp-yes
329 if (!in_array($item["verb"], array(ACTIVITY_POST, ACTIVITY_LIKE, ACTIVITY_SHARE)))
330 logger("Unhandled verb ".$item["verb"]." ".print_r($item, true));
332 $item["created"] = $xpath->query('atom:published/text()', $entry)->item(0)->nodeValue;
333 $item["edited"] = $xpath->query('atom:updated/text()', $entry)->item(0)->nodeValue;
334 $conversation = $xpath->query('ostatus:conversation/text()', $entry)->item(0)->nodeValue;
338 $inreplyto = $xpath->query('thr:in-reply-to', $entry);
339 if (is_object($inreplyto->item(0))) {
340 foreach($inreplyto->item(0)->attributes AS $attributes) {
341 if ($attributes->name == "ref")
342 $item["parent-uri"] = $attributes->textContent;
343 if ($attributes->name == "href")
344 $related = $attributes->textContent;
348 $georsspoint = $xpath->query('georss:point', $entry);
350 $item["coord"] = $georsspoint->item(0)->nodeValue;
353 // $item["location"] =
355 $categories = $xpath->query('atom:category', $entry);
357 foreach ($categories AS $category) {
358 foreach($category->attributes AS $attributes)
359 if ($attributes->name == "term") {
360 $term = $attributes->textContent;
361 if(strlen($item["tag"]))
363 $item["tag"] .= "#[url=".$a->get_baseurl()."/search?tag=".$term."]".$term."[/url]";
371 $links = $xpath->query('atom:link', $entry);
378 foreach ($links AS $link) {
379 foreach($link->attributes AS $attributes) {
380 if ($attributes->name == "href")
381 $href = $attributes->textContent;
382 if ($attributes->name == "rel")
383 $rel = $attributes->textContent;
384 if ($attributes->name == "type")
385 $type = $attributes->textContent;
386 if ($attributes->name == "length")
387 $length = $attributes->textContent;
388 if ($attributes->name == "title")
389 $title = $attributes->textContent;
391 if (($rel != "") AND ($href != ""))
394 $item["plink"] = $href;
395 if (($item["object-type"] == ACTIVITY_OBJ_QUESTION) OR
396 ($item["object-type"] == ACTIVITY_OBJ_EVENT))
397 $item["body"] .= add_page_info($href);
399 case "ostatus:conversation":
400 $conversation = $href;
404 if(strlen($item["attach"]))
405 $item["attach"] .= ',';
407 $item["attach"] .= '[attach]href="'.$href.'" length="'.$length.'" type="'.$type.'" title="'.$title.'"[/attach]';
410 if ($item["object-type"] != ACTIVITY_OBJ_BOOKMARK) {
411 if (!isset($item["parent-uri"]))
412 $item["parent-uri"] = $href;
417 $item["body"] .= add_page_info($href);
423 // Notification check
424 if ($importer["nurl"] == normalise_link($href))
434 $notice_info = $xpath->query('statusnet:notice_info', $entry);
435 if ($notice_info AND ($notice_info->length > 0)) {
436 foreach($notice_info->item(0)->attributes AS $attributes) {
437 if ($attributes->name == "source")
438 $item["app"] = strip_tags($attributes->textContent);
439 if ($attributes->name == "local_id")
440 $local_id = $attributes->textContent;
441 if ($attributes->name == "repeat_of")
442 $repeat_of = $attributes->textContent;
446 // Is it a repeated post?
447 if ($repeat_of != "") {
448 $activityobjects = $xpath->query('activity:object', $entry)->item(0);
450 if (is_object($activityobjects)) {
452 $orig_uri = $xpath->query("activity:object/atom:id", $activityobjects)->item(0)->nodeValue;
453 if (!isset($orig_uri))
454 $orig_uri = $xpath->query('atom:id/text()', $activityobjects)->item(0)->nodeValue;
456 $orig_links = $xpath->query("activity:object/atom:link[@rel='alternate']", $activityobjects);
457 if ($orig_links AND ($orig_links->length > 0))
458 foreach($orig_links->item(0)->attributes AS $attributes)
459 if ($attributes->name == "href")
460 $orig_link = $attributes->textContent;
462 if (!isset($orig_link))
463 $orig_link = $xpath->query("atom:link[@rel='alternate']", $activityobjects)->item(0)->nodeValue;
465 if (!isset($orig_link))
466 $orig_link = ostatus_convert_href($orig_uri);
468 $orig_body = $xpath->query('activity:object/atom:content/text()', $activityobjects)->item(0)->nodeValue;
469 if (!isset($orig_body))
470 $orig_body = $xpath->query('atom:content/text()', $activityobjects)->item(0)->nodeValue;
472 $orig_created = $xpath->query('atom:published/text()', $activityobjects)->item(0)->nodeValue;
474 $orig_contact = $contact;
475 $orig_author = ostatus_fetchauthor($xpath, $activityobjects, $importer, $orig_contact, false);
477 //if (!intval(get_config('system','wall-to-wall_share'))) {
478 // $prefix = share_header($orig_author['author-name'], $orig_author['author-link'], $orig_author['author-avatar'], "", $orig_created, $orig_link);
479 // $item["body"] = $prefix.add_page_info_to_body(html2bbcode($orig_body))."[/share]";
481 $item["author-name"] = $orig_author["author-name"];
482 $item["author-link"] = $orig_author["author-link"];
483 $item["author-avatar"] = $orig_author["author-avatar"];
484 $item["body"] = add_page_info_to_body(html2bbcode($orig_body));
485 $item["created"] = $orig_created;
487 $item["uri"] = $orig_uri;
488 $item["plink"] = $orig_link;
491 $item["verb"] = $xpath->query('activity:verb/text()', $activityobjects)->item(0)->nodeValue;
493 $item["object-type"] = $xpath->query('activity:object/activity:object-type/text()', $activityobjects)->item(0)->nodeValue;
494 if (!isset($item["object-type"]))
495 $item["object-type"] = $xpath->query('activity:object-type/text()', $activityobjects)->item(0)->nodeValue;
499 //if ($enclosure != "")
500 // $item["body"] .= add_page_info($enclosure);
502 if (isset($item["parent-uri"])) {
503 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s'",
504 intval($importer["uid"]), dbesc($item["parent-uri"]));
506 if (!$r AND ($related != "")) {
507 $reply_path = str_replace("/notice/", "/api/statuses/show/", $related).".atom";
509 if ($reply_path != $related) {
510 logger("Fetching related items for user ".$importer["uid"]." from ".$reply_path, LOGGER_DEBUG);
511 $reply_xml = fetch_url($reply_path);
513 $reply_contact = $contact;
514 ostatus_import($reply_xml,$importer,$reply_contact, $reply_hub);
516 // After the import try to fetch the parent item again
517 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s'",
518 intval($importer["uid"]), dbesc($item["parent-uri"]));
522 $item["type"] = 'remote-comment';
523 $item["gravity"] = GRAVITY_COMMENT;
526 $item["parent-uri"] = $item["uri"];
528 $item_id = ostatus_completion($conversation, $importer["uid"], $item);
531 logger("Error storing item", LOGGER_DEBUG);
535 logger("Item was stored with id ".$item_id, LOGGER_DEBUG);
536 $item["id"] = $item_id;
539 $u = q("SELECT `notify-flags`, `language`, `username`, `email` FROM user WHERE uid = %d LIMIT 1", intval($item['uid']));
540 $r = q("SELECT `parent` FROM `item` WHERE `id` = %d", intval($item_id));
543 'type' => NOTIFY_TAGSELF,
544 'notify_flags' => $u[0]["notify-flags"],
545 'language' => $u[0]["language"],
546 'to_name' => $u[0]["username"],
547 'to_email' => $u[0]["email"],
548 'uid' => $item["uid"],
550 'link' => $a->get_baseurl().'/display/'.urlencode(get_item_guid($item_id)),
551 'source_name' => $item["author-name"],
552 'source_link' => $item["author-link"],
553 'source_photo' => $item["author-avatar"],
554 'verb' => ACTIVITY_TAG,
556 'parent' => $r[0]["parent"]
562 function ostatus_convert_href($href) {
563 $elements = explode(":",$href);
565 if ((count($elements) <= 2) OR ($elements[0] != "tag"))
568 $server = explode(",", $elements[1]);
569 $conversation = explode("=", $elements[2]);
571 if ((count($elements) == 4) AND ($elements[2] == "post"))
572 return "http://".$server[0]."/notice/".$elements[3];
574 if ((count($conversation) != 2) OR ($conversation[1] ==""))
577 if ($elements[3] == "objectType=thread")
578 return "http://".$server[0]."/conversation/".$conversation[1];
580 return "http://".$server[0]."/notice/".$conversation[1];
585 function check_conversations($mentions = false, $override = false) {
586 $last = get_config('system','ostatus_last_poll');
588 $poll_interval = intval(get_config('system','ostatus_poll_interval'));
590 $poll_interval = OSTATUS_DEFAULT_POLL_INTERVAL;
592 // Don't poll if the interval is set negative
593 if (($poll_interval < 0) AND !$override)
597 $poll_timeframe = intval(get_config('system','ostatus_poll_timeframe'));
598 if (!$poll_timeframe)
599 $poll_timeframe = OSTATUS_DEFAULT_POLL_TIMEFRAME;
601 $poll_timeframe = intval(get_config('system','ostatus_poll_timeframe'));
602 if (!$poll_timeframe)
603 $poll_timeframe = OSTATUS_DEFAULT_POLL_TIMEFRAME_MENTIONS;
607 if ($last AND !$override) {
608 $next = $last + ($poll_interval * 60);
609 if ($next > time()) {
610 logger('poll interval not reached');
615 logger('cron_start');
617 $start = date("Y-m-d H:i:s", time() - ($poll_timeframe * 60));
620 $conversations = q("SELECT `term`.`oid`, `term`.`url`, `term`.`uid` FROM `term`
621 STRAIGHT_JOIN `thread` ON `thread`.`iid` = `term`.`oid` AND `thread`.`uid` = `term`.`uid`
622 WHERE `term`.`type` = 7 AND `term`.`term` > '%s' AND `thread`.`mention`
623 GROUP BY `term`.`url`, `term`.`uid` ORDER BY `term`.`term` DESC", dbesc($start));
625 $conversations = q("SELECT `oid`, `url`, `uid` FROM `term`
626 WHERE `type` = 7 AND `term` > '%s'
627 GROUP BY `url`, `uid` ORDER BY `term` DESC", dbesc($start));
629 foreach ($conversations AS $conversation) {
630 ostatus_completion($conversation['url'], $conversation['uid']);
635 set_config('system','ostatus_last_poll', time());
638 function ostatus_completion($conversation_url, $uid, $item = array()) {
644 $conversation_url = ostatus_convert_href($conversation_url);
646 // If the thread shouldn't be completed then store the item and go away
647 if ((intval(get_config('system','ostatus_poll_interval')) == -2) AND (count($item) > 0)) {
648 //$arr["app"] .= " (OStatus-NoCompletion)";
649 $item_stored = item_store($item, true);
650 return($item_stored);
654 $parents = q("SELECT `id`, `parent`, `uri`, `contact-id`, `type`, `verb`, `visible` FROM `item` WHERE `id` IN
655 (SELECT `parent` FROM `item` WHERE `id` IN
656 (SELECT `oid` FROM `term` WHERE `uid` = %d AND `otype` = %d AND `type` = %d AND `url` = '%s'))",
657 intval($uid), intval(TERM_OBJ_POST), intval(TERM_CONVERSATION), dbesc($conversation_url));
660 $parent = $parents[0];
661 elseif (count($item) > 0) {
663 $parent["type"] = "remote";
664 $parent["verb"] = ACTIVITY_POST;
665 $parent["visible"] = 1;
668 $r = q("SELECT `id` FROM `contact` WHERE `self` AND `uid`=%d", $uid);
674 $parent["parent"] = 0;
676 $parent["contact-id"] = $r[0]["id"];
677 $parent["type"] = "remote";
678 $parent["verb"] = ACTIVITY_POST;
679 $parent["visible"] = 1;
682 $conv = str_replace("/conversation/", "/api/statusnet/conversation/", $conversation_url).".as";
686 logger('fetching conversation url '.$conv.' for user '.$uid);
689 $conv_arr = z_fetch_url($conv."?page=".$pageno);
691 // If it is a non-ssl site and there is an error, then try ssl or vice versa
692 if (!$conv_arr["success"] AND (substr($conv, 0, 7) == "http://")) {
693 $conv = str_replace("http://", "https://", $conv);
694 $conv_as = fetch_url($conv."?page=".$pageno);
695 } elseif (!$conv_arr["success"] AND (substr($conv, 0, 8) == "https://")) {
696 $conv = str_replace("https://", "http://", $conv);
697 $conv_as = fetch_url($conv."?page=".$pageno);
699 $conv_as = $conv_arr["body"];
701 $conv_as = str_replace(',"statusnet:notice_info":', ',"statusnet_notice_info":', $conv_as);
702 $conv_as = json_decode($conv_as);
704 if (@is_array($conv_as->items))
705 $items = array_merge($items, $conv_as->items);
713 logger('fetching conversation done. Found '.count($items).' items');
715 if (!sizeof($items)) {
716 if (count($item) > 0) {
717 //$arr["app"] .= " (OStatus-NoConvFetched)";
718 $item_stored = item_store($item, true);
721 logger("Conversation ".$conversation_url." couldn't be fetched. Item uri ".$item["uri"]." stored: ".$item_stored, LOGGER_DEBUG);
722 ostatus_store_conversation($item_id, $conversation_url);
725 return($item_stored);
730 $items = array_reverse($items);
732 $r = q("SELECT `nurl` FROM `contact` WHERE `uid` = %d AND `self`", intval($uid));
735 foreach ($items as $single_conv) {
737 // Test - remove before flight
738 //$tempfile = tempnam(get_temppath(), "conversation");
739 //file_put_contents($tempfile, json_encode($single_conv));
743 if (isset($single_conv->object->id))
744 $single_conv->id = $single_conv->object->id;
746 $plink = ostatus_convert_href($single_conv->id);
747 if (isset($single_conv->object->url))
748 $plink = ostatus_convert_href($single_conv->object->url);
750 if (@!$single_conv->id)
753 logger("Got id ".$single_conv->id, LOGGER_DEBUG);
755 if ($first_id == "") {
756 $first_id = $single_conv->id;
758 // The first post of the conversation isn't our first post. There are three options:
759 // 1. Our conversation hasn't the "real" thread starter
760 // 2. This first post is a post inside our thread
761 // 3. This first post is a post inside another thread
762 if (($first_id != $parent["uri"]) AND ($parent["uri"] != "")) {
763 $new_parents = q("SELECT `id`, `parent`, `uri`, `contact-id`, `type`, `verb`, `visible` FROM `item` WHERE `id` IN
764 (SELECT `parent` FROM `item`
765 WHERE `uid` = %d AND `uri` = '%s' AND `network` IN ('%s','%s')) LIMIT 1",
766 intval($uid), dbesc($first_id), dbesc(NETWORK_OSTATUS), dbesc(NETWORK_DFRN));
768 if ($new_parents[0]["parent"] == $parent["parent"]) {
769 // Option 2: This post is already present inside our thread - but not as thread starter
770 logger("Option 2: uri present in our thread: ".$first_id, LOGGER_DEBUG);
771 $first_id = $parent["uri"];
773 // Option 3: Not so good. We have mixed parents. We have to see how to clean this up.
774 // For now just take the new parent.
775 $parent = $new_parents[0];
776 $first_id = $parent["uri"];
777 logger("Option 3: mixed parents for uri ".$first_id, LOGGER_DEBUG);
780 // Option 1: We hadn't got the real thread starter
781 // We have to clean up our existing messages.
783 $parent["uri"] = $first_id;
784 logger("Option 1: we have a new parent: ".$first_id, LOGGER_DEBUG);
786 } elseif ($parent["uri"] == "") {
788 $parent["uri"] = $first_id;
792 $parent_uri = $parent["uri"];
794 // "context" only seems to exist on older servers
795 if (isset($single_conv->context->inReplyTo->id)) {
796 $parent_exists = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `network` IN ('%s','%s') LIMIT 1",
797 intval($uid), dbesc($single_conv->context->inReplyTo->id), dbesc(NETWORK_OSTATUS), dbesc(NETWORK_DFRN));
799 $parent_uri = $single_conv->context->inReplyTo->id;
802 // This is the current way
803 if (isset($single_conv->object->inReplyTo->id)) {
804 $parent_exists = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `network` IN ('%s','%s') LIMIT 1",
805 intval($uid), dbesc($single_conv->object->inReplyTo->id), dbesc(NETWORK_OSTATUS), dbesc(NETWORK_DFRN));
807 $parent_uri = $single_conv->object->inReplyTo->id;
810 $message_exists = q("SELECT `id`, `parent`, `uri` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `network` IN ('%s','%s') LIMIT 1",
811 intval($uid), dbesc($single_conv->id),
812 dbesc(NETWORK_OSTATUS), dbesc(NETWORK_DFRN));
813 if ($message_exists) {
814 logger("Message ".$single_conv->id." already existed on the system", LOGGER_DEBUG);
816 if ($parent["id"] != 0) {
817 $existing_message = $message_exists[0];
819 // We improved the way we fetch OStatus messages, this shouldn't happen very often now
820 // To-Do: we have to change the shadow copies as well. This way here is really ugly.
821 if ($existing_message["parent"] != $parent["id"]) {
822 logger('updating id '.$existing_message["id"].' with parent '.$existing_message["parent"].' to parent '.$parent["id"].' uri '.$parent["uri"].' thread '.$parent_uri, LOGGER_DEBUG);
824 // Update the parent id of the selected item
825 $r = q("UPDATE `item` SET `parent` = %d, `parent-uri` = '%s' WHERE `id` = %d",
826 intval($parent["id"]), dbesc($parent["uri"]), intval($existing_message["id"]));
828 // Update the parent uri in the thread - but only if it points to itself
829 $r = q("UPDATE `item` SET `thr-parent` = '%s' WHERE `id` = %d AND `uri` = `thr-parent`",
830 dbesc($parent_uri), intval($existing_message["id"]));
832 // try to change all items of the same parent
833 $r = q("UPDATE `item` SET `parent` = %d, `parent-uri` = '%s' WHERE `parent` = %d",
834 intval($parent["id"]), dbesc($parent["uri"]), intval($existing_message["parent"]));
836 // Update the parent uri in the thread - but only if it points to itself
837 $r = q("UPDATE `item` SET `thr-parent` = '%s' WHERE (`parent` = %d) AND (`uri` = `thr-parent`)",
838 dbesc($parent["uri"]), intval($existing_message["parent"]));
840 // Now delete the thread
841 delete_thread($existing_message["parent"]);
845 // The item we are having on the system is the one that we wanted to store via the item array
846 if (isset($item["uri"]) AND ($item["uri"] == $existing_message["uri"])) {
854 if (is_array($single_conv->to))
855 foreach($single_conv->to AS $to)
856 if ($importer["nurl"] == normalise_link($to->id))
859 $actor = $single_conv->actor->id;
860 if (isset($single_conv->actor->url))
861 $actor = $single_conv->actor->url;
863 $contact = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `nurl` = '%s' AND `network` != '%s'",
864 $uid, normalise_link($actor), NETWORK_STATUSNET);
866 if (count($contact)) {
867 logger("Found contact for url ".$actor, LOGGER_DEBUG);
868 $contact_id = $contact[0]["id"];
870 logger("No contact found for url ".$actor, LOGGER_DEBUG);
872 // Adding a global contact
873 // To-Do: Use this data for the post
874 $global_contact_id = get_contact($actor, 0);
876 logger("Global contact ".$global_contact_id." found for url ".$actor, LOGGER_DEBUG);
878 $contact_id = $parent["contact-id"];
882 $arr["network"] = NETWORK_OSTATUS;
883 $arr["uri"] = $single_conv->id;
884 $arr["plink"] = $plink;
886 $arr["contact-id"] = $contact_id;
887 $arr["parent-uri"] = $parent_uri;
888 $arr["created"] = $single_conv->published;
889 $arr["edited"] = $single_conv->published;
890 $arr["owner-name"] = $single_conv->actor->displayName;
891 if ($arr["owner-name"] == '')
892 $arr["owner-name"] = $single_conv->actor->contact->displayName;
893 if ($arr["owner-name"] == '')
894 $arr["owner-name"] = $single_conv->actor->portablecontacts_net->displayName;
896 $arr["owner-link"] = $actor;
897 $arr["owner-avatar"] = $single_conv->actor->image->url;
898 $arr["author-name"] = $arr["owner-name"];
899 $arr["author-link"] = $actor;
900 $arr["author-avatar"] = $single_conv->actor->image->url;
901 $arr["body"] = add_page_info_to_body(html2bbcode($single_conv->content));
903 if (isset($single_conv->status_net->notice_info->source))
904 $arr["app"] = strip_tags($single_conv->status_net->notice_info->source);
905 elseif (isset($single_conv->statusnet->notice_info->source))
906 $arr["app"] = strip_tags($single_conv->statusnet->notice_info->source);
907 elseif (isset($single_conv->statusnet_notice_info->source))
908 $arr["app"] = strip_tags($single_conv->statusnet_notice_info->source);
909 elseif (isset($single_conv->provider->displayName))
910 $arr["app"] = $single_conv->provider->displayName;
912 $arr["app"] = "OStatus";
914 //$arr["app"] .= " (Conversation)";
916 $arr["object"] = json_encode($single_conv);
917 $arr["verb"] = $parent["verb"];
918 $arr["visible"] = $parent["visible"];
919 $arr["location"] = $single_conv->location->displayName;
920 $arr["coord"] = trim($single_conv->location->lat." ".$single_conv->location->lon);
922 // Is it a reshared item?
923 if (isset($single_conv->verb) AND ($single_conv->verb == "share") AND isset($single_conv->object)) {
924 if (is_array($single_conv->object))
925 $single_conv->object = $single_conv->object[0];
927 logger("Found reshared item ".$single_conv->object->id);
929 // $single_conv->object->context->conversation;
931 if (isset($single_conv->object->object->id))
932 $arr["uri"] = $single_conv->object->object->id;
934 $arr["uri"] = $single_conv->object->id;
936 if (isset($single_conv->object->object->url))
937 $plink = ostatus_convert_href($single_conv->object->object->url);
939 $plink = ostatus_convert_href($single_conv->object->url);
941 if (isset($single_conv->object->object->content))
942 $arr["body"] = add_page_info_to_body(html2bbcode($single_conv->object->object->content));
944 $arr["body"] = add_page_info_to_body(html2bbcode($single_conv->object->content));
946 $arr["plink"] = $plink;
948 $arr["created"] = $single_conv->object->published;
949 $arr["edited"] = $single_conv->object->published;
951 $arr["author-name"] = $single_conv->object->actor->displayName;
952 if ($arr["owner-name"] == '')
953 $arr["author-name"] = $single_conv->object->actor->contact->displayName;
955 $arr["author-link"] = $single_conv->object->actor->url;
956 $arr["author-avatar"] = $single_conv->object->actor->image->url;
958 $arr["app"] = $single_conv->object->provider->displayName."#";
959 //$arr["verb"] = $single_conv->object->verb;
961 $arr["location"] = $single_conv->object->location->displayName;
962 $arr["coord"] = trim($single_conv->object->location->lat." ".$single_conv->object->location->lon);
965 if ($arr["location"] == "")
966 unset($arr["location"]);
968 if ($arr["coord"] == "")
969 unset($arr["coord"]);
971 // Copy fields from given item array
972 if (isset($item["uri"]) AND (($item["uri"] == $arr["uri"]) OR ($item["uri"] == $single_conv->id))) {
973 $copy_fields = array("owner-name", "owner-link", "owner-avatar", "author-name", "author-link", "author-avatar",
974 "gravity", "body", "object-type", "object", "verb", "created", "edited", "coord", "tag",
975 "title", "attach", "app", "type", "location", "contact-id", "uri");
976 foreach ($copy_fields AS $field)
977 if (isset($item[$field]))
978 $arr[$field] = $item[$field];
980 //$arr["app"] .= " (OStatus)";
983 $newitem = item_store($arr);
985 logger("Item wasn't stored ".print_r($arr, true), LOGGER_DEBUG);
989 if (isset($item["uri"]) AND ($item["uri"] == $arr["uri"])) {
991 $item_stored = $newitem;
994 logger('Stored new item '.$plink.' for parent '.$arr["parent-uri"].' under id '.$newitem, LOGGER_DEBUG);
996 // Add the conversation entry (but don't fetch the whole conversation)
997 ostatus_store_conversation($newitem, $conversation_url);
1000 $u = q("SELECT `notify-flags`, `language`, `username`, `email` FROM user WHERE uid = %d LIMIT 1", intval($uid));
1001 $r = q("SELECT `parent` FROM `item` WHERE `id` = %d", intval($newitem));
1004 'type' => NOTIFY_TAGSELF,
1005 'notify_flags' => $u[0]["notify-flags"],
1006 'language' => $u[0]["language"],
1007 'to_name' => $u[0]["username"],
1008 'to_email' => $u[0]["email"],
1011 'link' => $a->get_baseurl().'/display/'.urlencode(get_item_guid($newitem)),
1012 'source_name' => $arr["author-name"],
1013 'source_link' => $arr["author-link"],
1014 'source_photo' => $arr["author-avatar"],
1015 'verb' => ACTIVITY_TAG,
1017 'parent' => $r[0]["parent"]
1021 // If the newly created item is the top item then change the parent settings of the thread
1022 // This shouldn't happen anymore. This is supposed to be absolote.
1023 if ($arr["uri"] == $first_id) {
1024 logger('setting new parent to id '.$newitem);
1025 $new_parents = q("SELECT `id`, `uri`, `contact-id`, `type`, `verb`, `visible` FROM `item` WHERE `uid` = %d AND `id` = %d LIMIT 1",
1026 intval($uid), intval($newitem));
1028 $parent = $new_parents[0];
1032 if (($item_stored < 0) AND (count($item) > 0)) {
1033 //$arr["app"] .= " (OStatus-NoConvFound)";
1034 $item_stored = item_store($item, true);
1036 logger("Uri ".$item["uri"]." wasn't found in conversation ".$conversation_url, LOGGER_DEBUG);
1037 ostatus_store_conversation($item_stored, $conversation_url);
1041 return($item_stored);
1044 function ostatus_store_conversation($itemid, $conversation_url) {
1047 $conversation_url = ostatus_convert_href($conversation_url);
1049 $messages = q("SELECT `uid`, `parent`, `created`, `received`, `guid` FROM `item` WHERE `id` = %d LIMIT 1", intval($itemid));
1052 $message = $messages[0];
1054 // Store conversation url if not done before
1055 $conversation = q("SELECT `url` FROM `term` WHERE `uid` = %d AND `oid` = %d AND `otype` = %d AND `type` = %d",
1056 intval($message["uid"]), intval($itemid), intval(TERM_OBJ_POST), intval(TERM_CONVERSATION));
1058 if (!$conversation) {
1059 $r = q("INSERT INTO `term` (`uid`, `oid`, `otype`, `type`, `term`, `url`, `created`, `received`, `guid`) VALUES (%d, %d, %d, %d, '%s', '%s', '%s', '%s', '%s')",
1060 intval($message["uid"]), intval($itemid), intval(TERM_OBJ_POST), intval(TERM_CONVERSATION),
1061 dbesc($message["created"]), dbesc($conversation_url), dbesc($message["created"]), dbesc($message["received"]), dbesc($message["guid"]));
1062 logger('Storing conversation url '.$conversation_url.' for id '.$itemid);