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