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
14 function ostatus_fetchauthor($xpath, $context, $importer, &$contact) {
17 $author["author-link"] = $xpath->evaluate('atom:author/atom:uri/text()', $context)->item(0)->nodeValue;
18 $author["author-name"] = $xpath->evaluate('atom:author/atom:name/text()', $context)->item(0)->nodeValue;
21 $authorlink = $author["author-link"];
23 $alternate = $xpath->query("atom:author/atom:link[@rel='alternate']", $context)->item(0)->attributes;
24 if (is_object($alternate))
25 foreach($alternate AS $attributes)
26 if ($attributes->name == "href")
27 $author["author-link"] = $attributes->textContent;
29 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `nurl` IN ('%s', '%s') AND `network` != '%s'",
30 intval($importer["uid"]), dbesc(normalise_link($author["author-link"])),
31 dbesc(normalise_link($authorlink)), dbesc(NETWORK_STATUSNET));
34 $author["contact-id"] = $r[0]["id"];
36 $author["contact-id"] = $contact["id"];
38 $avatarlist = array();
39 $avatars = $xpath->query("atom:author/atom:link[@rel='avatar']", $context);
40 foreach($avatars AS $avatar) {
43 foreach($avatar->attributes AS $attributes) {
44 if ($attributes->name == "href")
45 $href = $attributes->textContent;
46 if ($attributes->name == "width")
47 $width = $attributes->textContent;
49 if (($width > 0) AND ($href != ""))
50 $avatarlist[$width] = $href;
52 if (count($avatarlist) > 0) {
54 $author["author-avatar"] = current($avatarlist);
57 $displayname = $xpath->evaluate('atom:author/poco:displayName/text()', $context)->item(0)->nodeValue;
58 if ($displayname != "")
59 $author["author-name"] = $displayname;
61 $author["owner-name"] = $author["author-name"];
62 $author["owner-link"] = $author["author-link"];
63 $author["owner-avatar"] = $author["author-avatar"];
66 // Update contact data
67 $update_contact = ($r[0]['name-date'] < datetime_convert('','','now -12 hours'));
68 if ($update_contact) {
69 logger("Update contact data for contact ".$contact["id"], LOGGER_DEBUG);
71 $value = $xpath->evaluate('atom:author/poco:displayName/text()', $context)->item(0)->nodeValue;
73 $contact["name"] = $value;
75 $value = $xpath->evaluate('atom:author/poco:preferredUsername/text()', $context)->item(0)->nodeValue;
77 $contact["nick"] = $value;
79 $value = $xpath->evaluate('atom:author/poco:note/text()', $context)->item(0)->nodeValue;
81 $contact["about"] = $value;
83 $value = $xpath->evaluate('atom:author/poco:address/poco:formatted/text()', $context)->item(0)->nodeValue;
85 $contact["location"] = $value;
87 q("UPDATE `contact` SET `name` = '%s', `nick` = '%s', `about` = '%s', `location` = '%s', `name-date` = '%s' WHERE `id` = %d",
88 dbesc($contact["name"]), dbesc($contact["nick"]), dbesc($contact["about"]), dbesc($contact["location"]),
89 dbesc(datetime_convert()), intval($contact["id"]));
91 poco_check($contact["url"], $contact["name"], $contact["network"], $author["author-avatar"], $contact["about"], $contact["location"],
92 "", "", "", datetime_convert(), 2, $contact["id"], $contact["uid"]);
95 $update_photo = ($r[0]['avatar-date'] < datetime_convert('','','now -12 hours'));
97 if ($update_photo AND isset($author["author-avatar"])) {
98 logger("Update profile picture for contact ".$contact["id"], LOGGER_DEBUG);
100 $photos = import_profile_photo($author["author-avatar"], $importer["uid"], $contact["id"]);
102 q("UPDATE `contact` SET `photo` = '%s', `thumb` = '%s', `micro` = '%s', `avatar-date` = '%s' WHERE `id` = %d",
103 dbesc($photos[0]), dbesc($photos[1]), dbesc($photos[2]),
104 dbesc(datetime_convert()), intval($contact["id"]));
111 function ostatus_import($xml,$importer,&$contact, &$hub) {
115 logger("Import OStatus message", LOGGER_DEBUG);
120 $doc = new DOMDocument();
121 @$doc->loadXML($xml);
123 $xpath = new DomXPath($doc);
124 $xpath->registerNamespace('atom', "http://www.w3.org/2005/Atom");
125 $xpath->registerNamespace('thr', "http://purl.org/syndication/thread/1.0");
126 $xpath->registerNamespace('georss', "http://www.georss.org/georss");
127 $xpath->registerNamespace('activity', "http://activitystrea.ms/spec/1.0/");
128 $xpath->registerNamespace('media', "http://purl.org/syndication/atommedia");
129 $xpath->registerNamespace('poco', "http://portablecontacts.net/spec/1.0");
130 $xpath->registerNamespace('ostatus', "http://ostatus.org/schema/1.0");
131 $xpath->registerNamespace('statusnet', "http://status.net/schema/api/1/");
134 $hub_attributes = $xpath->query("/atom:feed/atom:link[@rel='hub']")->item(0)->attributes;
135 if (is_object($hub_attributes))
136 foreach($hub_attributes AS $hub_attribute)
137 if ($hub_attribute->name == "href") {
138 $hub = $hub_attribute->textContent;
139 logger("Found hub ".$hub, LOGGER_DEBUG);
143 $header["uid"] = $importer["uid"];
144 $header["network"] = NETWORK_OSTATUS;
145 $header["type"] = "remote";
147 $header["origin"] = 0;
148 $header["gravity"] = GRAVITY_PARENT;
150 // it could either be a received post or a post we fetched by ourselves
151 // depending on that, the first node is different
152 $first_child = $doc->firstChild->tagName;
154 if ($first_child == "feed")
155 $entries = $xpath->query('/atom:feed/atom:entry');
157 $entries = $xpath->query('/atom:entry');
160 $conversationlist = array();
163 // Reverse the order of the entries
164 $entrylist = array();
166 foreach ($entries AS $entry)
167 $entrylist[] = $entry;
169 foreach (array_reverse($entrylist) AS $entry) {
174 if ($first_child == "feed")
175 $author = ostatus_fetchauthor($xpath, $doc->firstChild, $importer, $contact);
177 $author = ostatus_fetchauthor($xpath, $entry, $importer, $contact);
179 $item = array_merge($header, $author);
182 $item["uri"] = $xpath->query('atom:id/text()', $entry)->item(0)->nodeValue;
184 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s'",
185 intval($importer["uid"]), dbesc($item["uri"]));
187 logger("Item with uri ".$item["uri"]." for user ".$importer["uid"]." already existed under id ".$r[0]["id"], LOGGER_DEBUG);
191 $item["body"] = add_page_info_to_body(html2bbcode($xpath->query('atom:content/text()', $entry)->item(0)->nodeValue));
192 $item["object-type"] = $xpath->query('activity:object-type/text()', $entry)->item(0)->nodeValue;
193 $item["object"] = $xml;
194 $item["verb"] = $xpath->query('activity:verb/text()', $entry)->item(0)->nodeValue;
196 if ($item["verb"] == ACTIVITY_JOIN) {
197 // ignore "Join" messages
201 if ($item["verb"] == ACTIVITY_FOLLOW) {
202 // ignore "Follow" messages
206 if ($item["verb"] == ACTIVITY_FAVORITE) {
207 // ignore "Favorite" messages
211 $item["created"] = $xpath->query('atom:published/text()', $entry)->item(0)->nodeValue;
212 $item["edited"] = $xpath->query('atom:updated/text()', $entry)->item(0)->nodeValue;
213 $conversation = $xpath->query('ostatus:conversation/text()', $entry)->item(0)->nodeValue;
217 $inreplyto = $xpath->query('thr:in-reply-to', $entry);
218 if (is_object($inreplyto->item(0))) {
219 foreach($inreplyto->item(0)->attributes AS $attributes) {
220 if ($attributes->name == "ref")
221 $item["parent-uri"] = $attributes->textContent;
222 if ($attributes->name == "href")
223 $related = $attributes->textContent;
227 $georsspoint = $xpath->query('georss:point', $entry);
229 $item["coord"] = $georsspoint->item(0)->nodeValue;
232 // $item["location"] =
234 $categories = $xpath->query('atom:category', $entry);
236 foreach ($categories AS $category) {
237 foreach($category->attributes AS $attributes)
238 if ($attributes->name == "term") {
239 $term = $attributes->textContent;
240 if(strlen($item["tag"]))
242 $item["tag"] .= "#[url=".$a->get_baseurl()."/search?tag=".$term."]".$term."[/url]";
250 $links = $xpath->query('atom:link', $entry);
257 foreach ($links AS $link) {
258 foreach($link->attributes AS $attributes) {
259 if ($attributes->name == "href")
260 $href = $attributes->textContent;
261 if ($attributes->name == "rel")
262 $rel = $attributes->textContent;
263 if ($attributes->name == "type")
264 $type = $attributes->textContent;
265 if ($attributes->name == "length")
266 $length = $attributes->textContent;
267 if ($attributes->name == "title")
268 $title = $attributes->textContent;
270 if (($rel != "") AND ($href != ""))
273 $item["plink"] = $href;
275 case "ostatus:conversation":
276 $conversation = $href;
280 if(strlen($item["attach"]))
281 $item["attach"] .= ',';
283 $item["attach"] .= '[attach]href="'.$href.'" length="'.$length.'" type="'.$type.'" title="'.$title.'"[/attach]';
286 if (!isset($item["parent-uri"]))
287 $item["parent-uri"] = $href;
296 // Notification check
297 if ($importer["nurl"] == normalise_link($href))
307 $notice_info = $xpath->query('statusnet:notice_info', $entry);
308 if ($notice_info AND ($notice_info->length > 0)) {
309 foreach($notice_info->item(0)->attributes AS $attributes) {
310 if ($attributes->name == "source")
311 $item["app"] = strip_tags($attributes->textContent);
312 if ($attributes->name == "local_id")
313 $local_id = $attributes->textContent;
314 if ($attributes->name == "repeat_of")
315 $repeat_of = $attributes->textContent;
319 // Is it a repeated post?
320 if ($repeat_of != "") {
321 $activityobjects = $xpath->query('activity:object', $entry)->item(0);
323 if (is_object($activityobjects)) {
325 $orig_uris = $xpath->query("activity:object/atom:link[@rel='alternate']", $activityobjects);
327 foreach($orig_uris->item(0)->attributes AS $attributes)
328 if ($attributes->name == "href")
329 $orig_uri = $attributes->textContent;
331 if (!isset($orig_uri))
332 $orig_uri = $xpath->query("atom:link[@rel='alternate']", $activityobjects)->item(0)->nodeValue;
334 if (!isset($orig_uri))
335 $orig_uri = $xpath->query("activity:object/atom:id", $activityobjects)->item(0)->nodeValue;
337 if (!isset($orig_uri))
338 $orig_uri = $xpath->query('atom:id/text()', $activityobjects)->item(0)->nodeValue;
340 $orig_body = $xpath->query('atom:content/text()', $activityobjects)->item(0)->nodeValue;
341 $orig_created = $xpath->query('atom:published/text()', $activityobjects)->item(0)->nodeValue;
343 $orig_contact = $contact;
344 $orig_author = ostatus_fetchauthor($xpath, $activityobjects, $importer, $orig_contact);
346 //if (!intval(get_config('system','wall-to-wall_share'))) {
347 // $prefix = share_header($orig_author['author-name'], $orig_author['author-link'], $orig_author['author-avatar'], "", $orig_created, $orig_uri);
348 // $item["body"] = $prefix.add_page_info_to_body(html2bbcode($orig_body))."[/share]";
350 $item["author-name"] = $orig_author["author-name"];
351 $item["author-link"] = $orig_author["author-link"];
352 $item["author-avatar"] = $orig_author["author-avatar"];
353 $item["body"] = add_page_info_to_body(html2bbcode($orig_body));
354 $item["created"] = $orig_created;
356 $item["uri"] = $orig_uri;
359 $item["verb"] = $xpath->query('activity:verb/text()', $activityobjects)->item(0)->nodeValue;
360 $item["object-type"] = $xpath->query('activity:object-type/text()', $activityobjects)->item(0)->nodeValue;
364 //if ($enclosure != "")
365 // $item["body"] .= add_page_info($enclosure);
367 if (isset($item["parent-uri"])) {
368 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s'",
369 intval($importer["uid"]), dbesc($item["parent-uri"]));
371 if (!$r AND ($related != "")) {
372 $reply_path = str_replace("/notice/", "/api/statuses/show/", $related).".atom";
374 if ($reply_path != $related) {
375 logger("Fetching related items for user ".$importer["uid"]." from ".$reply_path, LOGGER_DEBUG);
376 $reply_xml = fetch_url($reply_path);
378 $reply_contact = $contact;
379 ostatus_import($reply_xml,$importer,$reply_contact, $reply_hub);
381 // After the import try to fetch the parent item again
382 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s'",
383 intval($importer["uid"]), dbesc($item["parent-uri"]));
387 $item["type"] = 'remote-comment';
388 $item["gravity"] = GRAVITY_COMMENT;
391 $item["parent-uri"] = $item["uri"];
393 $item_id = ostatus_completion($conversation, $importer["uid"], $item);
397 $item["app"] .= $item_id;
398 $item_id = item_store($item, true);
400 logger("Shouldn't happen. Code ".$reason." - uri ".$item["uri"], LOGGER_DEBUG);
401 ostatus_store_conversation($item_id, $conversation_url);
408 logger("Error storing item ".print_r($item, true), LOGGER_DEBUG);
412 logger("Item was stored with id ".$item_id, LOGGER_DEBUG);
413 $item["id"] = $item_id;
415 if (!isset($item["parent"]) OR ($item["parent"] == 0))
416 $item["parent"] = $item_id;
419 $u = q("SELECT `notify-flags`, `language`, `username`, `email` FROM user WHERE uid = %d LIMIT 1", intval($item['uid']));
422 'type' => NOTIFY_TAGSELF,
423 'notify_flags' => $u[0]["notify-flags"],
424 'language' => $u[0]["language"],
425 'to_name' => $u[0]["username"],
426 'to_email' => $u[0]["email"],
427 'uid' => $item["uid"],
429 'link' => $a->get_baseurl().'/display/'.urlencode(get_item_guid($item["id"])),
430 'source_name' => $item["author-name"],
431 'source_link' => $item["author-link"],
432 'source_photo' => $item["author-avatar"],
433 'verb' => ACTIVITY_TAG,
435 'parent' => $item["parent"]
441 function ostatus_convert_href($href) {
442 $elements = explode(":",$href);
444 if ((count($elements) <= 2) OR ($elements[0] != "tag"))
447 $server = explode(",", $elements[1]);
448 $conversation = explode("=", $elements[2]);
450 if ((count($elements) == 4) AND ($elements[2] == "post"))
451 return "http://".$server[0]."/notice/".$elements[3];
453 if ((count($conversation) != 2) OR ($conversation[1] ==""))
456 if ($elements[3] == "objectType=thread")
457 return "http://".$server[0]."/conversation/".$conversation[1];
459 return "http://".$server[0]."/notice/".$conversation[1];
464 function check_conversations($override = false) {
465 $last = get_config('system','ostatus_last_poll');
467 $poll_interval = intval(get_config('system','ostatus_poll_interval'));
469 $poll_interval = OSTATUS_DEFAULT_POLL_INTERVAL;
471 // Don't poll if the interval is set negative
472 if (($poll_interval < 0) AND !$override)
475 $poll_timeframe = intval(get_config('system','ostatus_poll_timeframe'));
476 if (!$poll_timeframe)
477 $poll_timeframe = OSTATUS_DEFAULT_POLL_TIMEFRAME;
479 if ($last AND !$override) {
480 $next = $last + ($poll_interval * 60);
481 if ($next > time()) {
482 logger('poll interval not reached');
487 logger('cron_start');
489 $start = date("Y-m-d H:i:s", time() - ($poll_timeframe * 60));
490 $conversations = q("SELECT `oid`, `url`, `uid` FROM `term` WHERE `type` = 7 AND `term` > '%s' GROUP BY `url`, `uid` ORDER BY `term` DESC",
493 foreach ($conversations AS $conversation) {
494 ostatus_completion($conversation['url'], $conversation['uid']);
499 set_config('system','ostatus_last_poll', time());
502 function ostatus_completion($conversation_url, $uid, $item = array()) {
506 $conversation_url = ostatus_convert_href($conversation_url);
508 // If the thread shouldn't be completed then store the item and go away
509 if ((intval(get_config('system','ostatus_poll_interval')) == -2) AND (count($item) > 0)) {
510 $item_stored = item_store($item, true);
511 return($item_stored);
515 $parents = q("SELECT `id`, `parent`, `uri`, `contact-id`, `type`, `verb`, `visible` FROM `item` WHERE `id` IN
516 (SELECT `parent` FROM `item` WHERE `id` IN
517 (SELECT `oid` FROM `term` WHERE `uid` = %d AND `otype` = %d AND `type` = %d AND `url` = '%s'))",
518 intval($uid), intval(TERM_OBJ_POST), intval(TERM_CONVERSATION), dbesc($conversation_url));
521 $parent = $parents[0];
522 elseif (count($item) > 0) {
524 $parent["type"] = "remote";
525 $parent["verb"] = ACTIVITY_POST;
526 $parent["visible"] = 1;
529 $r = q("SELECT `id` FROM `contact` WHERE `self` AND `uid`=%d", $uid);
535 $parent["parent"] = 0;
537 $parent["contact-id"] = $r[0]["id"];
538 $parent["type"] = "remote";
539 $parent["verb"] = ACTIVITY_POST;
540 $parent["visible"] = 1;
543 $conv = str_replace("/conversation/", "/api/statusnet/conversation/", $conversation_url).".as";
547 logger('fetching conversation url '.$conv.' for user '.$uid);
550 $conv_arr = z_fetch_url($conv."?page=".$pageno);
552 // If it is a non-ssl site and there is an error, then try ssl or vice versa
553 if (!$conv_arr["success"] AND (substr($conv, 0, 7) == "http://")) {
554 $conv = str_replace("http://", "https://", $conv);
555 $conv_as = fetch_url($conv."?page=".$pageno);
556 } elseif (!$conv_arr["success"] AND (substr($conv, 0, 8) == "https://")) {
557 $conv = str_replace("https://", "http://", $conv);
558 $conv_as = fetch_url($conv."?page=".$pageno);
560 $conv_as = $conv_arr["body"];
562 $conv_as = str_replace(',"statusnet:notice_info":', ',"statusnet_notice_info":', $conv_as);
563 $conv_as = json_decode($conv_as);
565 if (@is_array($conv_as->items))
566 $items = array_merge($items, $conv_as->items);
574 logger('fetching conversation done. Found '.count($items).' items');
576 if (!sizeof($items)) {
577 if (count($item) > 0) {
578 $item_stored = item_store($item, true);
579 logger("Conversation ".$conversation_url." couldn't be fetched. Item uri ".$item["uri"]." stored: ".$item_stored, LOGGER_DEBUG);
582 ostatus_store_conversation($item_id, $conversation_url);
584 return($item_stored);
589 $items = array_reverse($items);
591 foreach ($items as $single_conv) {
593 // Test - remove before flight
594 //$tempfile = tempnam(get_temppath(), "conversation");
595 //file_put_contents($tempfile, json_encode($single_conv));
598 if (isset($single_conv->object->id))
599 $single_conv->id = $single_conv->object->id;
601 $plink = ostatus_convert_href($single_conv->id);
602 if (isset($single_conv->object->url))
603 $plink = ostatus_convert_href($single_conv->object->url);
605 if (@!$single_conv->id)
608 logger("Got id ".$single_conv->id, LOGGER_DEBUG);
610 if ($first_id == "") {
611 $first_id = $single_conv->id;
613 // The first post of the conversation isn't our first post. There are three options:
614 // 1. Our conversation hasn't the "real" thread starter
615 // 2. This first post is a post inside our thread
616 // 3. This first post is a post inside another thread
617 if (($first_id != $parent["uri"]) AND ($parent["uri"] != "")) {
618 $new_parents = q("SELECT `id`, `parent`, `uri`, `contact-id`, `type`, `verb`, `visible` FROM `item` WHERE `id` IN
619 (SELECT `parent` FROM `item`
620 WHERE `uid` = %d AND `uri` = '%s' AND `network` IN ('%s','%s')) LIMIT 1",
621 intval($uid), dbesc($first_id), dbesc(NETWORK_OSTATUS), dbesc(NETWORK_DFRN));
623 if ($new_parents[0]["parent"] == $parent["parent"]) {
624 // Option 2: This post is already present inside our thread - but not as thread starter
625 logger("Option 2: uri present in our thread: ".$first_id, LOGGER_DEBUG);
626 $first_id = $parent["uri"];
628 // Option 3: Not so good. We have mixed parents. We have to see how to clean this up.
629 // For now just take the new parent.
630 $parent = $new_parents[0];
631 $first_id = $parent["uri"];
632 logger("Option 3: mixed parents for uri ".$first_id, LOGGER_DEBUG);
635 // Option 1: We hadn't got the real thread starter
636 // We have to clean up our existing messages.
638 $parent["uri"] = $first_id;
639 logger("Option 1: we have a new parent: ".$first_id, LOGGER_DEBUG);
641 } elseif ($parent["uri"] == "") {
643 $parent["uri"] = $first_id;
647 if (isset($single_conv->context->inReplyTo->id)) {
648 $parent_uri = $single_conv->context->inReplyTo->id;
650 $parent_exists = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `network` IN ('%s','%s') LIMIT 1",
651 intval($uid), dbesc($parent_uri), dbesc(NETWORK_OSTATUS), dbesc(NETWORK_DFRN));
652 if (!$parent_exists) {
653 logger("Parent ".$parent_uri." wasn't found here", LOGGER_DEBUG);
654 $parent_uri = $parent["uri"];
657 $parent_uri = $parent["uri"];
659 $message_exists = q("SELECT `id`, `parent`, `uri` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `network` IN ('%s','%s') LIMIT 1",
660 intval($uid), dbesc($single_conv->id),
661 dbesc(NETWORK_OSTATUS), dbesc(NETWORK_DFRN));
662 if ($message_exists) {
663 logger("Message ".$single_conv->id." already existed on the system", LOGGER_DEBUG);
665 if ($parent["id"] != 0) {
666 $existing_message = $message_exists[0];
668 // We improved the way we fetch OStatus messages, this shouldn't happen very often now
669 // To-Do: we have to change the shadow copies as well. This way here is really ugly.
670 if ($existing_message["parent"] != $parent["id"]) {
671 logger('updating id '.$existing_message["id"].' with parent '.$existing_message["parent"].' to parent '.$parent["id"].' uri '.$parent["uri"].' thread '.$parent_uri, LOGGER_DEBUG);
673 // Update the parent id of the selected item
674 $r = q("UPDATE `item` SET `parent` = %d, `parent-uri` = '%s' WHERE `id` = %d",
675 intval($parent["id"]), dbesc($parent["uri"]), intval($existing_message["id"]));
677 // Update the parent uri in the thread - but only if it points to itself
678 $r = q("UPDATE `item` SET `thr-parent` = '%s' WHERE `id` = %d AND `uri` = `thr-parent`",
679 dbesc($parent_uri), intval($existing_message["id"]));
681 // try to change all items of the same parent
682 $r = q("UPDATE `item` SET `parent` = %d, `parent-uri` = '%s' WHERE `parent` = %d",
683 intval($parent["id"]), dbesc($parent["uri"]), intval($existing_message["parent"]));
685 // Update the parent uri in the thread - but only if it points to itself
686 $r = q("UPDATE `item` SET `thr-parent` = '%s' WHERE (`parent` = %d) AND (`uri` = `thr-parent`)",
687 dbesc($parent["uri"]), intval($existing_message["parent"]));
689 // Now delete the thread
690 delete_thread($existing_message["parent"]);
694 // The item we are having on the system is the one that we wanted to store via the item array
695 if (isset($item["uri"]) AND ($item["uri"] == $existing_message["uri"])) {
703 $actor = $single_conv->actor->id;
704 if (isset($single_conv->actor->url))
705 $actor = $single_conv->actor->url;
707 $contact = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `nurl` = '%s' AND `network` != '%s'",
708 $uid, normalise_link($actor), NETWORK_STATUSNET);
710 if (count($contact)) {
711 logger("Found contact for url ".$actor, LOGGER_DEBUG);
712 $contact_id = $contact[0]["id"];
714 logger("No contact found for url ".$actor, LOGGER_DEBUG);
716 // Adding a global contact
717 // To-Do: Use this data for the post
718 $global_contact_id = get_contact($actor, 0);
720 logger("Global contact ".$global_contact_id." found for url ".$actor, LOGGER_DEBUG);
722 $contact_id = $parent["contact-id"];
726 $arr["network"] = NETWORK_OSTATUS;
727 $arr["uri"] = $single_conv->id;
728 $arr["plink"] = $plink;
730 $arr["contact-id"] = $contact_id;
731 $arr["parent-uri"] = $parent_uri;
732 $arr["created"] = $single_conv->published;
733 $arr["edited"] = $single_conv->published;
734 $arr["owner-name"] = $single_conv->actor->displayName;
735 if ($arr["owner-name"] == '')
736 $arr["owner-name"] = $single_conv->actor->contact->displayName;
737 if ($arr["owner-name"] == '')
738 $arr["owner-name"] = $single_conv->actor->portablecontacts_net->displayName;
740 $arr["owner-link"] = $actor;
741 $arr["owner-avatar"] = $single_conv->actor->image->url;
742 $arr["author-name"] = $arr["owner-name"];
743 $arr["author-link"] = $actor;
744 $arr["author-avatar"] = $single_conv->actor->image->url;
745 $arr["body"] = add_page_info_to_body(html2bbcode($single_conv->content));
747 if (isset($single_conv->status_net->notice_info->source))
748 $arr["app"] = strip_tags($single_conv->status_net->notice_info->source);
749 elseif (isset($single_conv->statusnet->notice_info->source))
750 $arr["app"] = strip_tags($single_conv->statusnet->notice_info->source);
751 elseif (isset($single_conv->statusnet_notice_info->source))
752 $arr["app"] = strip_tags($single_conv->statusnet_notice_info->source);
753 elseif (isset($single_conv->provider->displayName))
754 $arr["app"] = $single_conv->provider->displayName;
756 $arr["app"] = "OStatus";
758 $arr["app"] .= " (Conversation)";
760 $arr["object"] = json_encode($single_conv);
761 $arr["verb"] = $parent["verb"];
762 $arr["visible"] = $parent["visible"];
763 $arr["location"] = $single_conv->location->displayName;
764 $arr["coord"] = trim($single_conv->location->lat." ".$single_conv->location->lon);
766 // Is it a reshared item?
767 if (isset($item->verb) AND ($item->verb == "share") AND isset($item->object)) {
768 if (is_array($item->object))
769 $item->object = $item->object[0];
771 logger("Found reshared item ".$single_conv->object->id);
773 // $single_conv->object->context->conversation;
775 $plink = ostatus_convert_href($single_conv->object->url);
777 $arr["uri"] = $single_conv->object->id;
778 $arr["plink"] = $plink;
779 $arr["created"] = $single_conv->object->published;
780 $arr["edited"] = $single_conv->object->published;
782 $arr["author-name"] = $single_conv->object->actor->displayName;
783 if ($arr["owner-name"] == '')
784 $arr["author-name"] = $single_conv->object->actor->contact->displayName;
786 $arr["author-link"] = $single_conv->object->actor->url;
787 $arr["author-avatar"] = $single_conv->object->actor->image->url;
789 $arr["body"] = add_page_info_to_body(html2bbcode($single_conv->object->content));
790 $arr["app"] = $single_conv->object->provider->displayName."#";
791 //$arr["verb"] = $single_conv->object->verb;
793 $arr["location"] = $single_conv->object->location->displayName;
794 $arr["coord"] = trim($single_conv->object->location->lat." ".$single_conv->object->location->lon);
797 if ($arr["location"] == "")
798 unset($arr["location"]);
800 if ($arr["coord"] == "")
801 unset($arr["coord"]);
803 // Copy fields from given item array
804 if (isset($item["uri"]) AND ($item["uri"] == $arr["uri"])) {
805 $copy_fields = array("owner-name", "owner-link", "owner-avatar", "author-name", "author-link", "author-avatar",
806 "gravity", "body", "object-type", "verb", "created", "edited", "coord", "tag",
807 "attach", "app", "type", "location", "contact-id");
808 foreach ($copy_fields AS $field)
809 if (isset($item[$field]))
810 $arr[$field] = $item[$field];
812 $arr["app"] .= " (OStatus)";
815 $newitem = item_store($arr);
817 logger("Item wasn't stored ".print_r($arr, true), LOGGER_DEBUG);
821 if (isset($item["uri"]) AND ($item["uri"] == $arr["uri"])) {
823 $item_stored = $newitem;
826 logger('Stored new item '.$plink.' for parent '.$arr["parent-uri"].' under id '.$newitem, LOGGER_DEBUG);
828 // Add the conversation entry (but don't fetch the whole conversation)
829 ostatus_store_conversation($newitem, $conversation_url);
831 // If the newly created item is the top item then change the parent settings of the thread
832 // This shouldn't happen anymore. This is supposed to be absolote.
833 if ($arr["uri"] == $first_id) {
834 logger('setting new parent to id '.$newitem);
835 $new_parents = q("SELECT `id`, `uri`, `contact-id`, `type`, `verb`, `visible` FROM `item` WHERE `uid` = %d AND `id` = %d LIMIT 1",
836 intval($uid), intval($newitem));
838 $parent = $new_parents[0];
842 return($item_stored);
845 function ostatus_store_conversation($itemid, $conversation_url) {
848 $conversation_url = ostatus_convert_href($conversation_url);
850 $messages = q("SELECT `uid`, `parent`, `created`, `received`, `guid` FROM `item` WHERE `id` = %d LIMIT 1", intval($itemid));
853 $message = $messages[0];
855 // Store conversation url if not done before
856 $conversation = q("SELECT `url` FROM `term` WHERE `uid` = %d AND `oid` = %d AND `otype` = %d AND `type` = %d",
857 intval($message["uid"]), intval($itemid), intval(TERM_OBJ_POST), intval(TERM_CONVERSATION));
859 if (!$conversation) {
860 $r = q("INSERT INTO `term` (`uid`, `oid`, `otype`, `type`, `term`, `url`, `created`, `received`, `guid`) VALUES (%d, %d, %d, %d, '%s', '%s', '%s', '%s', '%s')",
861 intval($message["uid"]), intval($itemid), intval(TERM_OBJ_POST), intval(TERM_CONVERSATION),
862 dbesc($message["created"]), dbesc($conversation_url), dbesc($message["created"]), dbesc($message["received"]), dbesc($message["guid"]));
863 logger('Storing conversation url '.$conversation_url.' for id '.$itemid);