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;
203 if ($item["verb"] == ACTIVITY_JOIN) {
204 // ignore "Join" messages
208 if ($item["verb"] == ACTIVITY_FOLLOW) {
209 // ignore "Follow" messages
213 if ($item["verb"] == ACTIVITY_FAVORITE) {
214 // ignore "Favorite" messages
218 $item["created"] = $xpath->query('atom:published/text()', $entry)->item(0)->nodeValue;
219 $item["edited"] = $xpath->query('atom:updated/text()', $entry)->item(0)->nodeValue;
220 $conversation = $xpath->query('ostatus:conversation/text()', $entry)->item(0)->nodeValue;
224 $inreplyto = $xpath->query('thr:in-reply-to', $entry);
225 if (is_object($inreplyto->item(0))) {
226 foreach($inreplyto->item(0)->attributes AS $attributes) {
227 if ($attributes->name == "ref")
228 $item["parent-uri"] = $attributes->textContent;
229 if ($attributes->name == "href")
230 $related = $attributes->textContent;
234 $georsspoint = $xpath->query('georss:point', $entry);
236 $item["coord"] = $georsspoint->item(0)->nodeValue;
239 // $item["location"] =
241 $categories = $xpath->query('atom:category', $entry);
243 foreach ($categories AS $category) {
244 foreach($category->attributes AS $attributes)
245 if ($attributes->name == "term") {
246 $term = $attributes->textContent;
247 if(strlen($item["tag"]))
249 $item["tag"] .= "#[url=".$a->get_baseurl()."/search?tag=".$term."]".$term."[/url]";
257 $links = $xpath->query('atom:link', $entry);
264 foreach ($links AS $link) {
265 foreach($link->attributes AS $attributes) {
266 if ($attributes->name == "href")
267 $href = $attributes->textContent;
268 if ($attributes->name == "rel")
269 $rel = $attributes->textContent;
270 if ($attributes->name == "type")
271 $type = $attributes->textContent;
272 if ($attributes->name == "length")
273 $length = $attributes->textContent;
274 if ($attributes->name == "title")
275 $title = $attributes->textContent;
277 if (($rel != "") AND ($href != ""))
280 $item["plink"] = $href;
281 if (($item["object-type"] == ACTIVITY_OBJ_QUESTION) OR
282 ($item["object-type"] == ACTIVITY_OBJ_EVENT))
283 $item["body"] .= add_page_info($href);
285 case "ostatus:conversation":
286 $conversation = $href;
290 if(strlen($item["attach"]))
291 $item["attach"] .= ',';
293 $item["attach"] .= '[attach]href="'.$href.'" length="'.$length.'" type="'.$type.'" title="'.$title.'"[/attach]';
296 if ($item["object-type"] != ACTIVITY_OBJ_BOOKMARK) {
297 if (!isset($item["parent-uri"]))
298 $item["parent-uri"] = $href;
303 $item["body"] .= add_page_info($href);
309 // Notification check
310 if ($importer["nurl"] == normalise_link($href))
320 $notice_info = $xpath->query('statusnet:notice_info', $entry);
321 if ($notice_info AND ($notice_info->length > 0)) {
322 foreach($notice_info->item(0)->attributes AS $attributes) {
323 if ($attributes->name == "source")
324 $item["app"] = strip_tags($attributes->textContent);
325 if ($attributes->name == "local_id")
326 $local_id = $attributes->textContent;
327 if ($attributes->name == "repeat_of")
328 $repeat_of = $attributes->textContent;
332 // Is it a repeated post?
333 if ($repeat_of != "") {
334 $activityobjects = $xpath->query('activity:object', $entry)->item(0);
336 if (is_object($activityobjects)) {
338 $orig_uri = $xpath->query("activity:object/atom:id", $activityobjects)->item(0)->nodeValue;
339 if (!isset($orig_uri))
340 $orig_uri = $xpath->query('atom:id/text()', $activityobjects)->item(0)->nodeValue;
342 $orig_links = $xpath->query("activity:object/atom:link[@rel='alternate']", $activityobjects);
343 if ($orig_links AND ($orig_links->length > 0))
344 foreach($orig_links->item(0)->attributes AS $attributes)
345 if ($attributes->name == "href")
346 $orig_link = $attributes->textContent;
348 if (!isset($orig_link))
349 $orig_link = $xpath->query("atom:link[@rel='alternate']", $activityobjects)->item(0)->nodeValue;
351 if (!isset($orig_link))
352 $orig_link = ostatus_convert_href($orig_uri);
354 $orig_body = $xpath->query('activity:object/atom:content/text()', $activityobjects)->item(0)->nodeValue;
355 if (!isset($orig_body))
356 $orig_body = $xpath->query('atom:content/text()', $activityobjects)->item(0)->nodeValue;
358 $orig_created = $xpath->query('atom:published/text()', $activityobjects)->item(0)->nodeValue;
360 $orig_contact = $contact;
361 $orig_author = ostatus_fetchauthor($xpath, $activityobjects, $importer, $orig_contact);
363 //if (!intval(get_config('system','wall-to-wall_share'))) {
364 // $prefix = share_header($orig_author['author-name'], $orig_author['author-link'], $orig_author['author-avatar'], "", $orig_created, $orig_link);
365 // $item["body"] = $prefix.add_page_info_to_body(html2bbcode($orig_body))."[/share]";
367 $item["author-name"] = $orig_author["author-name"];
368 $item["author-link"] = $orig_author["author-link"];
369 $item["author-avatar"] = $orig_author["author-avatar"];
370 $item["body"] = add_page_info_to_body(html2bbcode($orig_body));
371 $item["created"] = $orig_created;
373 $item["uri"] = $orig_uri;
374 $item["plink"] = $orig_link;
377 $item["verb"] = $xpath->query('activity:verb/text()', $activityobjects)->item(0)->nodeValue;
379 $item["object-type"] = $xpath->query('activity:object/activity:object-type/text()', $activityobjects)->item(0)->nodeValue;
380 if (!isset($item["object-type"]))
381 $item["object-type"] = $xpath->query('activity:object-type/text()', $activityobjects)->item(0)->nodeValue;
385 //if ($enclosure != "")
386 // $item["body"] .= add_page_info($enclosure);
388 if (isset($item["parent-uri"])) {
389 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s'",
390 intval($importer["uid"]), dbesc($item["parent-uri"]));
392 if (!$r AND ($related != "")) {
393 $reply_path = str_replace("/notice/", "/api/statuses/show/", $related).".atom";
395 if ($reply_path != $related) {
396 logger("Fetching related items for user ".$importer["uid"]." from ".$reply_path, LOGGER_DEBUG);
397 $reply_xml = fetch_url($reply_path);
399 $reply_contact = $contact;
400 ostatus_import($reply_xml,$importer,$reply_contact, $reply_hub);
402 // After the import try to fetch the parent item again
403 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s'",
404 intval($importer["uid"]), dbesc($item["parent-uri"]));
408 $item["type"] = 'remote-comment';
409 $item["gravity"] = GRAVITY_COMMENT;
412 $item["parent-uri"] = $item["uri"];
414 $item_id = ostatus_completion($conversation, $importer["uid"], $item);
417 logger("Error storing item", LOGGER_DEBUG);
421 logger("Item was stored with id ".$item_id, LOGGER_DEBUG);
422 $item["id"] = $item_id;
424 if (!isset($item["parent"]) OR ($item["parent"] == 0))
425 $item["parent"] = $item_id;
428 $u = q("SELECT `notify-flags`, `language`, `username`, `email` FROM user WHERE uid = %d LIMIT 1", intval($item['uid']));
431 'type' => NOTIFY_TAGSELF,
432 'notify_flags' => $u[0]["notify-flags"],
433 'language' => $u[0]["language"],
434 'to_name' => $u[0]["username"],
435 'to_email' => $u[0]["email"],
436 'uid' => $item["uid"],
438 'link' => $a->get_baseurl().'/display/'.urlencode(get_item_guid($item["id"])),
439 'source_name' => $item["author-name"],
440 'source_link' => $item["author-link"],
441 'source_photo' => $item["author-avatar"],
442 'verb' => ACTIVITY_TAG,
444 'parent' => $item["parent"]
450 function ostatus_convert_href($href) {
451 $elements = explode(":",$href);
453 if ((count($elements) <= 2) OR ($elements[0] != "tag"))
456 $server = explode(",", $elements[1]);
457 $conversation = explode("=", $elements[2]);
459 if ((count($elements) == 4) AND ($elements[2] == "post"))
460 return "http://".$server[0]."/notice/".$elements[3];
462 if ((count($conversation) != 2) OR ($conversation[1] ==""))
465 if ($elements[3] == "objectType=thread")
466 return "http://".$server[0]."/conversation/".$conversation[1];
468 return "http://".$server[0]."/notice/".$conversation[1];
473 function check_conversations($override = false) {
474 $last = get_config('system','ostatus_last_poll');
476 $poll_interval = intval(get_config('system','ostatus_poll_interval'));
478 $poll_interval = OSTATUS_DEFAULT_POLL_INTERVAL;
480 // Don't poll if the interval is set negative
481 if (($poll_interval < 0) AND !$override)
484 $poll_timeframe = intval(get_config('system','ostatus_poll_timeframe'));
485 if (!$poll_timeframe)
486 $poll_timeframe = OSTATUS_DEFAULT_POLL_TIMEFRAME;
488 if ($last AND !$override) {
489 $next = $last + ($poll_interval * 60);
490 if ($next > time()) {
491 logger('poll interval not reached');
496 logger('cron_start');
498 $start = date("Y-m-d H:i:s", time() - ($poll_timeframe * 60));
499 $conversations = q("SELECT `oid`, `url`, `uid` FROM `term` WHERE `type` = 7 AND `term` > '%s' GROUP BY `url`, `uid` ORDER BY `term` DESC",
502 foreach ($conversations AS $conversation) {
503 ostatus_completion($conversation['url'], $conversation['uid']);
508 set_config('system','ostatus_last_poll', time());
511 function ostatus_completion($conversation_url, $uid, $item = array()) {
515 $conversation_url = ostatus_convert_href($conversation_url);
517 // If the thread shouldn't be completed then store the item and go away
518 if ((intval(get_config('system','ostatus_poll_interval')) == -2) AND (count($item) > 0)) {
519 //$arr["app"] .= " (OStatus-NoCompletion)";
520 $item_stored = item_store($item, true);
521 return($item_stored);
525 $parents = q("SELECT `id`, `parent`, `uri`, `contact-id`, `type`, `verb`, `visible` FROM `item` WHERE `id` IN
526 (SELECT `parent` FROM `item` WHERE `id` IN
527 (SELECT `oid` FROM `term` WHERE `uid` = %d AND `otype` = %d AND `type` = %d AND `url` = '%s'))",
528 intval($uid), intval(TERM_OBJ_POST), intval(TERM_CONVERSATION), dbesc($conversation_url));
531 $parent = $parents[0];
532 elseif (count($item) > 0) {
534 $parent["type"] = "remote";
535 $parent["verb"] = ACTIVITY_POST;
536 $parent["visible"] = 1;
539 $r = q("SELECT `id` FROM `contact` WHERE `self` AND `uid`=%d", $uid);
545 $parent["parent"] = 0;
547 $parent["contact-id"] = $r[0]["id"];
548 $parent["type"] = "remote";
549 $parent["verb"] = ACTIVITY_POST;
550 $parent["visible"] = 1;
553 $conv = str_replace("/conversation/", "/api/statusnet/conversation/", $conversation_url).".as";
557 logger('fetching conversation url '.$conv.' for user '.$uid);
560 $conv_arr = z_fetch_url($conv."?page=".$pageno);
562 // If it is a non-ssl site and there is an error, then try ssl or vice versa
563 if (!$conv_arr["success"] AND (substr($conv, 0, 7) == "http://")) {
564 $conv = str_replace("http://", "https://", $conv);
565 $conv_as = fetch_url($conv."?page=".$pageno);
566 } elseif (!$conv_arr["success"] AND (substr($conv, 0, 8) == "https://")) {
567 $conv = str_replace("https://", "http://", $conv);
568 $conv_as = fetch_url($conv."?page=".$pageno);
570 $conv_as = $conv_arr["body"];
572 $conv_as = str_replace(',"statusnet:notice_info":', ',"statusnet_notice_info":', $conv_as);
573 $conv_as = json_decode($conv_as);
575 if (@is_array($conv_as->items))
576 $items = array_merge($items, $conv_as->items);
584 logger('fetching conversation done. Found '.count($items).' items');
586 if (!sizeof($items)) {
587 if (count($item) > 0) {
588 //$arr["app"] .= " (OStatus-NoConvFetched)";
589 $item_stored = item_store($item, true);
592 logger("Conversation ".$conversation_url." couldn't be fetched. Item uri ".$item["uri"]." stored: ".$item_stored, LOGGER_DEBUG);
593 ostatus_store_conversation($item_id, $conversation_url);
596 return($item_stored);
601 $items = array_reverse($items);
603 foreach ($items as $single_conv) {
605 // Test - remove before flight
606 //$tempfile = tempnam(get_temppath(), "conversation");
607 //file_put_contents($tempfile, json_encode($single_conv));
610 if (isset($single_conv->object->id))
611 $single_conv->id = $single_conv->object->id;
613 $plink = ostatus_convert_href($single_conv->id);
614 if (isset($single_conv->object->url))
615 $plink = ostatus_convert_href($single_conv->object->url);
617 if (@!$single_conv->id)
620 logger("Got id ".$single_conv->id, LOGGER_DEBUG);
622 if ($first_id == "") {
623 $first_id = $single_conv->id;
625 // The first post of the conversation isn't our first post. There are three options:
626 // 1. Our conversation hasn't the "real" thread starter
627 // 2. This first post is a post inside our thread
628 // 3. This first post is a post inside another thread
629 if (($first_id != $parent["uri"]) AND ($parent["uri"] != "")) {
630 $new_parents = q("SELECT `id`, `parent`, `uri`, `contact-id`, `type`, `verb`, `visible` FROM `item` WHERE `id` IN
631 (SELECT `parent` FROM `item`
632 WHERE `uid` = %d AND `uri` = '%s' AND `network` IN ('%s','%s')) LIMIT 1",
633 intval($uid), dbesc($first_id), dbesc(NETWORK_OSTATUS), dbesc(NETWORK_DFRN));
635 if ($new_parents[0]["parent"] == $parent["parent"]) {
636 // Option 2: This post is already present inside our thread - but not as thread starter
637 logger("Option 2: uri present in our thread: ".$first_id, LOGGER_DEBUG);
638 $first_id = $parent["uri"];
640 // Option 3: Not so good. We have mixed parents. We have to see how to clean this up.
641 // For now just take the new parent.
642 $parent = $new_parents[0];
643 $first_id = $parent["uri"];
644 logger("Option 3: mixed parents for uri ".$first_id, LOGGER_DEBUG);
647 // Option 1: We hadn't got the real thread starter
648 // We have to clean up our existing messages.
650 $parent["uri"] = $first_id;
651 logger("Option 1: we have a new parent: ".$first_id, LOGGER_DEBUG);
653 } elseif ($parent["uri"] == "") {
655 $parent["uri"] = $first_id;
659 $parent_uri = $parent["uri"];
661 // "context" only seems to exist on older servers
662 if (isset($single_conv->context->inReplyTo->id)) {
663 $parent_exists = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `network` IN ('%s','%s') LIMIT 1",
664 intval($uid), dbesc($single_conv->context->inReplyTo->id), dbesc(NETWORK_OSTATUS), dbesc(NETWORK_DFRN));
666 $parent_uri = $single_conv->context->inReplyTo->id;
669 // This is the current way
670 if (isset($single_conv->object->inReplyTo->id)) {
671 $parent_exists = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `network` IN ('%s','%s') LIMIT 1",
672 intval($uid), dbesc($single_conv->object->inReplyTo->id), dbesc(NETWORK_OSTATUS), dbesc(NETWORK_DFRN));
674 $parent_uri = $single_conv->object->inReplyTo->id;
677 $message_exists = q("SELECT `id`, `parent`, `uri` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `network` IN ('%s','%s') LIMIT 1",
678 intval($uid), dbesc($single_conv->id),
679 dbesc(NETWORK_OSTATUS), dbesc(NETWORK_DFRN));
680 if ($message_exists) {
681 logger("Message ".$single_conv->id." already existed on the system", LOGGER_DEBUG);
683 if ($parent["id"] != 0) {
684 $existing_message = $message_exists[0];
686 // We improved the way we fetch OStatus messages, this shouldn't happen very often now
687 // To-Do: we have to change the shadow copies as well. This way here is really ugly.
688 if ($existing_message["parent"] != $parent["id"]) {
689 logger('updating id '.$existing_message["id"].' with parent '.$existing_message["parent"].' to parent '.$parent["id"].' uri '.$parent["uri"].' thread '.$parent_uri, LOGGER_DEBUG);
691 // Update the parent id of the selected item
692 $r = q("UPDATE `item` SET `parent` = %d, `parent-uri` = '%s' WHERE `id` = %d",
693 intval($parent["id"]), dbesc($parent["uri"]), intval($existing_message["id"]));
695 // Update the parent uri in the thread - but only if it points to itself
696 $r = q("UPDATE `item` SET `thr-parent` = '%s' WHERE `id` = %d AND `uri` = `thr-parent`",
697 dbesc($parent_uri), intval($existing_message["id"]));
699 // try to change all items of the same parent
700 $r = q("UPDATE `item` SET `parent` = %d, `parent-uri` = '%s' WHERE `parent` = %d",
701 intval($parent["id"]), dbesc($parent["uri"]), intval($existing_message["parent"]));
703 // Update the parent uri in the thread - but only if it points to itself
704 $r = q("UPDATE `item` SET `thr-parent` = '%s' WHERE (`parent` = %d) AND (`uri` = `thr-parent`)",
705 dbesc($parent["uri"]), intval($existing_message["parent"]));
707 // Now delete the thread
708 delete_thread($existing_message["parent"]);
712 // The item we are having on the system is the one that we wanted to store via the item array
713 if (isset($item["uri"]) AND ($item["uri"] == $existing_message["uri"])) {
721 $actor = $single_conv->actor->id;
722 if (isset($single_conv->actor->url))
723 $actor = $single_conv->actor->url;
725 $contact = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `nurl` = '%s' AND `network` != '%s'",
726 $uid, normalise_link($actor), NETWORK_STATUSNET);
728 if (count($contact)) {
729 logger("Found contact for url ".$actor, LOGGER_DEBUG);
730 $contact_id = $contact[0]["id"];
732 logger("No contact found for url ".$actor, LOGGER_DEBUG);
734 // Adding a global contact
735 // To-Do: Use this data for the post
736 $global_contact_id = get_contact($actor, 0);
738 logger("Global contact ".$global_contact_id." found for url ".$actor, LOGGER_DEBUG);
740 $contact_id = $parent["contact-id"];
744 $arr["network"] = NETWORK_OSTATUS;
745 $arr["uri"] = $single_conv->id;
746 $arr["plink"] = $plink;
748 $arr["contact-id"] = $contact_id;
749 $arr["parent-uri"] = $parent_uri;
750 $arr["created"] = $single_conv->published;
751 $arr["edited"] = $single_conv->published;
752 $arr["owner-name"] = $single_conv->actor->displayName;
753 if ($arr["owner-name"] == '')
754 $arr["owner-name"] = $single_conv->actor->contact->displayName;
755 if ($arr["owner-name"] == '')
756 $arr["owner-name"] = $single_conv->actor->portablecontacts_net->displayName;
758 $arr["owner-link"] = $actor;
759 $arr["owner-avatar"] = $single_conv->actor->image->url;
760 $arr["author-name"] = $arr["owner-name"];
761 $arr["author-link"] = $actor;
762 $arr["author-avatar"] = $single_conv->actor->image->url;
763 $arr["body"] = add_page_info_to_body(html2bbcode($single_conv->content));
765 if (isset($single_conv->status_net->notice_info->source))
766 $arr["app"] = strip_tags($single_conv->status_net->notice_info->source);
767 elseif (isset($single_conv->statusnet->notice_info->source))
768 $arr["app"] = strip_tags($single_conv->statusnet->notice_info->source);
769 elseif (isset($single_conv->statusnet_notice_info->source))
770 $arr["app"] = strip_tags($single_conv->statusnet_notice_info->source);
771 elseif (isset($single_conv->provider->displayName))
772 $arr["app"] = $single_conv->provider->displayName;
774 $arr["app"] = "OStatus";
776 //$arr["app"] .= " (Conversation)";
778 $arr["object"] = json_encode($single_conv);
779 $arr["verb"] = $parent["verb"];
780 $arr["visible"] = $parent["visible"];
781 $arr["location"] = $single_conv->location->displayName;
782 $arr["coord"] = trim($single_conv->location->lat." ".$single_conv->location->lon);
784 // Is it a reshared item?
785 if (isset($single_conv->verb) AND ($single_conv->verb == "share") AND isset($single_conv->object)) {
786 if (is_array($single_conv->object))
787 $single_conv->object = $single_conv->object[0];
789 logger("Found reshared item ".$single_conv->object->id);
791 // $single_conv->object->context->conversation;
793 if (isset($single_conv->object->object->id))
794 $arr["uri"] = $single_conv->object->object->id;
796 $arr["uri"] = $single_conv->object->id;
798 if (isset($single_conv->object->object->url))
799 $plink = ostatus_convert_href($single_conv->object->object->url);
801 $plink = ostatus_convert_href($single_conv->object->url);
803 if (isset($single_conv->object->object->content))
804 $arr["body"] = add_page_info_to_body(html2bbcode($single_conv->object->object->content));
806 $arr["body"] = add_page_info_to_body(html2bbcode($single_conv->object->content));
808 $arr["plink"] = $plink;
810 $arr["created"] = $single_conv->object->published;
811 $arr["edited"] = $single_conv->object->published;
813 $arr["author-name"] = $single_conv->object->actor->displayName;
814 if ($arr["owner-name"] == '')
815 $arr["author-name"] = $single_conv->object->actor->contact->displayName;
817 $arr["author-link"] = $single_conv->object->actor->url;
818 $arr["author-avatar"] = $single_conv->object->actor->image->url;
820 $arr["app"] = $single_conv->object->provider->displayName."#";
821 //$arr["verb"] = $single_conv->object->verb;
823 $arr["location"] = $single_conv->object->location->displayName;
824 $arr["coord"] = trim($single_conv->object->location->lat." ".$single_conv->object->location->lon);
827 if ($arr["location"] == "")
828 unset($arr["location"]);
830 if ($arr["coord"] == "")
831 unset($arr["coord"]);
833 // Copy fields from given item array
834 if (isset($item["uri"]) AND (($item["uri"] == $arr["uri"]) OR ($item["uri"] == $single_conv->id))) {
835 $copy_fields = array("owner-name", "owner-link", "owner-avatar", "author-name", "author-link", "author-avatar",
836 "gravity", "body", "object-type", "object", "verb", "created", "edited", "coord", "tag",
837 "title", "attach", "app", "type", "location", "contact-id", "uri");
838 foreach ($copy_fields AS $field)
839 if (isset($item[$field]))
840 $arr[$field] = $item[$field];
842 //$arr["app"] .= " (OStatus)";
845 $newitem = item_store($arr);
847 logger("Item wasn't stored ".print_r($arr, true), LOGGER_DEBUG);
851 if (isset($item["uri"]) AND ($item["uri"] == $arr["uri"])) {
853 $item_stored = $newitem;
856 logger('Stored new item '.$plink.' for parent '.$arr["parent-uri"].' under id '.$newitem, LOGGER_DEBUG);
858 // Add the conversation entry (but don't fetch the whole conversation)
859 ostatus_store_conversation($newitem, $conversation_url);
861 // If the newly created item is the top item then change the parent settings of the thread
862 // This shouldn't happen anymore. This is supposed to be absolote.
863 if ($arr["uri"] == $first_id) {
864 logger('setting new parent to id '.$newitem);
865 $new_parents = q("SELECT `id`, `uri`, `contact-id`, `type`, `verb`, `visible` FROM `item` WHERE `uid` = %d AND `id` = %d LIMIT 1",
866 intval($uid), intval($newitem));
868 $parent = $new_parents[0];
872 if (($item_stored < 0) AND (count($item) > 0)) {
873 //$arr["app"] .= " (OStatus-NoConvFound)";
874 $item_stored = item_store($item, true);
876 logger("Uri ".$item["uri"]." wasn't found in conversation ".$conversation_url, LOGGER_DEBUG);
877 ostatus_store_conversation($item_stored, $conversation_url);
881 return($item_stored);
884 function ostatus_store_conversation($itemid, $conversation_url) {
887 $conversation_url = ostatus_convert_href($conversation_url);
889 $messages = q("SELECT `uid`, `parent`, `created`, `received`, `guid` FROM `item` WHERE `id` = %d LIMIT 1", intval($itemid));
892 $message = $messages[0];
894 // Store conversation url if not done before
895 $conversation = q("SELECT `url` FROM `term` WHERE `uid` = %d AND `oid` = %d AND `otype` = %d AND `type` = %d",
896 intval($message["uid"]), intval($itemid), intval(TERM_OBJ_POST), intval(TERM_CONVERSATION));
898 if (!$conversation) {
899 $r = q("INSERT INTO `term` (`uid`, `oid`, `otype`, `type`, `term`, `url`, `created`, `received`, `guid`) VALUES (%d, %d, %d, %d, '%s', '%s', '%s', '%s', '%s')",
900 intval($message["uid"]), intval($itemid), intval(TERM_OBJ_POST), intval(TERM_CONVERSATION),
901 dbesc($message["created"]), dbesc($conversation_url), dbesc($message["created"]), dbesc($message["received"]), dbesc($message["guid"]));
902 logger('Storing conversation url '.$conversation_url.' for id '.$itemid);