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;
194 if (($item["object-type"] == ACTIVITY_OBJ_BOOKMARK) OR ($item["object-type"] == ACTIVITY_OBJ_EVENT)) {
195 $item["title"] = $xpath->query('atom:title/text()', $entry)->item(0)->nodeValue;
196 $item["body"] = $xpath->query('atom:summary/text()', $entry)->item(0)->nodeValue;
197 } elseif ($item["object-type"] == ACTIVITY_OBJ_QUESTION)
198 $item["title"] = $xpath->query('atom:title/text()', $entry)->item(0)->nodeValue;
200 $item["object"] = $xml;
201 $item["verb"] = $xpath->query('activity:verb/text()', $entry)->item(0)->nodeValue;
205 if ($item["verb"] == "qvitter-delete-notice") {
206 // ignore "Delete" messages (by now)
210 if ($item["verb"] == ACTIVITY_JOIN) {
211 // ignore "Join" messages
215 if ($item["verb"] == ACTIVITY_FOLLOW) {
216 // ignore "Follow" messages
220 if ($item["verb"] == ACTIVITY_FAVORITE) {
221 // ignore "Favorite" messages
225 $item["created"] = $xpath->query('atom:published/text()', $entry)->item(0)->nodeValue;
226 $item["edited"] = $xpath->query('atom:updated/text()', $entry)->item(0)->nodeValue;
227 $conversation = $xpath->query('ostatus:conversation/text()', $entry)->item(0)->nodeValue;
231 $inreplyto = $xpath->query('thr:in-reply-to', $entry);
232 if (is_object($inreplyto->item(0))) {
233 foreach($inreplyto->item(0)->attributes AS $attributes) {
234 if ($attributes->name == "ref")
235 $item["parent-uri"] = $attributes->textContent;
236 if ($attributes->name == "href")
237 $related = $attributes->textContent;
241 $georsspoint = $xpath->query('georss:point', $entry);
243 $item["coord"] = $georsspoint->item(0)->nodeValue;
246 // $item["location"] =
248 $categories = $xpath->query('atom:category', $entry);
250 foreach ($categories AS $category) {
251 foreach($category->attributes AS $attributes)
252 if ($attributes->name == "term") {
253 $term = $attributes->textContent;
254 if(strlen($item["tag"]))
256 $item["tag"] .= "#[url=".$a->get_baseurl()."/search?tag=".$term."]".$term."[/url]";
264 $links = $xpath->query('atom:link', $entry);
271 foreach ($links AS $link) {
272 foreach($link->attributes AS $attributes) {
273 if ($attributes->name == "href")
274 $href = $attributes->textContent;
275 if ($attributes->name == "rel")
276 $rel = $attributes->textContent;
277 if ($attributes->name == "type")
278 $type = $attributes->textContent;
279 if ($attributes->name == "length")
280 $length = $attributes->textContent;
281 if ($attributes->name == "title")
282 $title = $attributes->textContent;
284 if (($rel != "") AND ($href != ""))
287 $item["plink"] = $href;
288 if (($item["object-type"] == ACTIVITY_OBJ_QUESTION) OR
289 ($item["object-type"] == ACTIVITY_OBJ_EVENT))
290 $item["body"] .= add_page_info($href);
292 case "ostatus:conversation":
293 $conversation = $href;
297 if(strlen($item["attach"]))
298 $item["attach"] .= ',';
300 $item["attach"] .= '[attach]href="'.$href.'" length="'.$length.'" type="'.$type.'" title="'.$title.'"[/attach]';
303 if ($item["object-type"] != ACTIVITY_OBJ_BOOKMARK) {
304 if (!isset($item["parent-uri"]))
305 $item["parent-uri"] = $href;
310 $item["body"] .= add_page_info($href);
316 // Notification check
317 if ($importer["nurl"] == normalise_link($href))
327 $notice_info = $xpath->query('statusnet:notice_info', $entry);
328 if ($notice_info AND ($notice_info->length > 0)) {
329 foreach($notice_info->item(0)->attributes AS $attributes) {
330 if ($attributes->name == "source")
331 $item["app"] = strip_tags($attributes->textContent);
332 if ($attributes->name == "local_id")
333 $local_id = $attributes->textContent;
334 if ($attributes->name == "repeat_of")
335 $repeat_of = $attributes->textContent;
339 // Is it a repeated post?
340 if ($repeat_of != "") {
341 $activityobjects = $xpath->query('activity:object', $entry)->item(0);
343 if (is_object($activityobjects)) {
345 $orig_uri = $xpath->query("activity:object/atom:id", $activityobjects)->item(0)->nodeValue;
346 if (!isset($orig_uri))
347 $orig_uri = $xpath->query('atom:id/text()', $activityobjects)->item(0)->nodeValue;
349 $orig_links = $xpath->query("activity:object/atom:link[@rel='alternate']", $activityobjects);
350 if ($orig_links AND ($orig_links->length > 0))
351 foreach($orig_links->item(0)->attributes AS $attributes)
352 if ($attributes->name == "href")
353 $orig_link = $attributes->textContent;
355 if (!isset($orig_link))
356 $orig_link = $xpath->query("atom:link[@rel='alternate']", $activityobjects)->item(0)->nodeValue;
358 if (!isset($orig_link))
359 $orig_link = ostatus_convert_href($orig_uri);
361 $orig_body = $xpath->query('activity:object/atom:content/text()', $activityobjects)->item(0)->nodeValue;
362 if (!isset($orig_body))
363 $orig_body = $xpath->query('atom:content/text()', $activityobjects)->item(0)->nodeValue;
365 $orig_created = $xpath->query('atom:published/text()', $activityobjects)->item(0)->nodeValue;
367 $orig_contact = $contact;
368 $orig_author = ostatus_fetchauthor($xpath, $activityobjects, $importer, $orig_contact);
370 //if (!intval(get_config('system','wall-to-wall_share'))) {
371 // $prefix = share_header($orig_author['author-name'], $orig_author['author-link'], $orig_author['author-avatar'], "", $orig_created, $orig_link);
372 // $item["body"] = $prefix.add_page_info_to_body(html2bbcode($orig_body))."[/share]";
374 $item["author-name"] = $orig_author["author-name"];
375 $item["author-link"] = $orig_author["author-link"];
376 $item["author-avatar"] = $orig_author["author-avatar"];
377 $item["body"] = add_page_info_to_body(html2bbcode($orig_body));
378 $item["created"] = $orig_created;
380 $item["uri"] = $orig_uri;
381 $item["plink"] = $orig_link;
384 $item["verb"] = $xpath->query('activity:verb/text()', $activityobjects)->item(0)->nodeValue;
386 $item["object-type"] = $xpath->query('activity:object/activity:object-type/text()', $activityobjects)->item(0)->nodeValue;
387 if (!isset($item["object-type"]))
388 $item["object-type"] = $xpath->query('activity:object-type/text()', $activityobjects)->item(0)->nodeValue;
392 //if ($enclosure != "")
393 // $item["body"] .= add_page_info($enclosure);
395 if (isset($item["parent-uri"])) {
396 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s'",
397 intval($importer["uid"]), dbesc($item["parent-uri"]));
399 if (!$r AND ($related != "")) {
400 $reply_path = str_replace("/notice/", "/api/statuses/show/", $related).".atom";
402 if ($reply_path != $related) {
403 logger("Fetching related items for user ".$importer["uid"]." from ".$reply_path, LOGGER_DEBUG);
404 $reply_xml = fetch_url($reply_path);
406 $reply_contact = $contact;
407 ostatus_import($reply_xml,$importer,$reply_contact, $reply_hub);
409 // After the import try to fetch the parent item again
410 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s'",
411 intval($importer["uid"]), dbesc($item["parent-uri"]));
415 $item["type"] = 'remote-comment';
416 $item["gravity"] = GRAVITY_COMMENT;
419 $item["parent-uri"] = $item["uri"];
421 $item_id = ostatus_completion($conversation, $importer["uid"], $item);
424 logger("Error storing item", LOGGER_DEBUG);
428 logger("Item was stored with id ".$item_id, LOGGER_DEBUG);
429 $item["id"] = $item_id;
432 $u = q("SELECT `notify-flags`, `language`, `username`, `email` FROM user WHERE uid = %d LIMIT 1", intval($item['uid']));
433 $r = q("SELECT `parent` FROM `item` WHERE `id` = %d", intval($item_id));
436 'type' => NOTIFY_TAGSELF,
437 'notify_flags' => $u[0]["notify-flags"],
438 'language' => $u[0]["language"],
439 'to_name' => $u[0]["username"],
440 'to_email' => $u[0]["email"],
441 'uid' => $item["uid"],
443 'link' => $a->get_baseurl().'/display/'.urlencode(get_item_guid($item_id)),
444 'source_name' => $item["author-name"],
445 'source_link' => $item["author-link"],
446 'source_photo' => $item["author-avatar"],
447 'verb' => ACTIVITY_TAG,
449 'parent' => $r[0]["parent"]
455 function ostatus_convert_href($href) {
456 $elements = explode(":",$href);
458 if ((count($elements) <= 2) OR ($elements[0] != "tag"))
461 $server = explode(",", $elements[1]);
462 $conversation = explode("=", $elements[2]);
464 if ((count($elements) == 4) AND ($elements[2] == "post"))
465 return "http://".$server[0]."/notice/".$elements[3];
467 if ((count($conversation) != 2) OR ($conversation[1] ==""))
470 if ($elements[3] == "objectType=thread")
471 return "http://".$server[0]."/conversation/".$conversation[1];
473 return "http://".$server[0]."/notice/".$conversation[1];
478 function check_conversations($override = false) {
479 $last = get_config('system','ostatus_last_poll');
481 $poll_interval = intval(get_config('system','ostatus_poll_interval'));
483 $poll_interval = OSTATUS_DEFAULT_POLL_INTERVAL;
485 // Don't poll if the interval is set negative
486 if (($poll_interval < 0) AND !$override)
489 $poll_timeframe = intval(get_config('system','ostatus_poll_timeframe'));
490 if (!$poll_timeframe)
491 $poll_timeframe = OSTATUS_DEFAULT_POLL_TIMEFRAME;
493 if ($last AND !$override) {
494 $next = $last + ($poll_interval * 60);
495 if ($next > time()) {
496 logger('poll interval not reached');
501 logger('cron_start');
503 $start = date("Y-m-d H:i:s", time() - ($poll_timeframe * 60));
504 $conversations = q("SELECT `oid`, `url`, `uid` FROM `term` WHERE `type` = 7 AND `term` > '%s' GROUP BY `url`, `uid` ORDER BY `term` DESC",
507 foreach ($conversations AS $conversation) {
508 ostatus_completion($conversation['url'], $conversation['uid']);
513 set_config('system','ostatus_last_poll', time());
516 function ostatus_completion($conversation_url, $uid, $item = array()) {
522 $conversation_url = ostatus_convert_href($conversation_url);
524 // If the thread shouldn't be completed then store the item and go away
525 if ((intval(get_config('system','ostatus_poll_interval')) == -2) AND (count($item) > 0)) {
526 //$arr["app"] .= " (OStatus-NoCompletion)";
527 $item_stored = item_store($item, true);
528 return($item_stored);
532 $parents = q("SELECT `id`, `parent`, `uri`, `contact-id`, `type`, `verb`, `visible` FROM `item` WHERE `id` IN
533 (SELECT `parent` FROM `item` WHERE `id` IN
534 (SELECT `oid` FROM `term` WHERE `uid` = %d AND `otype` = %d AND `type` = %d AND `url` = '%s'))",
535 intval($uid), intval(TERM_OBJ_POST), intval(TERM_CONVERSATION), dbesc($conversation_url));
538 $parent = $parents[0];
539 elseif (count($item) > 0) {
541 $parent["type"] = "remote";
542 $parent["verb"] = ACTIVITY_POST;
543 $parent["visible"] = 1;
546 $r = q("SELECT `id` FROM `contact` WHERE `self` AND `uid`=%d", $uid);
552 $parent["parent"] = 0;
554 $parent["contact-id"] = $r[0]["id"];
555 $parent["type"] = "remote";
556 $parent["verb"] = ACTIVITY_POST;
557 $parent["visible"] = 1;
560 $conv = str_replace("/conversation/", "/api/statusnet/conversation/", $conversation_url).".as";
564 logger('fetching conversation url '.$conv.' for user '.$uid);
567 $conv_arr = z_fetch_url($conv."?page=".$pageno);
569 // If it is a non-ssl site and there is an error, then try ssl or vice versa
570 if (!$conv_arr["success"] AND (substr($conv, 0, 7) == "http://")) {
571 $conv = str_replace("http://", "https://", $conv);
572 $conv_as = fetch_url($conv."?page=".$pageno);
573 } elseif (!$conv_arr["success"] AND (substr($conv, 0, 8) == "https://")) {
574 $conv = str_replace("https://", "http://", $conv);
575 $conv_as = fetch_url($conv."?page=".$pageno);
577 $conv_as = $conv_arr["body"];
579 $conv_as = str_replace(',"statusnet:notice_info":', ',"statusnet_notice_info":', $conv_as);
580 $conv_as = json_decode($conv_as);
582 if (@is_array($conv_as->items))
583 $items = array_merge($items, $conv_as->items);
591 logger('fetching conversation done. Found '.count($items).' items');
593 if (!sizeof($items)) {
594 if (count($item) > 0) {
595 //$arr["app"] .= " (OStatus-NoConvFetched)";
596 $item_stored = item_store($item, true);
599 logger("Conversation ".$conversation_url." couldn't be fetched. Item uri ".$item["uri"]." stored: ".$item_stored, LOGGER_DEBUG);
600 ostatus_store_conversation($item_id, $conversation_url);
603 return($item_stored);
608 $items = array_reverse($items);
610 $r = q("SELECT `nurl` FROM `contact` WHERE `uid` = %d AND `self`", intval($uid));
613 foreach ($items as $single_conv) {
615 // Test - remove before flight
616 //$tempfile = tempnam(get_temppath(), "conversation");
617 //file_put_contents($tempfile, json_encode($single_conv));
621 if (isset($single_conv->object->id))
622 $single_conv->id = $single_conv->object->id;
624 $plink = ostatus_convert_href($single_conv->id);
625 if (isset($single_conv->object->url))
626 $plink = ostatus_convert_href($single_conv->object->url);
628 if (@!$single_conv->id)
631 logger("Got id ".$single_conv->id, LOGGER_DEBUG);
633 if ($first_id == "") {
634 $first_id = $single_conv->id;
636 // The first post of the conversation isn't our first post. There are three options:
637 // 1. Our conversation hasn't the "real" thread starter
638 // 2. This first post is a post inside our thread
639 // 3. This first post is a post inside another thread
640 if (($first_id != $parent["uri"]) AND ($parent["uri"] != "")) {
641 $new_parents = q("SELECT `id`, `parent`, `uri`, `contact-id`, `type`, `verb`, `visible` FROM `item` WHERE `id` IN
642 (SELECT `parent` FROM `item`
643 WHERE `uid` = %d AND `uri` = '%s' AND `network` IN ('%s','%s')) LIMIT 1",
644 intval($uid), dbesc($first_id), dbesc(NETWORK_OSTATUS), dbesc(NETWORK_DFRN));
646 if ($new_parents[0]["parent"] == $parent["parent"]) {
647 // Option 2: This post is already present inside our thread - but not as thread starter
648 logger("Option 2: uri present in our thread: ".$first_id, LOGGER_DEBUG);
649 $first_id = $parent["uri"];
651 // Option 3: Not so good. We have mixed parents. We have to see how to clean this up.
652 // For now just take the new parent.
653 $parent = $new_parents[0];
654 $first_id = $parent["uri"];
655 logger("Option 3: mixed parents for uri ".$first_id, LOGGER_DEBUG);
658 // Option 1: We hadn't got the real thread starter
659 // We have to clean up our existing messages.
661 $parent["uri"] = $first_id;
662 logger("Option 1: we have a new parent: ".$first_id, LOGGER_DEBUG);
664 } elseif ($parent["uri"] == "") {
666 $parent["uri"] = $first_id;
670 $parent_uri = $parent["uri"];
672 // "context" only seems to exist on older servers
673 if (isset($single_conv->context->inReplyTo->id)) {
674 $parent_exists = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `network` IN ('%s','%s') LIMIT 1",
675 intval($uid), dbesc($single_conv->context->inReplyTo->id), dbesc(NETWORK_OSTATUS), dbesc(NETWORK_DFRN));
677 $parent_uri = $single_conv->context->inReplyTo->id;
680 // This is the current way
681 if (isset($single_conv->object->inReplyTo->id)) {
682 $parent_exists = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `network` IN ('%s','%s') LIMIT 1",
683 intval($uid), dbesc($single_conv->object->inReplyTo->id), dbesc(NETWORK_OSTATUS), dbesc(NETWORK_DFRN));
685 $parent_uri = $single_conv->object->inReplyTo->id;
688 $message_exists = q("SELECT `id`, `parent`, `uri` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `network` IN ('%s','%s') LIMIT 1",
689 intval($uid), dbesc($single_conv->id),
690 dbesc(NETWORK_OSTATUS), dbesc(NETWORK_DFRN));
691 if ($message_exists) {
692 logger("Message ".$single_conv->id." already existed on the system", LOGGER_DEBUG);
694 if ($parent["id"] != 0) {
695 $existing_message = $message_exists[0];
697 // We improved the way we fetch OStatus messages, this shouldn't happen very often now
698 // To-Do: we have to change the shadow copies as well. This way here is really ugly.
699 if ($existing_message["parent"] != $parent["id"]) {
700 logger('updating id '.$existing_message["id"].' with parent '.$existing_message["parent"].' to parent '.$parent["id"].' uri '.$parent["uri"].' thread '.$parent_uri, LOGGER_DEBUG);
702 // Update the parent id of the selected item
703 $r = q("UPDATE `item` SET `parent` = %d, `parent-uri` = '%s' WHERE `id` = %d",
704 intval($parent["id"]), dbesc($parent["uri"]), intval($existing_message["id"]));
706 // Update the parent uri in the thread - but only if it points to itself
707 $r = q("UPDATE `item` SET `thr-parent` = '%s' WHERE `id` = %d AND `uri` = `thr-parent`",
708 dbesc($parent_uri), intval($existing_message["id"]));
710 // try to change all items of the same parent
711 $r = q("UPDATE `item` SET `parent` = %d, `parent-uri` = '%s' WHERE `parent` = %d",
712 intval($parent["id"]), dbesc($parent["uri"]), intval($existing_message["parent"]));
714 // Update the parent uri in the thread - but only if it points to itself
715 $r = q("UPDATE `item` SET `thr-parent` = '%s' WHERE (`parent` = %d) AND (`uri` = `thr-parent`)",
716 dbesc($parent["uri"]), intval($existing_message["parent"]));
718 // Now delete the thread
719 delete_thread($existing_message["parent"]);
723 // The item we are having on the system is the one that we wanted to store via the item array
724 if (isset($item["uri"]) AND ($item["uri"] == $existing_message["uri"])) {
732 if (is_array($single_conv->to))
733 foreach($single_conv->to AS $to)
734 if ($importer["nurl"] == normalise_link($to->id))
737 $actor = $single_conv->actor->id;
738 if (isset($single_conv->actor->url))
739 $actor = $single_conv->actor->url;
741 $contact = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `nurl` = '%s' AND `network` != '%s'",
742 $uid, normalise_link($actor), NETWORK_STATUSNET);
744 if (count($contact)) {
745 logger("Found contact for url ".$actor, LOGGER_DEBUG);
746 $contact_id = $contact[0]["id"];
748 logger("No contact found for url ".$actor, LOGGER_DEBUG);
750 // Adding a global contact
751 // To-Do: Use this data for the post
752 $global_contact_id = get_contact($actor, 0);
754 logger("Global contact ".$global_contact_id." found for url ".$actor, LOGGER_DEBUG);
756 $contact_id = $parent["contact-id"];
760 $arr["network"] = NETWORK_OSTATUS;
761 $arr["uri"] = $single_conv->id;
762 $arr["plink"] = $plink;
764 $arr["contact-id"] = $contact_id;
765 $arr["parent-uri"] = $parent_uri;
766 $arr["created"] = $single_conv->published;
767 $arr["edited"] = $single_conv->published;
768 $arr["owner-name"] = $single_conv->actor->displayName;
769 if ($arr["owner-name"] == '')
770 $arr["owner-name"] = $single_conv->actor->contact->displayName;
771 if ($arr["owner-name"] == '')
772 $arr["owner-name"] = $single_conv->actor->portablecontacts_net->displayName;
774 $arr["owner-link"] = $actor;
775 $arr["owner-avatar"] = $single_conv->actor->image->url;
776 $arr["author-name"] = $arr["owner-name"];
777 $arr["author-link"] = $actor;
778 $arr["author-avatar"] = $single_conv->actor->image->url;
779 $arr["body"] = add_page_info_to_body(html2bbcode($single_conv->content));
781 if (isset($single_conv->status_net->notice_info->source))
782 $arr["app"] = strip_tags($single_conv->status_net->notice_info->source);
783 elseif (isset($single_conv->statusnet->notice_info->source))
784 $arr["app"] = strip_tags($single_conv->statusnet->notice_info->source);
785 elseif (isset($single_conv->statusnet_notice_info->source))
786 $arr["app"] = strip_tags($single_conv->statusnet_notice_info->source);
787 elseif (isset($single_conv->provider->displayName))
788 $arr["app"] = $single_conv->provider->displayName;
790 $arr["app"] = "OStatus";
792 //$arr["app"] .= " (Conversation)";
794 $arr["object"] = json_encode($single_conv);
795 $arr["verb"] = $parent["verb"];
796 $arr["visible"] = $parent["visible"];
797 $arr["location"] = $single_conv->location->displayName;
798 $arr["coord"] = trim($single_conv->location->lat." ".$single_conv->location->lon);
800 // Is it a reshared item?
801 if (isset($single_conv->verb) AND ($single_conv->verb == "share") AND isset($single_conv->object)) {
802 if (is_array($single_conv->object))
803 $single_conv->object = $single_conv->object[0];
805 logger("Found reshared item ".$single_conv->object->id);
807 // $single_conv->object->context->conversation;
809 if (isset($single_conv->object->object->id))
810 $arr["uri"] = $single_conv->object->object->id;
812 $arr["uri"] = $single_conv->object->id;
814 if (isset($single_conv->object->object->url))
815 $plink = ostatus_convert_href($single_conv->object->object->url);
817 $plink = ostatus_convert_href($single_conv->object->url);
819 if (isset($single_conv->object->object->content))
820 $arr["body"] = add_page_info_to_body(html2bbcode($single_conv->object->object->content));
822 $arr["body"] = add_page_info_to_body(html2bbcode($single_conv->object->content));
824 $arr["plink"] = $plink;
826 $arr["created"] = $single_conv->object->published;
827 $arr["edited"] = $single_conv->object->published;
829 $arr["author-name"] = $single_conv->object->actor->displayName;
830 if ($arr["owner-name"] == '')
831 $arr["author-name"] = $single_conv->object->actor->contact->displayName;
833 $arr["author-link"] = $single_conv->object->actor->url;
834 $arr["author-avatar"] = $single_conv->object->actor->image->url;
836 $arr["app"] = $single_conv->object->provider->displayName."#";
837 //$arr["verb"] = $single_conv->object->verb;
839 $arr["location"] = $single_conv->object->location->displayName;
840 $arr["coord"] = trim($single_conv->object->location->lat." ".$single_conv->object->location->lon);
843 if ($arr["location"] == "")
844 unset($arr["location"]);
846 if ($arr["coord"] == "")
847 unset($arr["coord"]);
849 // Copy fields from given item array
850 if (isset($item["uri"]) AND (($item["uri"] == $arr["uri"]) OR ($item["uri"] == $single_conv->id))) {
851 $copy_fields = array("owner-name", "owner-link", "owner-avatar", "author-name", "author-link", "author-avatar",
852 "gravity", "body", "object-type", "object", "verb", "created", "edited", "coord", "tag",
853 "title", "attach", "app", "type", "location", "contact-id", "uri");
854 foreach ($copy_fields AS $field)
855 if (isset($item[$field]))
856 $arr[$field] = $item[$field];
858 //$arr["app"] .= " (OStatus)";
861 $newitem = item_store($arr);
863 logger("Item wasn't stored ".print_r($arr, true), LOGGER_DEBUG);
867 if (isset($item["uri"]) AND ($item["uri"] == $arr["uri"])) {
869 $item_stored = $newitem;
872 logger('Stored new item '.$plink.' for parent '.$arr["parent-uri"].' under id '.$newitem, LOGGER_DEBUG);
874 // Add the conversation entry (but don't fetch the whole conversation)
875 ostatus_store_conversation($newitem, $conversation_url);
878 $u = q("SELECT `notify-flags`, `language`, `username`, `email` FROM user WHERE uid = %d LIMIT 1", intval($uid));
879 $r = q("SELECT `parent` FROM `item` WHERE `id` = %d", intval($newitem));
882 'type' => NOTIFY_TAGSELF,
883 'notify_flags' => $u[0]["notify-flags"],
884 'language' => $u[0]["language"],
885 'to_name' => $u[0]["username"],
886 'to_email' => $u[0]["email"],
889 'link' => $a->get_baseurl().'/display/'.urlencode(get_item_guid($newitem)),
890 'source_name' => $arr["author-name"],
891 'source_link' => $arr["author-link"],
892 'source_photo' => $arr["author-avatar"],
893 'verb' => ACTIVITY_TAG,
895 'parent' => $r[0]["parent"]
899 // If the newly created item is the top item then change the parent settings of the thread
900 // This shouldn't happen anymore. This is supposed to be absolote.
901 if ($arr["uri"] == $first_id) {
902 logger('setting new parent to id '.$newitem);
903 $new_parents = q("SELECT `id`, `uri`, `contact-id`, `type`, `verb`, `visible` FROM `item` WHERE `uid` = %d AND `id` = %d LIMIT 1",
904 intval($uid), intval($newitem));
906 $parent = $new_parents[0];
910 if (($item_stored < 0) AND (count($item) > 0)) {
911 //$arr["app"] .= " (OStatus-NoConvFound)";
912 $item_stored = item_store($item, true);
914 logger("Uri ".$item["uri"]." wasn't found in conversation ".$conversation_url, LOGGER_DEBUG);
915 ostatus_store_conversation($item_stored, $conversation_url);
919 return($item_stored);
922 function ostatus_store_conversation($itemid, $conversation_url) {
925 $conversation_url = ostatus_convert_href($conversation_url);
927 $messages = q("SELECT `uid`, `parent`, `created`, `received`, `guid` FROM `item` WHERE `id` = %d LIMIT 1", intval($itemid));
930 $message = $messages[0];
932 // Store conversation url if not done before
933 $conversation = q("SELECT `url` FROM `term` WHERE `uid` = %d AND `oid` = %d AND `otype` = %d AND `type` = %d",
934 intval($message["uid"]), intval($itemid), intval(TERM_OBJ_POST), intval(TERM_CONVERSATION));
936 if (!$conversation) {
937 $r = q("INSERT INTO `term` (`uid`, `oid`, `otype`, `type`, `term`, `url`, `created`, `received`, `guid`) VALUES (%d, %d, %d, %d, '%s', '%s', '%s', '%s', '%s')",
938 intval($message["uid"]), intval($itemid), intval(TERM_OBJ_POST), intval(TERM_CONVERSATION),
939 dbesc($message["created"]), dbesc($conversation_url), dbesc($message["created"]), dbesc($message["received"]), dbesc($message["guid"]));
940 logger('Storing conversation url '.$conversation_url.' for id '.$itemid);