]> git.mxchange.org Git - friendica.git/blob - include/ostatus.php
80a67f201c1617d2fa8dd1a53a2c6e344f311445
[friendica.git] / include / ostatus.php
1 <?php
2 require_once("include/Contact.php");
3 require_once("include/threads.php");
4 require_once("include/html2bbcode.php");
5 require_once("include/items.php");
6 require_once("mod/share.php");
7 require_once("include/enotify.php");
8 require_once("include/socgraph.php");
9 require_once("include/Photo.php");
10
11 define('OSTATUS_DEFAULT_POLL_INTERVAL', 30); // given in minutes
12 define('OSTATUS_DEFAULT_POLL_TIMEFRAME', 1440); // given in minutes
13
14 function ostatus_fetchauthor($xpath, $context, $importer, &$contact) {
15
16         $author = array();
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;
19
20         // Preserve the value
21         $authorlink = $author["author-link"];
22
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;
28
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));
32         if ($r) {
33                 $contact = $r[0];
34                 $author["contact-id"] = $r[0]["id"];
35         } else
36                 $author["contact-id"] = $contact["id"];
37
38         $avatarlist = array();
39         $avatars = $xpath->query("atom:author/atom:link[@rel='avatar']", $context);
40         foreach($avatars AS $avatar) {
41                 $href = "";
42                 $width = 0;
43                 foreach($avatar->attributes AS $attributes) {
44                         if ($attributes->name == "href")
45                                 $href = $attributes->textContent;
46                         if ($attributes->name == "width")
47                                 $width = $attributes->textContent;
48                 }
49                 if (($width > 0) AND ($href != ""))
50                         $avatarlist[$width] = $href;
51         }
52         if (count($avatarlist) > 0) {
53                 krsort($avatarlist);
54                 $author["author-avatar"] = current($avatarlist);
55         }
56
57         $displayname = $xpath->evaluate('atom:author/poco:displayName/text()', $context)->item(0)->nodeValue;
58         if ($displayname != "")
59                 $author["author-name"] = $displayname;
60
61         $author["owner-name"] = $author["author-name"];
62         $author["owner-link"] = $author["author-link"];
63         $author["owner-avatar"] = $author["author-avatar"];
64
65         if ($r) {
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);
70
71                         $value = $xpath->evaluate('atom:author/poco:displayName/text()', $context)->item(0)->nodeValue;
72                         if ($value != "")
73                                 $contact["name"] = $value;
74
75                         $value = $xpath->evaluate('atom:author/poco:preferredUsername/text()', $context)->item(0)->nodeValue;
76                         if ($value != "")
77                                 $contact["nick"] = $value;
78
79                         $value = $xpath->evaluate('atom:author/poco:note/text()', $context)->item(0)->nodeValue;
80                         if ($value != "")
81                                 $contact["about"] = $value;
82
83                         $value = $xpath->evaluate('atom:author/poco:address/poco:formatted/text()', $context)->item(0)->nodeValue;
84                         if ($value != "")
85                                 $contact["location"] = $value;
86
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"]));
90
91                         poco_check($contact["url"], $contact["name"], $contact["network"], $author["author-avatar"], $contact["about"], $contact["location"],
92                                         "", "", "", datetime_convert(), 2, $contact["id"], $contact["uid"]);
93                 }
94
95                 $update_photo = ($r[0]['avatar-date'] < datetime_convert('','','now -12 hours'));
96
97                 if ($update_photo AND isset($author["author-avatar"])) {
98                         logger("Update profile picture for contact ".$contact["id"], LOGGER_DEBUG);
99
100                         $photos = import_profile_photo($author["author-avatar"], $importer["uid"], $contact["id"]);
101
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"]));
105                 }
106         }
107
108         return($author);
109 }
110
111 function ostatus_import($xml,$importer,&$contact, &$hub) {
112
113         $a = get_app();
114
115         logger("Import OStatus message", LOGGER_DEBUG);
116
117         if ($xml == "")
118                 return;
119
120         $doc = new DOMDocument();
121         @$doc->loadXML($xml);
122
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/");
132
133         $gub = "";
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);
140                         }
141
142         $header = array();
143         $header["uid"] = $importer["uid"];
144         $header["network"] = NETWORK_OSTATUS;
145         $header["type"] = "remote";
146         $header["wall"] = 0;
147         $header["origin"] = 0;
148         $header["gravity"] = GRAVITY_PARENT;
149
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;
153
154         if ($first_child == "feed")
155                 $entries = $xpath->query('/atom:feed/atom:entry');
156         else
157                 $entries = $xpath->query('/atom:entry');
158
159         $conversation = "";
160         $conversationlist = array();
161         $item_id = 0;
162
163         // Reverse the order of the entries
164         $entrylist = array();
165
166         foreach ($entries AS $entry)
167                 $entrylist[] = $entry;
168
169         foreach (array_reverse($entrylist) AS $entry) {
170
171                 $mention = false;
172
173                 // fetch the author
174                 if ($first_child == "feed")
175                         $author = ostatus_fetchauthor($xpath, $doc->firstChild, $importer, $contact);
176                 else
177                         $author = ostatus_fetchauthor($xpath, $entry, $importer, $contact);
178
179                 $item = array_merge($header, $author);
180
181                 // Now get the item
182                 $item["uri"] = $xpath->query('atom:id/text()', $entry)->item(0)->nodeValue;
183
184                 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s'",
185                         intval($importer["uid"]), dbesc($item["uri"]));
186                 if ($r) {
187                         logger("Item with uri ".$item["uri"]." for user ".$importer["uid"]." already existed under id ".$r[0]["id"], LOGGER_DEBUG);
188                         continue;
189                 }
190
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;
195
196                 if ($item["verb"] == ACTIVITY_JOIN) {
197                         // ignore "Join" messages
198                         continue;
199                 }
200
201                 if ($item["verb"] == ACTIVITY_FOLLOW) {
202                         // ignore "Follow" messages
203                         continue;
204                 }
205
206                 if ($item["verb"] == ACTIVITY_FAVORITE) {
207                         // ignore "Favorite" messages
208                         continue;
209                 }
210
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;
214
215                 $related = "";
216
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;
224                         }
225                 }
226
227                 $georsspoint = $xpath->query('georss:point', $entry);
228                 if ($georsspoint)
229                         $item["coord"] = $georsspoint->item(0)->nodeValue;
230
231                 // To-Do
232                 // $item["location"] =
233
234                 $categories = $xpath->query('atom:category', $entry);
235                 if ($categories) {
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"]))
241                                                         $item["tag"] .= ',';
242                                                 $item["tag"] .= "#[url=".$a->get_baseurl()."/search?tag=".$term."]".$term."[/url]";
243                                         }
244                         }
245                 }
246
247                 $self = "";
248                 $enclosure = "";
249
250                 $links = $xpath->query('atom:link', $entry);
251                 if ($links) {
252                         $rel = "";
253                         $href = "";
254                         $type = "";
255                         $length = "0";
256                         $title = "";
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;
269                                 }
270                                 if (($rel != "") AND ($href != ""))
271                                         switch($rel) {
272                                                 case "alternate":
273                                                         $item["plink"] = $href;
274                                                         break;
275                                                 case "ostatus:conversation":
276                                                         $conversation = $href;
277                                                         break;
278                                                 case "enclosure":
279                                                         $enclosure = $href;
280                                                         if(strlen($item["attach"]))
281                                                                 $item["attach"] .= ',';
282
283                                                         $item["attach"] .= '[attach]href="'.$href.'" length="'.$length.'" type="'.$type.'" title="'.$title.'"[/attach]';
284                                                         break;
285                                                 case "related":
286                                                         if (!isset($item["parent-uri"]))
287                                                                 $item["parent-uri"] = $href;
288
289                                                         if ($related == "")
290                                                                 $related = $href;
291                                                         break;
292                                                 case "self":
293                                                         $self = $href;
294                                                         break;
295                                                 case "mentioned":
296                                                         // Notification check
297                                                         if ($importer["nurl"] == normalise_link($href))
298                                                                 $mention = true;
299                                                         break;
300                                         }
301                         }
302                 }
303
304                 $local_id = "";
305                 $repeat_of = "";
306
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;
316                         }
317                 }
318
319                 // Is it a repeated post?
320                 if ($repeat_of != "") {
321                         $activityobjects = $xpath->query('activity:object', $entry)->item(0);
322
323                         if (is_object($activityobjects)) {
324
325                                 $orig_uri = $xpath->query("activity:object/atom:id", $activityobjects)->item(0)->nodeValue;
326                                 if (!isset($orig_uri))
327                                         $orig_uri = $xpath->query('atom:id/text()', $activityobjects)->item(0)->nodeValue;
328
329                                 $orig_links = $xpath->query("activity:object/atom:link[@rel='alternate']", $activityobjects);
330                                 if ($orig_links AND ($orig_links->length > 0))
331                                         foreach($orig_links->item(0)->attributes AS $attributes)
332                                                 if ($attributes->name == "href")
333                                                         $orig_link = $attributes->textContent;
334
335                                 if (!isset($orig_link))
336                                         $orig_link = $xpath->query("atom:link[@rel='alternate']", $activityobjects)->item(0)->nodeValue;
337
338                                 if (!isset($orig_link))
339                                         $orig_link =  ostatus_convert_href($orig_uri);
340
341                                 $orig_body = $xpath->query('activity:object/atom:content/text()', $activityobjects)->item(0)->nodeValue;
342                                 if (!isset($orig_body))
343                                         $orig_body = $xpath->query('atom:content/text()', $activityobjects)->item(0)->nodeValue;
344
345                                 $orig_created = $xpath->query('atom:published/text()', $activityobjects)->item(0)->nodeValue;
346
347                                 $orig_contact = $contact;
348                                 $orig_author = ostatus_fetchauthor($xpath, $activityobjects, $importer, $orig_contact);
349
350                                 //if (!intval(get_config('system','wall-to-wall_share'))) {
351                                 //      $prefix = share_header($orig_author['author-name'], $orig_author['author-link'], $orig_author['author-avatar'], "", $orig_created, $orig_link);
352                                 //      $item["body"] = $prefix.add_page_info_to_body(html2bbcode($orig_body))."[/share]";
353                                 //} else {
354                                         $item["author-name"] = $orig_author["author-name"];
355                                         $item["author-link"] = $orig_author["author-link"];
356                                         $item["author-avatar"] = $orig_author["author-avatar"];
357                                         $item["body"] = add_page_info_to_body(html2bbcode($orig_body));
358                                         $item["created"] = $orig_created;
359
360                                         $item["uri"] = $orig_uri;
361                                         $item["plink"] = $orig_link;
362                                 //}
363
364                                 $item["verb"] = $xpath->query('activity:verb/text()', $activityobjects)->item(0)->nodeValue;
365
366                                 $item["object-type"] = $xpath->query('activity:object/activity:object-type/text()', $activityobjects)->item(0)->nodeValue;
367                                 if (!isset($item["object-type"]))
368                                         $item["object-type"] = $xpath->query('activity:object-type/text()', $activityobjects)->item(0)->nodeValue;
369                         }
370                 }
371
372                 //if ($enclosure != "")
373                 //      $item["body"] .= add_page_info($enclosure);
374
375                 if (isset($item["parent-uri"])) {
376                         $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s'",
377                                 intval($importer["uid"]), dbesc($item["parent-uri"]));
378
379                         if (!$r AND ($related != "")) {
380                                 $reply_path = str_replace("/notice/", "/api/statuses/show/", $related).".atom";
381
382                                 if ($reply_path != $related) {
383                                         logger("Fetching related items for user ".$importer["uid"]." from ".$reply_path, LOGGER_DEBUG);
384                                         $reply_xml = fetch_url($reply_path);
385
386                                         $reply_contact = $contact;
387                                         ostatus_import($reply_xml,$importer,$reply_contact, $reply_hub);
388
389                                         // After the import try to fetch the parent item again
390                                         $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s'",
391                                                 intval($importer["uid"]), dbesc($item["parent-uri"]));
392                                 }
393                         }
394                         if ($r) {
395                                 $item["type"] = 'remote-comment';
396                                 $item["gravity"] = GRAVITY_COMMENT;
397                         }
398                 } else
399                         $item["parent-uri"] = $item["uri"];
400
401                 $item_id = ostatus_completion($conversation, $importer["uid"], $item);
402
403                 if ($item_id <= 0) {
404                         $reason = $item_id;
405                         $item["app"] .= $item_id;
406                         $item_id = item_store($item, true);
407                         if ($item_id) {
408                                 logger("Uri ".$item["uri"]." wasn't found in conversation ".$conversation, LOGGER_DEBUG);
409                                 ostatus_store_conversation($item_id, $conversation_url);
410                         }
411                 }
412                 //echo $xml;
413                 //print_r($item);
414
415                 if (!$item_id) {
416                         logger("Error storing item ".print_r($item, true), LOGGER_DEBUG);
417                         continue;
418                 }
419
420                 logger("Item was stored with id ".$item_id, LOGGER_DEBUG);
421                 $item["id"] = $item_id;
422
423                 if (!isset($item["parent"]) OR ($item["parent"] == 0))
424                         $item["parent"] = $item_id;
425
426                 if ($mention) {
427                         $u = q("SELECT `notify-flags`, `language`, `username`, `email` FROM user WHERE uid = %d LIMIT 1", intval($item['uid']));
428
429                         notification(array(
430                                 'type'         => NOTIFY_TAGSELF,
431                                 'notify_flags' => $u[0]["notify-flags"],
432                                 'language'     => $u[0]["language"],
433                                 'to_name'      => $u[0]["username"],
434                                 'to_email'     => $u[0]["email"],
435                                 'uid'          => $item["uid"],
436                                 'item'         => $item,
437                                 'link'         => $a->get_baseurl().'/display/'.urlencode(get_item_guid($item["id"])),
438                                 'source_name'  => $item["author-name"],
439                                 'source_link'  => $item["author-link"],
440                                 'source_photo' => $item["author-avatar"],
441                                 'verb'         => ACTIVITY_TAG,
442                                 'otype'        => 'item',
443                                 'parent'       => $item["parent"]
444                         ));
445                 }
446         }
447 }
448
449 function ostatus_convert_href($href) {
450         $elements = explode(":",$href);
451
452         if ((count($elements) <= 2) OR ($elements[0] != "tag"))
453                 return $href;
454
455         $server = explode(",", $elements[1]);
456         $conversation = explode("=", $elements[2]);
457
458         if ((count($elements) == 4) AND ($elements[2] == "post"))
459                 return "http://".$server[0]."/notice/".$elements[3];
460
461         if ((count($conversation) != 2) OR ($conversation[1] ==""))
462                 return $href;
463
464         if ($elements[3] == "objectType=thread")
465                 return "http://".$server[0]."/conversation/".$conversation[1];
466         else
467                 return "http://".$server[0]."/notice/".$conversation[1];
468
469         return $href;
470 }
471
472 function check_conversations($override = false) {
473         $last = get_config('system','ostatus_last_poll');
474
475         $poll_interval = intval(get_config('system','ostatus_poll_interval'));
476         if(! $poll_interval)
477                 $poll_interval = OSTATUS_DEFAULT_POLL_INTERVAL;
478
479         // Don't poll if the interval is set negative
480         if (($poll_interval < 0) AND !$override)
481                 return;
482
483         $poll_timeframe = intval(get_config('system','ostatus_poll_timeframe'));
484         if (!$poll_timeframe)
485                 $poll_timeframe = OSTATUS_DEFAULT_POLL_TIMEFRAME;
486
487         if ($last AND !$override) {
488                 $next = $last + ($poll_interval * 60);
489                 if ($next > time()) {
490                         logger('poll interval not reached');
491                         return;
492                 }
493         }
494
495         logger('cron_start');
496
497         $start = date("Y-m-d H:i:s", time() - ($poll_timeframe * 60));
498         $conversations = q("SELECT `oid`, `url`, `uid` FROM `term` WHERE `type` = 7 AND `term` > '%s' GROUP BY `url`, `uid` ORDER BY `term` DESC",
499                                 dbesc($start));
500
501         foreach ($conversations AS $conversation) {
502                 ostatus_completion($conversation['url'], $conversation['uid']);
503         }
504
505         logger('cron_end');
506
507         set_config('system','ostatus_last_poll', time());
508 }
509
510 function ostatus_completion($conversation_url, $uid, $item = array()) {
511
512         $item_stored = -3;
513
514         $conversation_url = ostatus_convert_href($conversation_url);
515
516         // If the thread shouldn't be completed then store the item and go away
517         if ((intval(get_config('system','ostatus_poll_interval')) == -2) AND (count($item) > 0)) {
518                 $item_stored = item_store($item, true);
519                 return($item_stored);
520         }
521
522         // Get the parent
523         $parents = q("SELECT `id`, `parent`, `uri`, `contact-id`, `type`, `verb`, `visible` FROM `item` WHERE `id` IN
524                         (SELECT `parent` FROM `item` WHERE `id` IN
525                                 (SELECT `oid` FROM `term` WHERE `uid` = %d AND `otype` = %d AND `type` = %d AND `url` = '%s'))",
526                         intval($uid), intval(TERM_OBJ_POST), intval(TERM_CONVERSATION), dbesc($conversation_url));
527
528         if ($parents)
529                 $parent = $parents[0];
530         elseif (count($item) > 0) {
531                 $parent = $item;
532                 $parent["type"] = "remote";
533                 $parent["verb"] = ACTIVITY_POST;
534                 $parent["visible"] = 1;
535         } else {
536                 // Preset the parent
537                 $r = q("SELECT `id` FROM `contact` WHERE `self` AND `uid`=%d", $uid);
538                 if (!$r)
539                         return(-1);
540
541                 $parent = array();
542                 $parent["id"] = 0;
543                 $parent["parent"] = 0;
544                 $parent["uri"] = "";
545                 $parent["contact-id"] = $r[0]["id"];
546                 $parent["type"] = "remote";
547                 $parent["verb"] = ACTIVITY_POST;
548                 $parent["visible"] = 1;
549         }
550
551         $conv = str_replace("/conversation/", "/api/statusnet/conversation/", $conversation_url).".as";
552         $pageno = 1;
553         $items = array();
554
555         logger('fetching conversation url '.$conv.' for user '.$uid);
556
557         do {
558                 $conv_arr = z_fetch_url($conv."?page=".$pageno);
559
560                 // If it is a non-ssl site and there is an error, then try ssl or vice versa
561                 if (!$conv_arr["success"] AND (substr($conv, 0, 7) == "http://")) {
562                         $conv = str_replace("http://", "https://", $conv);
563                         $conv_as = fetch_url($conv."?page=".$pageno);
564                 } elseif (!$conv_arr["success"] AND (substr($conv, 0, 8) == "https://")) {
565                         $conv = str_replace("https://", "http://", $conv);
566                         $conv_as = fetch_url($conv."?page=".$pageno);
567                 } else
568                         $conv_as = $conv_arr["body"];
569
570                 $conv_as = str_replace(',"statusnet:notice_info":', ',"statusnet_notice_info":', $conv_as);
571                 $conv_as = json_decode($conv_as);
572
573                 if (@is_array($conv_as->items))
574                         $items = array_merge($items, $conv_as->items);
575                 else
576                         break;
577
578                 $pageno++;
579
580         } while (true);
581
582         logger('fetching conversation done. Found '.count($items).' items');
583
584         if (!sizeof($items)) {
585                 if (count($item) > 0) {
586                         $item_stored = item_store($item, true);
587                         logger("Conversation ".$conversation_url." couldn't be fetched. Item uri ".$item["uri"]." stored: ".$item_stored, LOGGER_DEBUG);
588
589                         if ($item_stored)
590                                 ostatus_store_conversation($item_id, $conversation_url);
591
592                         return($item_stored);
593                 } else
594                         return(-2);
595         }
596
597         $items = array_reverse($items);
598
599         foreach ($items as $single_conv) {
600
601                 // Test - remove before flight
602                 //$tempfile = tempnam(get_temppath(), "conversation");
603                 //file_put_contents($tempfile, json_encode($single_conv));
604
605
606                 if (isset($single_conv->object->id))
607                         $single_conv->id = $single_conv->object->id;
608
609                 $plink = ostatus_convert_href($single_conv->id);
610                 if (isset($single_conv->object->url))
611                         $plink = ostatus_convert_href($single_conv->object->url);
612
613                 if (@!$single_conv->id)
614                         continue;
615
616                 logger("Got id ".$single_conv->id, LOGGER_DEBUG);
617
618                 if ($first_id == "") {
619                         $first_id = $single_conv->id;
620
621                         // The first post of the conversation isn't our first post. There are three options:
622                         // 1. Our conversation hasn't the "real" thread starter
623                         // 2. This first post is a post inside our thread
624                         // 3. This first post is a post inside another thread
625                         if (($first_id != $parent["uri"]) AND ($parent["uri"] != "")) {
626                                 $new_parents = q("SELECT `id`, `parent`, `uri`, `contact-id`, `type`, `verb`, `visible` FROM `item` WHERE `id` IN
627                                                         (SELECT `parent` FROM `item`
628                                                                 WHERE `uid` = %d AND `uri` = '%s' AND `network` IN ('%s','%s')) LIMIT 1",
629                                         intval($uid), dbesc($first_id), dbesc(NETWORK_OSTATUS), dbesc(NETWORK_DFRN));
630                                 if ($new_parents) {
631                                         if ($new_parents[0]["parent"] == $parent["parent"]) {
632                                                 // Option 2: This post is already present inside our thread - but not as thread starter
633                                                 logger("Option 2: uri present in our thread: ".$first_id, LOGGER_DEBUG);
634                                                 $first_id = $parent["uri"];
635                                         } else {
636                                                 // Option 3: Not so good. We have mixed parents. We have to see how to clean this up.
637                                                 // For now just take the new parent.
638                                                 $parent = $new_parents[0];
639                                                 $first_id = $parent["uri"];
640                                                 logger("Option 3: mixed parents for uri ".$first_id, LOGGER_DEBUG);
641                                         }
642                                 } else {
643                                         // Option 1: We hadn't got the real thread starter
644                                         // We have to clean up our existing messages.
645                                         $parent["id"] = 0;
646                                         $parent["uri"] = $first_id;
647                                         logger("Option 1: we have a new parent: ".$first_id, LOGGER_DEBUG);
648                                 }
649                         } elseif ($parent["uri"] == "") {
650                                 $parent["id"] = 0;
651                                 $parent["uri"] = $first_id;
652                         }
653                 }
654
655                 if (isset($single_conv->context->inReplyTo->id)) {
656                         $parent_uri = $single_conv->context->inReplyTo->id;
657
658                         $parent_exists = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `network` IN ('%s','%s') LIMIT 1",
659                                                 intval($uid), dbesc($parent_uri), dbesc(NETWORK_OSTATUS), dbesc(NETWORK_DFRN));
660                         if (!$parent_exists) {
661                                 logger("Parent ".$parent_uri." wasn't found here", LOGGER_DEBUG);
662                                 $parent_uri = $parent["uri"];
663                         }
664                 } else
665                         $parent_uri = $parent["uri"];
666
667                 $message_exists = q("SELECT `id`, `parent`, `uri` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `network` IN ('%s','%s') LIMIT 1",
668                                                 intval($uid), dbesc($single_conv->id),
669                                                 dbesc(NETWORK_OSTATUS), dbesc(NETWORK_DFRN));
670                 if ($message_exists) {
671                         logger("Message ".$single_conv->id." already existed on the system", LOGGER_DEBUG);
672
673                         if ($parent["id"] != 0) {
674                                 $existing_message = $message_exists[0];
675
676                                 // We improved the way we fetch OStatus messages, this shouldn't happen very often now
677                                 // To-Do: we have to change the shadow copies as well. This way here is really ugly.
678                                 if ($existing_message["parent"] != $parent["id"]) {
679                                         logger('updating id '.$existing_message["id"].' with parent '.$existing_message["parent"].' to parent '.$parent["id"].' uri '.$parent["uri"].' thread '.$parent_uri, LOGGER_DEBUG);
680
681                                         // Update the parent id of the selected item
682                                         $r = q("UPDATE `item` SET `parent` = %d, `parent-uri` = '%s' WHERE `id` = %d",
683                                                 intval($parent["id"]), dbesc($parent["uri"]), intval($existing_message["id"]));
684
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 `id` = %d AND `uri` = `thr-parent`",
687                                                 dbesc($parent_uri), intval($existing_message["id"]));
688
689                                         // try to change all items of the same parent
690                                         $r = q("UPDATE `item` SET `parent` = %d, `parent-uri` = '%s' WHERE `parent` = %d",
691                                                 intval($parent["id"]), dbesc($parent["uri"]), intval($existing_message["parent"]));
692
693                                         // Update the parent uri in the thread - but only if it points to itself
694                                         $r = q("UPDATE `item` SET `thr-parent` = '%s' WHERE (`parent` = %d) AND (`uri` = `thr-parent`)",
695                                                 dbesc($parent["uri"]), intval($existing_message["parent"]));
696
697                                         // Now delete the thread
698                                         delete_thread($existing_message["parent"]);
699                                 }
700                         }
701
702                         // The item we are having on the system is the one that we wanted to store via the item array
703                         if (isset($item["uri"]) AND ($item["uri"] == $existing_message["uri"])) {
704                                 $item = array();
705                                 $item_stored = 0;
706                         }
707
708                         continue;
709                 }
710
711                 $actor = $single_conv->actor->id;
712                 if (isset($single_conv->actor->url))
713                         $actor = $single_conv->actor->url;
714
715                 $contact = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `nurl` = '%s' AND `network` != '%s'",
716                                 $uid, normalise_link($actor), NETWORK_STATUSNET);
717
718                 if (count($contact)) {
719                         logger("Found contact for url ".$actor, LOGGER_DEBUG);
720                         $contact_id = $contact[0]["id"];
721                 } else {
722                         logger("No contact found for url ".$actor, LOGGER_DEBUG);
723
724                         // Adding a global contact
725                         // To-Do: Use this data for the post
726                         $global_contact_id = get_contact($actor, 0);
727
728                         logger("Global contact ".$global_contact_id." found for url ".$actor, LOGGER_DEBUG);
729
730                         $contact_id = $parent["contact-id"];
731                 }
732
733                 $arr = array();
734                 $arr["network"] = NETWORK_OSTATUS;
735                 $arr["uri"] = $single_conv->id;
736                 $arr["plink"] = $plink;
737                 $arr["uid"] = $uid;
738                 $arr["contact-id"] = $contact_id;
739                 $arr["parent-uri"] = $parent_uri;
740                 $arr["created"] = $single_conv->published;
741                 $arr["edited"] = $single_conv->published;
742                 $arr["owner-name"] = $single_conv->actor->displayName;
743                 if ($arr["owner-name"] == '')
744                         $arr["owner-name"] = $single_conv->actor->contact->displayName;
745                 if ($arr["owner-name"] == '')
746                         $arr["owner-name"] = $single_conv->actor->portablecontacts_net->displayName;
747
748                 $arr["owner-link"] = $actor;
749                 $arr["owner-avatar"] = $single_conv->actor->image->url;
750                 $arr["author-name"] = $arr["owner-name"];
751                 $arr["author-link"] = $actor;
752                 $arr["author-avatar"] = $single_conv->actor->image->url;
753                 $arr["body"] = add_page_info_to_body(html2bbcode($single_conv->content));
754
755                 if (isset($single_conv->status_net->notice_info->source))
756                         $arr["app"] = strip_tags($single_conv->status_net->notice_info->source);
757                 elseif (isset($single_conv->statusnet->notice_info->source))
758                         $arr["app"] = strip_tags($single_conv->statusnet->notice_info->source);
759                 elseif (isset($single_conv->statusnet_notice_info->source))
760                         $arr["app"] = strip_tags($single_conv->statusnet_notice_info->source);
761                 elseif (isset($single_conv->provider->displayName))
762                         $arr["app"] = $single_conv->provider->displayName;
763                 else
764                         $arr["app"] = "OStatus";
765
766                 $arr["app"] .= " (Conversation)";
767
768                 $arr["object"] = json_encode($single_conv);
769                 $arr["verb"] = $parent["verb"];
770                 $arr["visible"] = $parent["visible"];
771                 $arr["location"] = $single_conv->location->displayName;
772                 $arr["coord"] = trim($single_conv->location->lat." ".$single_conv->location->lon);
773
774                 // Is it a reshared item?
775                 if (isset($single_conv->verb) AND ($single_conv->verb == "share") AND isset($single_conv->object)) {
776                         if (is_array($single_conv->object))
777                                 $single_conv->object = $single_conv->object[0];
778
779                         logger("Found reshared item ".$single_conv->object->id);
780
781                         // $single_conv->object->context->conversation;
782
783                         if (isset($single_conv->object->object->id))
784                                 $arr["uri"] = $single_conv->object->object->id;
785                         else
786                                 $arr["uri"] = $single_conv->object->id;
787
788                         if (isset($single_conv->object->object->url))
789                                 $plink = ostatus_convert_href($single_conv->object->object->url);
790                         else
791                                 $plink = ostatus_convert_href($single_conv->object->url);
792
793                         if (isset($single_conv->object->object->content))
794                                 $arr["body"] = add_page_info_to_body(html2bbcode($single_conv->object->object->content));
795                         else
796                                 $arr["body"] = add_page_info_to_body(html2bbcode($single_conv->object->content));
797
798                         $arr["plink"] = $plink;
799
800                         $arr["created"] = $single_conv->object->published;
801                         $arr["edited"] = $single_conv->object->published;
802
803                         $arr["author-name"] = $single_conv->object->actor->displayName;
804                         if ($arr["owner-name"] == '')
805                                 $arr["author-name"] = $single_conv->object->actor->contact->displayName;
806
807                         $arr["author-link"] = $single_conv->object->actor->url;
808                         $arr["author-avatar"] = $single_conv->object->actor->image->url;
809
810                         $arr["app"] = $single_conv->object->provider->displayName."#";
811                         //$arr["verb"] = $single_conv->object->verb;
812
813                         $arr["location"] = $single_conv->object->location->displayName;
814                         $arr["coord"] = trim($single_conv->object->location->lat." ".$single_conv->object->location->lon);
815                 }
816
817                 if ($arr["location"] == "")
818                         unset($arr["location"]);
819
820                 if ($arr["coord"] == "")
821                         unset($arr["coord"]);
822
823                 // Copy fields from given item array
824                 if (isset($item["uri"]) AND ($item["uri"] == $arr["uri"])) {
825                         $copy_fields = array("owner-name", "owner-link", "owner-avatar", "author-name", "author-link", "author-avatar",
826                                                 "gravity", "body", "object-type", "verb", "created", "edited", "coord", "tag",
827                                                 "attach", "app", "type", "location", "contact-id");
828                         foreach ($copy_fields AS $field)
829                                 if (isset($item[$field]))
830                                         $arr[$field] = $item[$field];
831
832                         $arr["app"] .= " (OStatus)";
833                 }
834
835                 $newitem = item_store($arr);
836                 if (!$newitem) {
837                         logger("Item wasn't stored ".print_r($arr, true), LOGGER_DEBUG);
838                         continue;
839                 }
840
841                 if (isset($item["uri"]) AND ($item["uri"] == $arr["uri"])) {
842                         $item = array();
843                         $item_stored = $newitem;
844                 }
845
846                 logger('Stored new item '.$plink.' for parent '.$arr["parent-uri"].' under id '.$newitem, LOGGER_DEBUG);
847
848                 // Add the conversation entry (but don't fetch the whole conversation)
849                 ostatus_store_conversation($newitem, $conversation_url);
850
851                 // If the newly created item is the top item then change the parent settings of the thread
852                 // This shouldn't happen anymore. This is supposed to be absolote.
853                 if ($arr["uri"] == $first_id) {
854                         logger('setting new parent to id '.$newitem);
855                         $new_parents = q("SELECT `id`, `uri`, `contact-id`, `type`, `verb`, `visible` FROM `item` WHERE `uid` = %d AND `id` = %d LIMIT 1",
856                                 intval($uid), intval($newitem));
857                         if ($new_parents)
858                                 $parent = $new_parents[0];
859                 }
860         }
861
862         return($item_stored);
863 }
864
865 function ostatus_store_conversation($itemid, $conversation_url) {
866         global $a;
867
868         $conversation_url = ostatus_convert_href($conversation_url);
869
870         $messages = q("SELECT `uid`, `parent`, `created`, `received`, `guid` FROM `item` WHERE `id` = %d LIMIT 1", intval($itemid));
871         if (!$messages)
872                 return;
873         $message = $messages[0];
874
875         // Store conversation url if not done before
876         $conversation = q("SELECT `url` FROM `term` WHERE `uid` = %d AND `oid` = %d AND `otype` = %d AND `type` = %d",
877                 intval($message["uid"]), intval($itemid), intval(TERM_OBJ_POST), intval(TERM_CONVERSATION));
878
879         if (!$conversation) {
880                 $r = q("INSERT INTO `term` (`uid`, `oid`, `otype`, `type`, `term`, `url`, `created`, `received`, `guid`) VALUES (%d, %d, %d, %d, '%s', '%s', '%s', '%s', '%s')",
881                         intval($message["uid"]), intval($itemid), intval(TERM_OBJ_POST), intval(TERM_CONVERSATION),
882                         dbesc($message["created"]), dbesc($conversation_url), dbesc($message["created"]), dbesc($message["received"]), dbesc($message["guid"]));
883                 logger('Storing conversation url '.$conversation_url.' for id '.$itemid);
884         }
885 }
886 ?>