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");
11 define('OSTATUS_DEFAULT_POLL_INTERVAL', 30); // given in minutes
12 define('OSTATUS_DEFAULT_POLL_TIMEFRAME', 1440); // given in minutes
13 define('OSTATUS_DEFAULT_POLL_TIMEFRAME_MENTIONS', 14400); // given in minutes
15 function ostatus_fetchauthor($xpath, $context, $importer, &$contact, $onlyfetch) {
18 $author["author-link"] = $xpath->evaluate('atom:author/atom:uri/text()', $context)->item(0)->nodeValue;
19 $author["author-name"] = $xpath->evaluate('atom:author/atom:name/text()', $context)->item(0)->nodeValue;
22 $authorlink = $author["author-link"];
24 $alternate = $xpath->query("atom:author/atom:link[@rel='alternate']", $context)->item(0)->attributes;
25 if (is_object($alternate))
26 foreach($alternate AS $attributes)
27 if ($attributes->name == "href")
28 $author["author-link"] = $attributes->textContent;
30 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `nurl` IN ('%s', '%s') AND `network` != '%s'",
31 intval($importer["uid"]), dbesc(normalise_link($author["author-link"])),
32 dbesc(normalise_link($authorlink)), dbesc(NETWORK_STATUSNET));
35 $author["contact-id"] = $r[0]["id"];
37 $author["contact-id"] = $contact["id"];
39 $avatarlist = array();
40 $avatars = $xpath->query("atom:author/atom:link[@rel='avatar']", $context);
41 foreach($avatars AS $avatar) {
44 foreach($avatar->attributes AS $attributes) {
45 if ($attributes->name == "href")
46 $href = $attributes->textContent;
47 if ($attributes->name == "width")
48 $width = $attributes->textContent;
50 if (($width > 0) AND ($href != ""))
51 $avatarlist[$width] = $href;
53 if (count($avatarlist) > 0) {
55 $author["author-avatar"] = current($avatarlist);
58 $displayname = $xpath->evaluate('atom:author/poco:displayName/text()', $context)->item(0)->nodeValue;
59 if ($displayname != "")
60 $author["author-name"] = $displayname;
62 $author["owner-name"] = $author["author-name"];
63 $author["owner-link"] = $author["author-link"];
64 $author["owner-avatar"] = $author["author-avatar"];
66 if ($r AND !$onlyfetch) {
67 // Update contact data
68 $update_contact = ($r[0]['name-date'] < datetime_convert('','','now -12 hours'));
69 if ($update_contact) {
70 logger("Update contact data for contact ".$contact["id"], LOGGER_DEBUG);
72 $value = $xpath->evaluate('atom:author/poco:displayName/text()', $context)->item(0)->nodeValue;
74 $contact["name"] = $value;
76 $value = $xpath->evaluate('atom:author/poco:preferredUsername/text()', $context)->item(0)->nodeValue;
78 $contact["nick"] = $value;
80 $value = $xpath->evaluate('atom:author/poco:note/text()', $context)->item(0)->nodeValue;
82 $contact["about"] = $value;
84 $value = $xpath->evaluate('atom:author/poco:address/poco:formatted/text()', $context)->item(0)->nodeValue;
86 $contact["location"] = $value;
88 q("UPDATE `contact` SET `name` = '%s', `nick` = '%s', `about` = '%s', `location` = '%s', `name-date` = '%s' WHERE `id` = %d",
89 dbesc($contact["name"]), dbesc($contact["nick"]), dbesc($contact["about"]), dbesc($contact["location"]),
90 dbesc(datetime_convert()), intval($contact["id"]));
92 poco_check($contact["url"], $contact["name"], $contact["network"], $author["author-avatar"], $contact["about"], $contact["location"],
93 "", "", "", datetime_convert(), 2, $contact["id"], $contact["uid"]);
96 $update_photo = ($r[0]['avatar-date'] < datetime_convert('','','now -12 hours'));
98 if ($update_photo AND isset($author["author-avatar"])) {
99 logger("Update profile picture for contact ".$contact["id"], LOGGER_DEBUG);
101 $photos = import_profile_photo($author["author-avatar"], $importer["uid"], $contact["id"]);
103 q("UPDATE `contact` SET `photo` = '%s', `thumb` = '%s', `micro` = '%s', `avatar-date` = '%s' WHERE `id` = %d",
104 dbesc($photos[0]), dbesc($photos[1]), dbesc($photos[2]),
105 dbesc(datetime_convert()), intval($contact["id"]));
112 function ostatus_salmon_author($xml, $importer) {
118 $doc = new DOMDocument();
119 @$doc->loadXML($xml);
121 $xpath = new DomXPath($doc);
122 $xpath->registerNamespace('atom', "http://www.w3.org/2005/Atom");
123 $xpath->registerNamespace('thr', "http://purl.org/syndication/thread/1.0");
124 $xpath->registerNamespace('georss', "http://www.georss.org/georss");
125 $xpath->registerNamespace('activity', "http://activitystrea.ms/spec/1.0/");
126 $xpath->registerNamespace('media', "http://purl.org/syndication/atommedia");
127 $xpath->registerNamespace('poco', "http://portablecontacts.net/spec/1.0");
128 $xpath->registerNamespace('ostatus', "http://ostatus.org/schema/1.0");
129 $xpath->registerNamespace('statusnet', "http://status.net/schema/api/1/");
131 $entries = $xpath->query('/atom:entry');
133 foreach ($entries AS $entry) {
135 $author = ostatus_fetchauthor($xpath, $entry, $importer, $contact, true);
140 function ostatus_import($xml,$importer,&$contact, &$hub) {
144 logger("Import OStatus message", LOGGER_DEBUG);
149 $doc = new DOMDocument();
150 @$doc->loadXML($xml);
152 $xpath = new DomXPath($doc);
153 $xpath->registerNamespace('atom', "http://www.w3.org/2005/Atom");
154 $xpath->registerNamespace('thr', "http://purl.org/syndication/thread/1.0");
155 $xpath->registerNamespace('georss', "http://www.georss.org/georss");
156 $xpath->registerNamespace('activity', "http://activitystrea.ms/spec/1.0/");
157 $xpath->registerNamespace('media', "http://purl.org/syndication/atommedia");
158 $xpath->registerNamespace('poco', "http://portablecontacts.net/spec/1.0");
159 $xpath->registerNamespace('ostatus', "http://ostatus.org/schema/1.0");
160 $xpath->registerNamespace('statusnet', "http://status.net/schema/api/1/");
163 $hub_attributes = $xpath->query("/atom:feed/atom:link[@rel='hub']")->item(0)->attributes;
164 if (is_object($hub_attributes))
165 foreach($hub_attributes AS $hub_attribute)
166 if ($hub_attribute->name == "href") {
167 $hub = $hub_attribute->textContent;
168 logger("Found hub ".$hub, LOGGER_DEBUG);
172 $header["uid"] = $importer["uid"];
173 $header["network"] = NETWORK_OSTATUS;
174 $header["type"] = "remote";
176 $header["origin"] = 0;
177 $header["gravity"] = GRAVITY_PARENT;
179 // it could either be a received post or a post we fetched by ourselves
180 // depending on that, the first node is different
181 $first_child = $doc->firstChild->tagName;
183 if ($first_child == "feed")
184 $entries = $xpath->query('/atom:feed/atom:entry');
186 $entries = $xpath->query('/atom:entry');
189 $conversationlist = array();
192 // Reverse the order of the entries
193 $entrylist = array();
195 foreach ($entries AS $entry)
196 $entrylist[] = $entry;
198 foreach (array_reverse($entrylist) AS $entry) {
203 if ($first_child == "feed")
204 $author = ostatus_fetchauthor($xpath, $doc->firstChild, $importer, $contact, false);
206 $author = ostatus_fetchauthor($xpath, $entry, $importer, $contact, false);
208 $value = $xpath->evaluate('atom:author/poco:preferredUsername/text()', $context)->item(0)->nodeValue;
212 $nickname = $author["author-name"];
214 $item = array_merge($header, $author);
217 $item["uri"] = $xpath->query('atom:id/text()', $entry)->item(0)->nodeValue;
219 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s'",
220 intval($importer["uid"]), dbesc($item["uri"]));
222 logger("Item with uri ".$item["uri"]." for user ".$importer["uid"]." already existed under id ".$r[0]["id"], LOGGER_DEBUG);
226 $item["body"] = add_page_info_to_body(html2bbcode($xpath->query('atom:content/text()', $entry)->item(0)->nodeValue));
227 $item["object-type"] = $xpath->query('activity:object-type/text()', $entry)->item(0)->nodeValue;
229 if (($item["object-type"] == ACTIVITY_OBJ_BOOKMARK) OR ($item["object-type"] == ACTIVITY_OBJ_EVENT)) {
230 $item["title"] = $xpath->query('atom:title/text()', $entry)->item(0)->nodeValue;
231 $item["body"] = $xpath->query('atom:summary/text()', $entry)->item(0)->nodeValue;
232 } elseif ($item["object-type"] == ACTIVITY_OBJ_QUESTION)
233 $item["title"] = $xpath->query('atom:title/text()', $entry)->item(0)->nodeValue;
235 $item["object"] = $xml;
236 $item["verb"] = $xpath->query('activity:verb/text()', $entry)->item(0)->nodeValue;
240 if ($item["verb"] == "qvitter-delete-notice") {
241 // ignore "Delete" messages (by now)
242 logger("Ignore delete message ".print_r($item, true));
246 if ($item["verb"] == ACTIVITY_JOIN) {
247 // ignore "Join" messages
248 logger("Ignore join message ".print_r($item, true));
252 if ($item["verb"] == ACTIVITY_FOLLOW) {
253 new_follower($importer, $contact, $item, $nickname);
257 if ($item["verb"] == NAMESPACE_OSTATUS."/unfollow") {
258 lose_follower($importer, $contact, $item, $dummy);
262 if ($item["verb"] == ACTIVITY_FAVORITE) {
263 $orig_uri = $xpath->query("activity:object/atom:id", $entry)->item(0)->nodeValue;
264 logger("Favorite ".$orig_uri." ".print_r($item, true));
266 $item["verb"] = ACTIVITY_LIKE;
267 $item["parent-uri"] = $orig_uri;
268 $item["gravity"] = GRAVITY_LIKE;
271 if ($item["verb"] == NAMESPACE_OSTATUS."/unfavorite") {
272 // Ignore "Unfavorite" message
273 logger("Ignore unfavorite message ".print_r($item, true));
277 // http://activitystrea.ms/schema/1.0/rsvp-yes
278 if (!in_array($item["verb"], array(ACTIVITY_POST, ACTIVITY_LIKE, ACTIVITY_SHARE)))
279 logger("Unhandled verb ".$item["verb"]." ".print_r($item, true));
281 $item["created"] = $xpath->query('atom:published/text()', $entry)->item(0)->nodeValue;
282 $item["edited"] = $xpath->query('atom:updated/text()', $entry)->item(0)->nodeValue;
283 $conversation = $xpath->query('ostatus:conversation/text()', $entry)->item(0)->nodeValue;
287 $inreplyto = $xpath->query('thr:in-reply-to', $entry);
288 if (is_object($inreplyto->item(0))) {
289 foreach($inreplyto->item(0)->attributes AS $attributes) {
290 if ($attributes->name == "ref")
291 $item["parent-uri"] = $attributes->textContent;
292 if ($attributes->name == "href")
293 $related = $attributes->textContent;
297 $georsspoint = $xpath->query('georss:point', $entry);
299 $item["coord"] = $georsspoint->item(0)->nodeValue;
302 // $item["location"] =
304 $categories = $xpath->query('atom:category', $entry);
306 foreach ($categories AS $category) {
307 foreach($category->attributes AS $attributes)
308 if ($attributes->name == "term") {
309 $term = $attributes->textContent;
310 if(strlen($item["tag"]))
312 $item["tag"] .= "#[url=".$a->get_baseurl()."/search?tag=".$term."]".$term."[/url]";
320 $links = $xpath->query('atom:link', $entry);
327 foreach ($links AS $link) {
328 foreach($link->attributes AS $attributes) {
329 if ($attributes->name == "href")
330 $href = $attributes->textContent;
331 if ($attributes->name == "rel")
332 $rel = $attributes->textContent;
333 if ($attributes->name == "type")
334 $type = $attributes->textContent;
335 if ($attributes->name == "length")
336 $length = $attributes->textContent;
337 if ($attributes->name == "title")
338 $title = $attributes->textContent;
340 if (($rel != "") AND ($href != ""))
343 $item["plink"] = $href;
344 if (($item["object-type"] == ACTIVITY_OBJ_QUESTION) OR
345 ($item["object-type"] == ACTIVITY_OBJ_EVENT))
346 $item["body"] .= add_page_info($href);
348 case "ostatus:conversation":
349 $conversation = $href;
353 if(strlen($item["attach"]))
354 $item["attach"] .= ',';
356 $item["attach"] .= '[attach]href="'.$href.'" length="'.$length.'" type="'.$type.'" title="'.$title.'"[/attach]';
359 if ($item["object-type"] != ACTIVITY_OBJ_BOOKMARK) {
360 if (!isset($item["parent-uri"]))
361 $item["parent-uri"] = $href;
366 $item["body"] .= add_page_info($href);
372 // Notification check
373 if ($importer["nurl"] == normalise_link($href))
383 $notice_info = $xpath->query('statusnet:notice_info', $entry);
384 if ($notice_info AND ($notice_info->length > 0)) {
385 foreach($notice_info->item(0)->attributes AS $attributes) {
386 if ($attributes->name == "source")
387 $item["app"] = strip_tags($attributes->textContent);
388 if ($attributes->name == "local_id")
389 $local_id = $attributes->textContent;
390 if ($attributes->name == "repeat_of")
391 $repeat_of = $attributes->textContent;
395 // Is it a repeated post?
396 if ($repeat_of != "") {
397 $activityobjects = $xpath->query('activity:object', $entry)->item(0);
399 if (is_object($activityobjects)) {
401 $orig_uri = $xpath->query("activity:object/atom:id", $activityobjects)->item(0)->nodeValue;
402 if (!isset($orig_uri))
403 $orig_uri = $xpath->query('atom:id/text()', $activityobjects)->item(0)->nodeValue;
405 $orig_links = $xpath->query("activity:object/atom:link[@rel='alternate']", $activityobjects);
406 if ($orig_links AND ($orig_links->length > 0))
407 foreach($orig_links->item(0)->attributes AS $attributes)
408 if ($attributes->name == "href")
409 $orig_link = $attributes->textContent;
411 if (!isset($orig_link))
412 $orig_link = $xpath->query("atom:link[@rel='alternate']", $activityobjects)->item(0)->nodeValue;
414 if (!isset($orig_link))
415 $orig_link = ostatus_convert_href($orig_uri);
417 $orig_body = $xpath->query('activity:object/atom:content/text()', $activityobjects)->item(0)->nodeValue;
418 if (!isset($orig_body))
419 $orig_body = $xpath->query('atom:content/text()', $activityobjects)->item(0)->nodeValue;
421 $orig_created = $xpath->query('atom:published/text()', $activityobjects)->item(0)->nodeValue;
423 $orig_contact = $contact;
424 $orig_author = ostatus_fetchauthor($xpath, $activityobjects, $importer, $orig_contact, false);
426 //if (!intval(get_config('system','wall-to-wall_share'))) {
427 // $prefix = share_header($orig_author['author-name'], $orig_author['author-link'], $orig_author['author-avatar'], "", $orig_created, $orig_link);
428 // $item["body"] = $prefix.add_page_info_to_body(html2bbcode($orig_body))."[/share]";
430 $item["author-name"] = $orig_author["author-name"];
431 $item["author-link"] = $orig_author["author-link"];
432 $item["author-avatar"] = $orig_author["author-avatar"];
433 $item["body"] = add_page_info_to_body(html2bbcode($orig_body));
434 $item["created"] = $orig_created;
436 $item["uri"] = $orig_uri;
437 $item["plink"] = $orig_link;
440 $item["verb"] = $xpath->query('activity:verb/text()', $activityobjects)->item(0)->nodeValue;
442 $item["object-type"] = $xpath->query('activity:object/activity:object-type/text()', $activityobjects)->item(0)->nodeValue;
443 if (!isset($item["object-type"]))
444 $item["object-type"] = $xpath->query('activity:object-type/text()', $activityobjects)->item(0)->nodeValue;
448 //if ($enclosure != "")
449 // $item["body"] .= add_page_info($enclosure);
451 if (isset($item["parent-uri"])) {
452 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s'",
453 intval($importer["uid"]), dbesc($item["parent-uri"]));
455 if (!$r AND ($related != "")) {
456 $reply_path = str_replace("/notice/", "/api/statuses/show/", $related).".atom";
458 if ($reply_path != $related) {
459 logger("Fetching related items for user ".$importer["uid"]." from ".$reply_path, LOGGER_DEBUG);
460 $reply_xml = fetch_url($reply_path);
462 $reply_contact = $contact;
463 ostatus_import($reply_xml,$importer,$reply_contact, $reply_hub);
465 // After the import try to fetch the parent item again
466 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s'",
467 intval($importer["uid"]), dbesc($item["parent-uri"]));
471 $item["type"] = 'remote-comment';
472 $item["gravity"] = GRAVITY_COMMENT;
475 $item["parent-uri"] = $item["uri"];
477 $item_id = ostatus_completion($conversation, $importer["uid"], $item);
480 logger("Error storing item", LOGGER_DEBUG);
484 logger("Item was stored with id ".$item_id, LOGGER_DEBUG);
485 $item["id"] = $item_id;
488 $u = q("SELECT `notify-flags`, `language`, `username`, `email` FROM user WHERE uid = %d LIMIT 1", intval($item['uid']));
489 $r = q("SELECT `parent` FROM `item` WHERE `id` = %d", intval($item_id));
492 'type' => NOTIFY_TAGSELF,
493 'notify_flags' => $u[0]["notify-flags"],
494 'language' => $u[0]["language"],
495 'to_name' => $u[0]["username"],
496 'to_email' => $u[0]["email"],
497 'uid' => $item["uid"],
499 'link' => $a->get_baseurl().'/display/'.urlencode(get_item_guid($item_id)),
500 'source_name' => $item["author-name"],
501 'source_link' => $item["author-link"],
502 'source_photo' => $item["author-avatar"],
503 'verb' => ACTIVITY_TAG,
505 'parent' => $r[0]["parent"]
511 function ostatus_convert_href($href) {
512 $elements = explode(":",$href);
514 if ((count($elements) <= 2) OR ($elements[0] != "tag"))
517 $server = explode(",", $elements[1]);
518 $conversation = explode("=", $elements[2]);
520 if ((count($elements) == 4) AND ($elements[2] == "post"))
521 return "http://".$server[0]."/notice/".$elements[3];
523 if ((count($conversation) != 2) OR ($conversation[1] ==""))
526 if ($elements[3] == "objectType=thread")
527 return "http://".$server[0]."/conversation/".$conversation[1];
529 return "http://".$server[0]."/notice/".$conversation[1];
534 function check_conversations($mentions = false, $override = false) {
535 $last = get_config('system','ostatus_last_poll');
537 $poll_interval = intval(get_config('system','ostatus_poll_interval'));
539 $poll_interval = OSTATUS_DEFAULT_POLL_INTERVAL;
541 // Don't poll if the interval is set negative
542 if (($poll_interval < 0) AND !$override)
546 $poll_timeframe = intval(get_config('system','ostatus_poll_timeframe'));
547 if (!$poll_timeframe)
548 $poll_timeframe = OSTATUS_DEFAULT_POLL_TIMEFRAME;
550 $poll_timeframe = intval(get_config('system','ostatus_poll_timeframe'));
551 if (!$poll_timeframe)
552 $poll_timeframe = OSTATUS_DEFAULT_POLL_TIMEFRAME_MENTIONS;
556 if ($last AND !$override) {
557 $next = $last + ($poll_interval * 60);
558 if ($next > time()) {
559 logger('poll interval not reached');
564 logger('cron_start');
566 $start = date("Y-m-d H:i:s", time() - ($poll_timeframe * 60));
569 $conversations = q("SELECT `term`.`oid`, `term`.`url`, `term`.`uid` FROM `term`
570 STRAIGHT_JOIN `thread` ON `thread`.`iid` = `term`.`oid` AND `thread`.`uid` = `term`.`uid`
571 WHERE `term`.`type` = 7 AND `term`.`term` > '%s' AND `thread`.`mention`
572 GROUP BY `term`.`url`, `term`.`uid` ORDER BY `term`.`term` DESC", dbesc($start));
574 $conversations = q("SELECT `oid`, `url`, `uid` FROM `term`
575 WHERE `type` = 7 AND `term` > '%s'
576 GROUP BY `url`, `uid` ORDER BY `term` DESC", dbesc($start));
578 foreach ($conversations AS $conversation) {
579 ostatus_completion($conversation['url'], $conversation['uid']);
584 set_config('system','ostatus_last_poll', time());
587 function ostatus_completion($conversation_url, $uid, $item = array()) {
593 $conversation_url = ostatus_convert_href($conversation_url);
595 // If the thread shouldn't be completed then store the item and go away
596 if ((intval(get_config('system','ostatus_poll_interval')) == -2) AND (count($item) > 0)) {
597 //$arr["app"] .= " (OStatus-NoCompletion)";
598 $item_stored = item_store($item, true);
599 return($item_stored);
603 $parents = q("SELECT `id`, `parent`, `uri`, `contact-id`, `type`, `verb`, `visible` FROM `item` WHERE `id` IN
604 (SELECT `parent` FROM `item` WHERE `id` IN
605 (SELECT `oid` FROM `term` WHERE `uid` = %d AND `otype` = %d AND `type` = %d AND `url` = '%s'))",
606 intval($uid), intval(TERM_OBJ_POST), intval(TERM_CONVERSATION), dbesc($conversation_url));
609 $parent = $parents[0];
610 elseif (count($item) > 0) {
612 $parent["type"] = "remote";
613 $parent["verb"] = ACTIVITY_POST;
614 $parent["visible"] = 1;
617 $r = q("SELECT `id` FROM `contact` WHERE `self` AND `uid`=%d", $uid);
623 $parent["parent"] = 0;
625 $parent["contact-id"] = $r[0]["id"];
626 $parent["type"] = "remote";
627 $parent["verb"] = ACTIVITY_POST;
628 $parent["visible"] = 1;
631 $conv = str_replace("/conversation/", "/api/statusnet/conversation/", $conversation_url).".as";
635 logger('fetching conversation url '.$conv.' for user '.$uid);
638 $conv_arr = z_fetch_url($conv."?page=".$pageno);
640 // If it is a non-ssl site and there is an error, then try ssl or vice versa
641 if (!$conv_arr["success"] AND (substr($conv, 0, 7) == "http://")) {
642 $conv = str_replace("http://", "https://", $conv);
643 $conv_as = fetch_url($conv."?page=".$pageno);
644 } elseif (!$conv_arr["success"] AND (substr($conv, 0, 8) == "https://")) {
645 $conv = str_replace("https://", "http://", $conv);
646 $conv_as = fetch_url($conv."?page=".$pageno);
648 $conv_as = $conv_arr["body"];
650 $conv_as = str_replace(',"statusnet:notice_info":', ',"statusnet_notice_info":', $conv_as);
651 $conv_as = json_decode($conv_as);
653 if (@is_array($conv_as->items))
654 $items = array_merge($items, $conv_as->items);
662 logger('fetching conversation done. Found '.count($items).' items');
664 if (!sizeof($items)) {
665 if (count($item) > 0) {
666 //$arr["app"] .= " (OStatus-NoConvFetched)";
667 $item_stored = item_store($item, true);
670 logger("Conversation ".$conversation_url." couldn't be fetched. Item uri ".$item["uri"]." stored: ".$item_stored, LOGGER_DEBUG);
671 ostatus_store_conversation($item_id, $conversation_url);
674 return($item_stored);
679 $items = array_reverse($items);
681 $r = q("SELECT `nurl` FROM `contact` WHERE `uid` = %d AND `self`", intval($uid));
684 foreach ($items as $single_conv) {
686 // Test - remove before flight
687 //$tempfile = tempnam(get_temppath(), "conversation");
688 //file_put_contents($tempfile, json_encode($single_conv));
692 if (isset($single_conv->object->id))
693 $single_conv->id = $single_conv->object->id;
695 $plink = ostatus_convert_href($single_conv->id);
696 if (isset($single_conv->object->url))
697 $plink = ostatus_convert_href($single_conv->object->url);
699 if (@!$single_conv->id)
702 logger("Got id ".$single_conv->id, LOGGER_DEBUG);
704 if ($first_id == "") {
705 $first_id = $single_conv->id;
707 // The first post of the conversation isn't our first post. There are three options:
708 // 1. Our conversation hasn't the "real" thread starter
709 // 2. This first post is a post inside our thread
710 // 3. This first post is a post inside another thread
711 if (($first_id != $parent["uri"]) AND ($parent["uri"] != "")) {
712 $new_parents = q("SELECT `id`, `parent`, `uri`, `contact-id`, `type`, `verb`, `visible` FROM `item` WHERE `id` IN
713 (SELECT `parent` FROM `item`
714 WHERE `uid` = %d AND `uri` = '%s' AND `network` IN ('%s','%s')) LIMIT 1",
715 intval($uid), dbesc($first_id), dbesc(NETWORK_OSTATUS), dbesc(NETWORK_DFRN));
717 if ($new_parents[0]["parent"] == $parent["parent"]) {
718 // Option 2: This post is already present inside our thread - but not as thread starter
719 logger("Option 2: uri present in our thread: ".$first_id, LOGGER_DEBUG);
720 $first_id = $parent["uri"];
722 // Option 3: Not so good. We have mixed parents. We have to see how to clean this up.
723 // For now just take the new parent.
724 $parent = $new_parents[0];
725 $first_id = $parent["uri"];
726 logger("Option 3: mixed parents for uri ".$first_id, LOGGER_DEBUG);
729 // Option 1: We hadn't got the real thread starter
730 // We have to clean up our existing messages.
732 $parent["uri"] = $first_id;
733 logger("Option 1: we have a new parent: ".$first_id, LOGGER_DEBUG);
735 } elseif ($parent["uri"] == "") {
737 $parent["uri"] = $first_id;
741 $parent_uri = $parent["uri"];
743 // "context" only seems to exist on older servers
744 if (isset($single_conv->context->inReplyTo->id)) {
745 $parent_exists = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `network` IN ('%s','%s') LIMIT 1",
746 intval($uid), dbesc($single_conv->context->inReplyTo->id), dbesc(NETWORK_OSTATUS), dbesc(NETWORK_DFRN));
748 $parent_uri = $single_conv->context->inReplyTo->id;
751 // This is the current way
752 if (isset($single_conv->object->inReplyTo->id)) {
753 $parent_exists = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `network` IN ('%s','%s') LIMIT 1",
754 intval($uid), dbesc($single_conv->object->inReplyTo->id), dbesc(NETWORK_OSTATUS), dbesc(NETWORK_DFRN));
756 $parent_uri = $single_conv->object->inReplyTo->id;
759 $message_exists = q("SELECT `id`, `parent`, `uri` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `network` IN ('%s','%s') LIMIT 1",
760 intval($uid), dbesc($single_conv->id),
761 dbesc(NETWORK_OSTATUS), dbesc(NETWORK_DFRN));
762 if ($message_exists) {
763 logger("Message ".$single_conv->id." already existed on the system", LOGGER_DEBUG);
765 if ($parent["id"] != 0) {
766 $existing_message = $message_exists[0];
768 // We improved the way we fetch OStatus messages, this shouldn't happen very often now
769 // To-Do: we have to change the shadow copies as well. This way here is really ugly.
770 if ($existing_message["parent"] != $parent["id"]) {
771 logger('updating id '.$existing_message["id"].' with parent '.$existing_message["parent"].' to parent '.$parent["id"].' uri '.$parent["uri"].' thread '.$parent_uri, LOGGER_DEBUG);
773 // Update the parent id of the selected item
774 $r = q("UPDATE `item` SET `parent` = %d, `parent-uri` = '%s' WHERE `id` = %d",
775 intval($parent["id"]), dbesc($parent["uri"]), intval($existing_message["id"]));
777 // Update the parent uri in the thread - but only if it points to itself
778 $r = q("UPDATE `item` SET `thr-parent` = '%s' WHERE `id` = %d AND `uri` = `thr-parent`",
779 dbesc($parent_uri), intval($existing_message["id"]));
781 // try to change all items of the same parent
782 $r = q("UPDATE `item` SET `parent` = %d, `parent-uri` = '%s' WHERE `parent` = %d",
783 intval($parent["id"]), dbesc($parent["uri"]), intval($existing_message["parent"]));
785 // Update the parent uri in the thread - but only if it points to itself
786 $r = q("UPDATE `item` SET `thr-parent` = '%s' WHERE (`parent` = %d) AND (`uri` = `thr-parent`)",
787 dbesc($parent["uri"]), intval($existing_message["parent"]));
789 // Now delete the thread
790 delete_thread($existing_message["parent"]);
794 // The item we are having on the system is the one that we wanted to store via the item array
795 if (isset($item["uri"]) AND ($item["uri"] == $existing_message["uri"])) {
803 if (is_array($single_conv->to))
804 foreach($single_conv->to AS $to)
805 if ($importer["nurl"] == normalise_link($to->id))
808 $actor = $single_conv->actor->id;
809 if (isset($single_conv->actor->url))
810 $actor = $single_conv->actor->url;
812 $contact = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `nurl` = '%s' AND `network` != '%s'",
813 $uid, normalise_link($actor), NETWORK_STATUSNET);
815 if (count($contact)) {
816 logger("Found contact for url ".$actor, LOGGER_DEBUG);
817 $contact_id = $contact[0]["id"];
819 logger("No contact found for url ".$actor, LOGGER_DEBUG);
821 // Adding a global contact
822 // To-Do: Use this data for the post
823 $global_contact_id = get_contact($actor, 0);
825 logger("Global contact ".$global_contact_id." found for url ".$actor, LOGGER_DEBUG);
827 $contact_id = $parent["contact-id"];
831 $arr["network"] = NETWORK_OSTATUS;
832 $arr["uri"] = $single_conv->id;
833 $arr["plink"] = $plink;
835 $arr["contact-id"] = $contact_id;
836 $arr["parent-uri"] = $parent_uri;
837 $arr["created"] = $single_conv->published;
838 $arr["edited"] = $single_conv->published;
839 $arr["owner-name"] = $single_conv->actor->displayName;
840 if ($arr["owner-name"] == '')
841 $arr["owner-name"] = $single_conv->actor->contact->displayName;
842 if ($arr["owner-name"] == '')
843 $arr["owner-name"] = $single_conv->actor->portablecontacts_net->displayName;
845 $arr["owner-link"] = $actor;
846 $arr["owner-avatar"] = $single_conv->actor->image->url;
847 $arr["author-name"] = $arr["owner-name"];
848 $arr["author-link"] = $actor;
849 $arr["author-avatar"] = $single_conv->actor->image->url;
850 $arr["body"] = add_page_info_to_body(html2bbcode($single_conv->content));
852 if (isset($single_conv->status_net->notice_info->source))
853 $arr["app"] = strip_tags($single_conv->status_net->notice_info->source);
854 elseif (isset($single_conv->statusnet->notice_info->source))
855 $arr["app"] = strip_tags($single_conv->statusnet->notice_info->source);
856 elseif (isset($single_conv->statusnet_notice_info->source))
857 $arr["app"] = strip_tags($single_conv->statusnet_notice_info->source);
858 elseif (isset($single_conv->provider->displayName))
859 $arr["app"] = $single_conv->provider->displayName;
861 $arr["app"] = "OStatus";
863 //$arr["app"] .= " (Conversation)";
865 $arr["object"] = json_encode($single_conv);
866 $arr["verb"] = $parent["verb"];
867 $arr["visible"] = $parent["visible"];
868 $arr["location"] = $single_conv->location->displayName;
869 $arr["coord"] = trim($single_conv->location->lat." ".$single_conv->location->lon);
871 // Is it a reshared item?
872 if (isset($single_conv->verb) AND ($single_conv->verb == "share") AND isset($single_conv->object)) {
873 if (is_array($single_conv->object))
874 $single_conv->object = $single_conv->object[0];
876 logger("Found reshared item ".$single_conv->object->id);
878 // $single_conv->object->context->conversation;
880 if (isset($single_conv->object->object->id))
881 $arr["uri"] = $single_conv->object->object->id;
883 $arr["uri"] = $single_conv->object->id;
885 if (isset($single_conv->object->object->url))
886 $plink = ostatus_convert_href($single_conv->object->object->url);
888 $plink = ostatus_convert_href($single_conv->object->url);
890 if (isset($single_conv->object->object->content))
891 $arr["body"] = add_page_info_to_body(html2bbcode($single_conv->object->object->content));
893 $arr["body"] = add_page_info_to_body(html2bbcode($single_conv->object->content));
895 $arr["plink"] = $plink;
897 $arr["created"] = $single_conv->object->published;
898 $arr["edited"] = $single_conv->object->published;
900 $arr["author-name"] = $single_conv->object->actor->displayName;
901 if ($arr["owner-name"] == '')
902 $arr["author-name"] = $single_conv->object->actor->contact->displayName;
904 $arr["author-link"] = $single_conv->object->actor->url;
905 $arr["author-avatar"] = $single_conv->object->actor->image->url;
907 $arr["app"] = $single_conv->object->provider->displayName."#";
908 //$arr["verb"] = $single_conv->object->verb;
910 $arr["location"] = $single_conv->object->location->displayName;
911 $arr["coord"] = trim($single_conv->object->location->lat." ".$single_conv->object->location->lon);
914 if ($arr["location"] == "")
915 unset($arr["location"]);
917 if ($arr["coord"] == "")
918 unset($arr["coord"]);
920 // Copy fields from given item array
921 if (isset($item["uri"]) AND (($item["uri"] == $arr["uri"]) OR ($item["uri"] == $single_conv->id))) {
922 $copy_fields = array("owner-name", "owner-link", "owner-avatar", "author-name", "author-link", "author-avatar",
923 "gravity", "body", "object-type", "object", "verb", "created", "edited", "coord", "tag",
924 "title", "attach", "app", "type", "location", "contact-id", "uri");
925 foreach ($copy_fields AS $field)
926 if (isset($item[$field]))
927 $arr[$field] = $item[$field];
929 //$arr["app"] .= " (OStatus)";
932 $newitem = item_store($arr);
934 logger("Item wasn't stored ".print_r($arr, true), LOGGER_DEBUG);
938 if (isset($item["uri"]) AND ($item["uri"] == $arr["uri"])) {
940 $item_stored = $newitem;
943 logger('Stored new item '.$plink.' for parent '.$arr["parent-uri"].' under id '.$newitem, LOGGER_DEBUG);
945 // Add the conversation entry (but don't fetch the whole conversation)
946 ostatus_store_conversation($newitem, $conversation_url);
949 $u = q("SELECT `notify-flags`, `language`, `username`, `email` FROM user WHERE uid = %d LIMIT 1", intval($uid));
950 $r = q("SELECT `parent` FROM `item` WHERE `id` = %d", intval($newitem));
953 'type' => NOTIFY_TAGSELF,
954 'notify_flags' => $u[0]["notify-flags"],
955 'language' => $u[0]["language"],
956 'to_name' => $u[0]["username"],
957 'to_email' => $u[0]["email"],
960 'link' => $a->get_baseurl().'/display/'.urlencode(get_item_guid($newitem)),
961 'source_name' => $arr["author-name"],
962 'source_link' => $arr["author-link"],
963 'source_photo' => $arr["author-avatar"],
964 'verb' => ACTIVITY_TAG,
966 'parent' => $r[0]["parent"]
970 // If the newly created item is the top item then change the parent settings of the thread
971 // This shouldn't happen anymore. This is supposed to be absolote.
972 if ($arr["uri"] == $first_id) {
973 logger('setting new parent to id '.$newitem);
974 $new_parents = q("SELECT `id`, `uri`, `contact-id`, `type`, `verb`, `visible` FROM `item` WHERE `uid` = %d AND `id` = %d LIMIT 1",
975 intval($uid), intval($newitem));
977 $parent = $new_parents[0];
981 if (($item_stored < 0) AND (count($item) > 0)) {
982 //$arr["app"] .= " (OStatus-NoConvFound)";
983 $item_stored = item_store($item, true);
985 logger("Uri ".$item["uri"]." wasn't found in conversation ".$conversation_url, LOGGER_DEBUG);
986 ostatus_store_conversation($item_stored, $conversation_url);
990 return($item_stored);
993 function ostatus_store_conversation($itemid, $conversation_url) {
996 $conversation_url = ostatus_convert_href($conversation_url);
998 $messages = q("SELECT `uid`, `parent`, `created`, `received`, `guid` FROM `item` WHERE `id` = %d LIMIT 1", intval($itemid));
1001 $message = $messages[0];
1003 // Store conversation url if not done before
1004 $conversation = q("SELECT `url` FROM `term` WHERE `uid` = %d AND `oid` = %d AND `otype` = %d AND `type` = %d",
1005 intval($message["uid"]), intval($itemid), intval(TERM_OBJ_POST), intval(TERM_CONVERSATION));
1007 if (!$conversation) {
1008 $r = q("INSERT INTO `term` (`uid`, `oid`, `otype`, `type`, `term`, `url`, `created`, `received`, `guid`) VALUES (%d, %d, %d, %d, '%s', '%s', '%s', '%s', '%s')",
1009 intval($message["uid"]), intval($itemid), intval(TERM_OBJ_POST), intval(TERM_CONVERSATION),
1010 dbesc($message["created"]), dbesc($conversation_url), dbesc($message["created"]), dbesc($message["received"]), dbesc($message["guid"]));
1011 logger('Storing conversation url '.$conversation_url.' for id '.$itemid);