]> git.mxchange.org Git - friendica.git/blob - include/ostatus.php
Merge pull request #1716 from annando/1506-no-googlemap
[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
194                 if (($item["object-type"] == ACTIVITY_OBJ_BOOKMARK) OR ($item["object-type"] == ACTIVITY_OBJ_EVENT)) {
195                         $item["title"] = $xpath->query('atom:title/text()', $entry)->item(0)->nodeValue;
196                         $item["body"] = $xpath->query('atom:summary/text()', $entry)->item(0)->nodeValue;
197                 } elseif ($item["object-type"] == ACTIVITY_OBJ_QUESTION)
198                         $item["title"] = $xpath->query('atom:title/text()', $entry)->item(0)->nodeValue;
199
200                 $item["object"] = $xml;
201                 $item["verb"] = $xpath->query('activity:verb/text()', $entry)->item(0)->nodeValue;
202
203                 // To-Do:
204                 // Delete a message
205                 if ($item["verb"] == "qvitter-delete-notice") {
206                         // ignore "Delete" messages (by now)
207                         continue;
208                 }
209
210                 if ($item["verb"] == ACTIVITY_JOIN) {
211                         // ignore "Join" messages
212                         continue;
213                 }
214
215                 if ($item["verb"] == ACTIVITY_FOLLOW) {
216                         // ignore "Follow" messages
217                         continue;
218                 }
219
220                 if ($item["verb"] == ACTIVITY_FAVORITE) {
221                         // ignore "Favorite" messages
222                         continue;
223                 }
224
225                 $item["created"] = $xpath->query('atom:published/text()', $entry)->item(0)->nodeValue;
226                 $item["edited"] = $xpath->query('atom:updated/text()', $entry)->item(0)->nodeValue;
227                 $conversation = $xpath->query('ostatus:conversation/text()', $entry)->item(0)->nodeValue;
228
229                 $related = "";
230
231                 $inreplyto = $xpath->query('thr:in-reply-to', $entry);
232                 if (is_object($inreplyto->item(0))) {
233                         foreach($inreplyto->item(0)->attributes AS $attributes) {
234                                 if ($attributes->name == "ref")
235                                         $item["parent-uri"] = $attributes->textContent;
236                                 if ($attributes->name == "href")
237                                         $related = $attributes->textContent;
238                         }
239                 }
240
241                 $georsspoint = $xpath->query('georss:point', $entry);
242                 if ($georsspoint)
243                         $item["coord"] = $georsspoint->item(0)->nodeValue;
244
245                 // To-Do
246                 // $item["location"] =
247
248                 $categories = $xpath->query('atom:category', $entry);
249                 if ($categories) {
250                         foreach ($categories AS $category) {
251                                 foreach($category->attributes AS $attributes)
252                                         if ($attributes->name == "term") {
253                                                 $term = $attributes->textContent;
254                                                 if(strlen($item["tag"]))
255                                                         $item["tag"] .= ',';
256                                                 $item["tag"] .= "#[url=".$a->get_baseurl()."/search?tag=".$term."]".$term."[/url]";
257                                         }
258                         }
259                 }
260
261                 $self = "";
262                 $enclosure = "";
263
264                 $links = $xpath->query('atom:link', $entry);
265                 if ($links) {
266                         $rel = "";
267                         $href = "";
268                         $type = "";
269                         $length = "0";
270                         $title = "";
271                         foreach ($links AS $link) {
272                                 foreach($link->attributes AS $attributes) {
273                                         if ($attributes->name == "href")
274                                                 $href = $attributes->textContent;
275                                         if ($attributes->name == "rel")
276                                                 $rel = $attributes->textContent;
277                                         if ($attributes->name == "type")
278                                                 $type = $attributes->textContent;
279                                         if ($attributes->name == "length")
280                                                 $length = $attributes->textContent;
281                                         if ($attributes->name == "title")
282                                                 $title = $attributes->textContent;
283                                 }
284                                 if (($rel != "") AND ($href != ""))
285                                         switch($rel) {
286                                                 case "alternate":
287                                                         $item["plink"] = $href;
288                                                         if (($item["object-type"] == ACTIVITY_OBJ_QUESTION) OR
289                                                                 ($item["object-type"] == ACTIVITY_OBJ_EVENT))
290                                                                 $item["body"] .= add_page_info($href);
291                                                         break;
292                                                 case "ostatus:conversation":
293                                                         $conversation = $href;
294                                                         break;
295                                                 case "enclosure":
296                                                         $enclosure = $href;
297                                                         if(strlen($item["attach"]))
298                                                                 $item["attach"] .= ',';
299
300                                                         $item["attach"] .= '[attach]href="'.$href.'" length="'.$length.'" type="'.$type.'" title="'.$title.'"[/attach]';
301                                                         break;
302                                                 case "related":
303                                                         if ($item["object-type"] != ACTIVITY_OBJ_BOOKMARK) {
304                                                                 if (!isset($item["parent-uri"]))
305                                                                         $item["parent-uri"] = $href;
306
307                                                                 if ($related == "")
308                                                                         $related = $href;
309                                                         } else
310                                                                 $item["body"] .= add_page_info($href);
311                                                         break;
312                                                 case "self":
313                                                         $self = $href;
314                                                         break;
315                                                 case "mentioned":
316                                                         // Notification check
317                                                         if ($importer["nurl"] == normalise_link($href))
318                                                                 $mention = true;
319                                                         break;
320                                         }
321                         }
322                 }
323
324                 $local_id = "";
325                 $repeat_of = "";
326
327                 $notice_info = $xpath->query('statusnet:notice_info', $entry);
328                 if ($notice_info AND ($notice_info->length > 0)) {
329                         foreach($notice_info->item(0)->attributes AS $attributes) {
330                                 if ($attributes->name == "source")
331                                         $item["app"] = strip_tags($attributes->textContent);
332                                 if ($attributes->name == "local_id")
333                                         $local_id = $attributes->textContent;
334                                 if ($attributes->name == "repeat_of")
335                                         $repeat_of = $attributes->textContent;
336                         }
337                 }
338
339                 // Is it a repeated post?
340                 if ($repeat_of != "") {
341                         $activityobjects = $xpath->query('activity:object', $entry)->item(0);
342
343                         if (is_object($activityobjects)) {
344
345                                 $orig_uri = $xpath->query("activity:object/atom:id", $activityobjects)->item(0)->nodeValue;
346                                 if (!isset($orig_uri))
347                                         $orig_uri = $xpath->query('atom:id/text()', $activityobjects)->item(0)->nodeValue;
348
349                                 $orig_links = $xpath->query("activity:object/atom:link[@rel='alternate']", $activityobjects);
350                                 if ($orig_links AND ($orig_links->length > 0))
351                                         foreach($orig_links->item(0)->attributes AS $attributes)
352                                                 if ($attributes->name == "href")
353                                                         $orig_link = $attributes->textContent;
354
355                                 if (!isset($orig_link))
356                                         $orig_link = $xpath->query("atom:link[@rel='alternate']", $activityobjects)->item(0)->nodeValue;
357
358                                 if (!isset($orig_link))
359                                         $orig_link =  ostatus_convert_href($orig_uri);
360
361                                 $orig_body = $xpath->query('activity:object/atom:content/text()', $activityobjects)->item(0)->nodeValue;
362                                 if (!isset($orig_body))
363                                         $orig_body = $xpath->query('atom:content/text()', $activityobjects)->item(0)->nodeValue;
364
365                                 $orig_created = $xpath->query('atom:published/text()', $activityobjects)->item(0)->nodeValue;
366
367                                 $orig_contact = $contact;
368                                 $orig_author = ostatus_fetchauthor($xpath, $activityobjects, $importer, $orig_contact);
369
370                                 //if (!intval(get_config('system','wall-to-wall_share'))) {
371                                 //      $prefix = share_header($orig_author['author-name'], $orig_author['author-link'], $orig_author['author-avatar'], "", $orig_created, $orig_link);
372                                 //      $item["body"] = $prefix.add_page_info_to_body(html2bbcode($orig_body))."[/share]";
373                                 //} else {
374                                         $item["author-name"] = $orig_author["author-name"];
375                                         $item["author-link"] = $orig_author["author-link"];
376                                         $item["author-avatar"] = $orig_author["author-avatar"];
377                                         $item["body"] = add_page_info_to_body(html2bbcode($orig_body));
378                                         $item["created"] = $orig_created;
379
380                                         $item["uri"] = $orig_uri;
381                                         $item["plink"] = $orig_link;
382                                 //}
383
384                                 $item["verb"] = $xpath->query('activity:verb/text()', $activityobjects)->item(0)->nodeValue;
385
386                                 $item["object-type"] = $xpath->query('activity:object/activity:object-type/text()', $activityobjects)->item(0)->nodeValue;
387                                 if (!isset($item["object-type"]))
388                                         $item["object-type"] = $xpath->query('activity:object-type/text()', $activityobjects)->item(0)->nodeValue;
389                         }
390                 }
391
392                 //if ($enclosure != "")
393                 //      $item["body"] .= add_page_info($enclosure);
394
395                 if (isset($item["parent-uri"])) {
396                         $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s'",
397                                 intval($importer["uid"]), dbesc($item["parent-uri"]));
398
399                         if (!$r AND ($related != "")) {
400                                 $reply_path = str_replace("/notice/", "/api/statuses/show/", $related).".atom";
401
402                                 if ($reply_path != $related) {
403                                         logger("Fetching related items for user ".$importer["uid"]." from ".$reply_path, LOGGER_DEBUG);
404                                         $reply_xml = fetch_url($reply_path);
405
406                                         $reply_contact = $contact;
407                                         ostatus_import($reply_xml,$importer,$reply_contact, $reply_hub);
408
409                                         // After the import try to fetch the parent item again
410                                         $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s'",
411                                                 intval($importer["uid"]), dbesc($item["parent-uri"]));
412                                 }
413                         }
414                         if ($r) {
415                                 $item["type"] = 'remote-comment';
416                                 $item["gravity"] = GRAVITY_COMMENT;
417                         }
418                 } else
419                         $item["parent-uri"] = $item["uri"];
420
421                 $item_id = ostatus_completion($conversation, $importer["uid"], $item);
422
423                 if (!$item_id) {
424                         logger("Error storing item", LOGGER_DEBUG);
425                         continue;
426                 }
427
428                 logger("Item was stored with id ".$item_id, LOGGER_DEBUG);
429                 $item["id"] = $item_id;
430
431                 if ($mention) {
432                         $u = q("SELECT `notify-flags`, `language`, `username`, `email` FROM user WHERE uid = %d LIMIT 1", intval($item['uid']));
433                         $r = q("SELECT `parent` FROM `item` WHERE `id` = %d", intval($item_id));
434
435                         notification(array(
436                                 'type'         => NOTIFY_TAGSELF,
437                                 'notify_flags' => $u[0]["notify-flags"],
438                                 'language'     => $u[0]["language"],
439                                 'to_name'      => $u[0]["username"],
440                                 'to_email'     => $u[0]["email"],
441                                 'uid'          => $item["uid"],
442                                 'item'         => $item,
443                                 'link'         => $a->get_baseurl().'/display/'.urlencode(get_item_guid($item_id)),
444                                 'source_name'  => $item["author-name"],
445                                 'source_link'  => $item["author-link"],
446                                 'source_photo' => $item["author-avatar"],
447                                 'verb'         => ACTIVITY_TAG,
448                                 'otype'        => 'item',
449                                 'parent'       => $r[0]["parent"]
450                         ));
451                 }
452         }
453 }
454
455 function ostatus_convert_href($href) {
456         $elements = explode(":",$href);
457
458         if ((count($elements) <= 2) OR ($elements[0] != "tag"))
459                 return $href;
460
461         $server = explode(",", $elements[1]);
462         $conversation = explode("=", $elements[2]);
463
464         if ((count($elements) == 4) AND ($elements[2] == "post"))
465                 return "http://".$server[0]."/notice/".$elements[3];
466
467         if ((count($conversation) != 2) OR ($conversation[1] ==""))
468                 return $href;
469
470         if ($elements[3] == "objectType=thread")
471                 return "http://".$server[0]."/conversation/".$conversation[1];
472         else
473                 return "http://".$server[0]."/notice/".$conversation[1];
474
475         return $href;
476 }
477
478 function check_conversations($override = false) {
479         $last = get_config('system','ostatus_last_poll');
480
481         $poll_interval = intval(get_config('system','ostatus_poll_interval'));
482         if(! $poll_interval)
483                 $poll_interval = OSTATUS_DEFAULT_POLL_INTERVAL;
484
485         // Don't poll if the interval is set negative
486         if (($poll_interval < 0) AND !$override)
487                 return;
488
489         $poll_timeframe = intval(get_config('system','ostatus_poll_timeframe'));
490         if (!$poll_timeframe)
491                 $poll_timeframe = OSTATUS_DEFAULT_POLL_TIMEFRAME;
492
493         if ($last AND !$override) {
494                 $next = $last + ($poll_interval * 60);
495                 if ($next > time()) {
496                         logger('poll interval not reached');
497                         return;
498                 }
499         }
500
501         logger('cron_start');
502
503         $start = date("Y-m-d H:i:s", time() - ($poll_timeframe * 60));
504         $conversations = q("SELECT `oid`, `url`, `uid` FROM `term` WHERE `type` = 7 AND `term` > '%s' GROUP BY `url`, `uid` ORDER BY `term` DESC",
505                                 dbesc($start));
506
507         foreach ($conversations AS $conversation) {
508                 ostatus_completion($conversation['url'], $conversation['uid']);
509         }
510
511         logger('cron_end');
512
513         set_config('system','ostatus_last_poll', time());
514 }
515
516 function ostatus_completion($conversation_url, $uid, $item = array()) {
517
518         $a = get_app();
519
520         $item_stored = -1;
521
522         $conversation_url = ostatus_convert_href($conversation_url);
523
524         // If the thread shouldn't be completed then store the item and go away
525         if ((intval(get_config('system','ostatus_poll_interval')) == -2) AND (count($item) > 0)) {
526                 //$arr["app"] .= " (OStatus-NoCompletion)";
527                 $item_stored = item_store($item, true);
528                 return($item_stored);
529         }
530
531         // Get the parent
532         $parents = q("SELECT `id`, `parent`, `uri`, `contact-id`, `type`, `verb`, `visible` FROM `item` WHERE `id` IN
533                         (SELECT `parent` FROM `item` WHERE `id` IN
534                                 (SELECT `oid` FROM `term` WHERE `uid` = %d AND `otype` = %d AND `type` = %d AND `url` = '%s'))",
535                         intval($uid), intval(TERM_OBJ_POST), intval(TERM_CONVERSATION), dbesc($conversation_url));
536
537         if ($parents)
538                 $parent = $parents[0];
539         elseif (count($item) > 0) {
540                 $parent = $item;
541                 $parent["type"] = "remote";
542                 $parent["verb"] = ACTIVITY_POST;
543                 $parent["visible"] = 1;
544         } else {
545                 // Preset the parent
546                 $r = q("SELECT `id` FROM `contact` WHERE `self` AND `uid`=%d", $uid);
547                 if (!$r)
548                         return(-2);
549
550                 $parent = array();
551                 $parent["id"] = 0;
552                 $parent["parent"] = 0;
553                 $parent["uri"] = "";
554                 $parent["contact-id"] = $r[0]["id"];
555                 $parent["type"] = "remote";
556                 $parent["verb"] = ACTIVITY_POST;
557                 $parent["visible"] = 1;
558         }
559
560         $conv = str_replace("/conversation/", "/api/statusnet/conversation/", $conversation_url).".as";
561         $pageno = 1;
562         $items = array();
563
564         logger('fetching conversation url '.$conv.' for user '.$uid);
565
566         do {
567                 $conv_arr = z_fetch_url($conv."?page=".$pageno);
568
569                 // If it is a non-ssl site and there is an error, then try ssl or vice versa
570                 if (!$conv_arr["success"] AND (substr($conv, 0, 7) == "http://")) {
571                         $conv = str_replace("http://", "https://", $conv);
572                         $conv_as = fetch_url($conv."?page=".$pageno);
573                 } elseif (!$conv_arr["success"] AND (substr($conv, 0, 8) == "https://")) {
574                         $conv = str_replace("https://", "http://", $conv);
575                         $conv_as = fetch_url($conv."?page=".$pageno);
576                 } else
577                         $conv_as = $conv_arr["body"];
578
579                 $conv_as = str_replace(',"statusnet:notice_info":', ',"statusnet_notice_info":', $conv_as);
580                 $conv_as = json_decode($conv_as);
581
582                 if (@is_array($conv_as->items))
583                         $items = array_merge($items, $conv_as->items);
584                 else
585                         break;
586
587                 $pageno++;
588
589         } while (true);
590
591         logger('fetching conversation done. Found '.count($items).' items');
592
593         if (!sizeof($items)) {
594                 if (count($item) > 0) {
595                         //$arr["app"] .= " (OStatus-NoConvFetched)";
596                         $item_stored = item_store($item, true);
597
598                         if ($item_stored) {
599                                 logger("Conversation ".$conversation_url." couldn't be fetched. Item uri ".$item["uri"]." stored: ".$item_stored, LOGGER_DEBUG);
600                                 ostatus_store_conversation($item_id, $conversation_url);
601                         }
602
603                         return($item_stored);
604                 } else
605                         return(-3);
606         }
607
608         $items = array_reverse($items);
609
610         $r = q("SELECT `nurl` FROM `contact` WHERE `uid` = %d AND `self`", intval($uid));
611         $importer = $r[0];
612
613         foreach ($items as $single_conv) {
614
615                 // Test - remove before flight
616                 //$tempfile = tempnam(get_temppath(), "conversation");
617                 //file_put_contents($tempfile, json_encode($single_conv));
618
619                 $mention = false;
620
621                 if (isset($single_conv->object->id))
622                         $single_conv->id = $single_conv->object->id;
623
624                 $plink = ostatus_convert_href($single_conv->id);
625                 if (isset($single_conv->object->url))
626                         $plink = ostatus_convert_href($single_conv->object->url);
627
628                 if (@!$single_conv->id)
629                         continue;
630
631                 logger("Got id ".$single_conv->id, LOGGER_DEBUG);
632
633                 if ($first_id == "") {
634                         $first_id = $single_conv->id;
635
636                         // The first post of the conversation isn't our first post. There are three options:
637                         // 1. Our conversation hasn't the "real" thread starter
638                         // 2. This first post is a post inside our thread
639                         // 3. This first post is a post inside another thread
640                         if (($first_id != $parent["uri"]) AND ($parent["uri"] != "")) {
641                                 $new_parents = q("SELECT `id`, `parent`, `uri`, `contact-id`, `type`, `verb`, `visible` FROM `item` WHERE `id` IN
642                                                         (SELECT `parent` FROM `item`
643                                                                 WHERE `uid` = %d AND `uri` = '%s' AND `network` IN ('%s','%s')) LIMIT 1",
644                                         intval($uid), dbesc($first_id), dbesc(NETWORK_OSTATUS), dbesc(NETWORK_DFRN));
645                                 if ($new_parents) {
646                                         if ($new_parents[0]["parent"] == $parent["parent"]) {
647                                                 // Option 2: This post is already present inside our thread - but not as thread starter
648                                                 logger("Option 2: uri present in our thread: ".$first_id, LOGGER_DEBUG);
649                                                 $first_id = $parent["uri"];
650                                         } else {
651                                                 // Option 3: Not so good. We have mixed parents. We have to see how to clean this up.
652                                                 // For now just take the new parent.
653                                                 $parent = $new_parents[0];
654                                                 $first_id = $parent["uri"];
655                                                 logger("Option 3: mixed parents for uri ".$first_id, LOGGER_DEBUG);
656                                         }
657                                 } else {
658                                         // Option 1: We hadn't got the real thread starter
659                                         // We have to clean up our existing messages.
660                                         $parent["id"] = 0;
661                                         $parent["uri"] = $first_id;
662                                         logger("Option 1: we have a new parent: ".$first_id, LOGGER_DEBUG);
663                                 }
664                         } elseif ($parent["uri"] == "") {
665                                 $parent["id"] = 0;
666                                 $parent["uri"] = $first_id;
667                         }
668                 }
669
670                 $parent_uri = $parent["uri"];
671
672                 // "context" only seems to exist on older servers
673                 if (isset($single_conv->context->inReplyTo->id)) {
674                         $parent_exists = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `network` IN ('%s','%s') LIMIT 1",
675                                                 intval($uid), dbesc($single_conv->context->inReplyTo->id), dbesc(NETWORK_OSTATUS), dbesc(NETWORK_DFRN));
676                         if ($parent_exists)
677                                 $parent_uri = $single_conv->context->inReplyTo->id;
678                 }
679
680                 // This is the current way
681                 if (isset($single_conv->object->inReplyTo->id)) {
682                         $parent_exists = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `network` IN ('%s','%s') LIMIT 1",
683                                                 intval($uid), dbesc($single_conv->object->inReplyTo->id), dbesc(NETWORK_OSTATUS), dbesc(NETWORK_DFRN));
684                         if ($parent_exists)
685                                 $parent_uri = $single_conv->object->inReplyTo->id;
686                 }
687
688                 $message_exists = q("SELECT `id`, `parent`, `uri` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `network` IN ('%s','%s') LIMIT 1",
689                                                 intval($uid), dbesc($single_conv->id),
690                                                 dbesc(NETWORK_OSTATUS), dbesc(NETWORK_DFRN));
691                 if ($message_exists) {
692                         logger("Message ".$single_conv->id." already existed on the system", LOGGER_DEBUG);
693
694                         if ($parent["id"] != 0) {
695                                 $existing_message = $message_exists[0];
696
697                                 // We improved the way we fetch OStatus messages, this shouldn't happen very often now
698                                 // To-Do: we have to change the shadow copies as well. This way here is really ugly.
699                                 if ($existing_message["parent"] != $parent["id"]) {
700                                         logger('updating id '.$existing_message["id"].' with parent '.$existing_message["parent"].' to parent '.$parent["id"].' uri '.$parent["uri"].' thread '.$parent_uri, LOGGER_DEBUG);
701
702                                         // Update the parent id of the selected item
703                                         $r = q("UPDATE `item` SET `parent` = %d, `parent-uri` = '%s' WHERE `id` = %d",
704                                                 intval($parent["id"]), dbesc($parent["uri"]), intval($existing_message["id"]));
705
706                                         // Update the parent uri in the thread - but only if it points to itself
707                                         $r = q("UPDATE `item` SET `thr-parent` = '%s' WHERE `id` = %d AND `uri` = `thr-parent`",
708                                                 dbesc($parent_uri), intval($existing_message["id"]));
709
710                                         // try to change all items of the same parent
711                                         $r = q("UPDATE `item` SET `parent` = %d, `parent-uri` = '%s' WHERE `parent` = %d",
712                                                 intval($parent["id"]), dbesc($parent["uri"]), intval($existing_message["parent"]));
713
714                                         // Update the parent uri in the thread - but only if it points to itself
715                                         $r = q("UPDATE `item` SET `thr-parent` = '%s' WHERE (`parent` = %d) AND (`uri` = `thr-parent`)",
716                                                 dbesc($parent["uri"]), intval($existing_message["parent"]));
717
718                                         // Now delete the thread
719                                         delete_thread($existing_message["parent"]);
720                                 }
721                         }
722
723                         // The item we are having on the system is the one that we wanted to store via the item array
724                         if (isset($item["uri"]) AND ($item["uri"] == $existing_message["uri"])) {
725                                 $item = array();
726                                 $item_stored = 0;
727                         }
728
729                         continue;
730                 }
731
732                 if (is_array($single_conv->to))
733                         foreach($single_conv->to AS $to)
734                                 if ($importer["nurl"] == normalise_link($to->id))
735                                         $mention = true;
736
737                 $actor = $single_conv->actor->id;
738                 if (isset($single_conv->actor->url))
739                         $actor = $single_conv->actor->url;
740
741                 $contact = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `nurl` = '%s' AND `network` != '%s'",
742                                 $uid, normalise_link($actor), NETWORK_STATUSNET);
743
744                 if (count($contact)) {
745                         logger("Found contact for url ".$actor, LOGGER_DEBUG);
746                         $contact_id = $contact[0]["id"];
747                 } else {
748                         logger("No contact found for url ".$actor, LOGGER_DEBUG);
749
750                         // Adding a global contact
751                         // To-Do: Use this data for the post
752                         $global_contact_id = get_contact($actor, 0);
753
754                         logger("Global contact ".$global_contact_id." found for url ".$actor, LOGGER_DEBUG);
755
756                         $contact_id = $parent["contact-id"];
757                 }
758
759                 $arr = array();
760                 $arr["network"] = NETWORK_OSTATUS;
761                 $arr["uri"] = $single_conv->id;
762                 $arr["plink"] = $plink;
763                 $arr["uid"] = $uid;
764                 $arr["contact-id"] = $contact_id;
765                 $arr["parent-uri"] = $parent_uri;
766                 $arr["created"] = $single_conv->published;
767                 $arr["edited"] = $single_conv->published;
768                 $arr["owner-name"] = $single_conv->actor->displayName;
769                 if ($arr["owner-name"] == '')
770                         $arr["owner-name"] = $single_conv->actor->contact->displayName;
771                 if ($arr["owner-name"] == '')
772                         $arr["owner-name"] = $single_conv->actor->portablecontacts_net->displayName;
773
774                 $arr["owner-link"] = $actor;
775                 $arr["owner-avatar"] = $single_conv->actor->image->url;
776                 $arr["author-name"] = $arr["owner-name"];
777                 $arr["author-link"] = $actor;
778                 $arr["author-avatar"] = $single_conv->actor->image->url;
779                 $arr["body"] = add_page_info_to_body(html2bbcode($single_conv->content));
780
781                 if (isset($single_conv->status_net->notice_info->source))
782                         $arr["app"] = strip_tags($single_conv->status_net->notice_info->source);
783                 elseif (isset($single_conv->statusnet->notice_info->source))
784                         $arr["app"] = strip_tags($single_conv->statusnet->notice_info->source);
785                 elseif (isset($single_conv->statusnet_notice_info->source))
786                         $arr["app"] = strip_tags($single_conv->statusnet_notice_info->source);
787                 elseif (isset($single_conv->provider->displayName))
788                         $arr["app"] = $single_conv->provider->displayName;
789                 else
790                         $arr["app"] = "OStatus";
791
792                 //$arr["app"] .= " (Conversation)";
793
794                 $arr["object"] = json_encode($single_conv);
795                 $arr["verb"] = $parent["verb"];
796                 $arr["visible"] = $parent["visible"];
797                 $arr["location"] = $single_conv->location->displayName;
798                 $arr["coord"] = trim($single_conv->location->lat." ".$single_conv->location->lon);
799
800                 // Is it a reshared item?
801                 if (isset($single_conv->verb) AND ($single_conv->verb == "share") AND isset($single_conv->object)) {
802                         if (is_array($single_conv->object))
803                                 $single_conv->object = $single_conv->object[0];
804
805                         logger("Found reshared item ".$single_conv->object->id);
806
807                         // $single_conv->object->context->conversation;
808
809                         if (isset($single_conv->object->object->id))
810                                 $arr["uri"] = $single_conv->object->object->id;
811                         else
812                                 $arr["uri"] = $single_conv->object->id;
813
814                         if (isset($single_conv->object->object->url))
815                                 $plink = ostatus_convert_href($single_conv->object->object->url);
816                         else
817                                 $plink = ostatus_convert_href($single_conv->object->url);
818
819                         if (isset($single_conv->object->object->content))
820                                 $arr["body"] = add_page_info_to_body(html2bbcode($single_conv->object->object->content));
821                         else
822                                 $arr["body"] = add_page_info_to_body(html2bbcode($single_conv->object->content));
823
824                         $arr["plink"] = $plink;
825
826                         $arr["created"] = $single_conv->object->published;
827                         $arr["edited"] = $single_conv->object->published;
828
829                         $arr["author-name"] = $single_conv->object->actor->displayName;
830                         if ($arr["owner-name"] == '')
831                                 $arr["author-name"] = $single_conv->object->actor->contact->displayName;
832
833                         $arr["author-link"] = $single_conv->object->actor->url;
834                         $arr["author-avatar"] = $single_conv->object->actor->image->url;
835
836                         $arr["app"] = $single_conv->object->provider->displayName."#";
837                         //$arr["verb"] = $single_conv->object->verb;
838
839                         $arr["location"] = $single_conv->object->location->displayName;
840                         $arr["coord"] = trim($single_conv->object->location->lat." ".$single_conv->object->location->lon);
841                 }
842
843                 if ($arr["location"] == "")
844                         unset($arr["location"]);
845
846                 if ($arr["coord"] == "")
847                         unset($arr["coord"]);
848
849                 // Copy fields from given item array
850                 if (isset($item["uri"]) AND (($item["uri"] == $arr["uri"]) OR ($item["uri"] ==  $single_conv->id))) {
851                         $copy_fields = array("owner-name", "owner-link", "owner-avatar", "author-name", "author-link", "author-avatar",
852                                                 "gravity", "body", "object-type", "object", "verb", "created", "edited", "coord", "tag",
853                                                 "title", "attach", "app", "type", "location", "contact-id", "uri");
854                         foreach ($copy_fields AS $field)
855                                 if (isset($item[$field]))
856                                         $arr[$field] = $item[$field];
857
858                         //$arr["app"] .= " (OStatus)";
859                 }
860
861                 $newitem = item_store($arr);
862                 if (!$newitem) {
863                         logger("Item wasn't stored ".print_r($arr, true), LOGGER_DEBUG);
864                         continue;
865                 }
866
867                 if (isset($item["uri"]) AND ($item["uri"] == $arr["uri"])) {
868                         $item = array();
869                         $item_stored = $newitem;
870                 }
871
872                 logger('Stored new item '.$plink.' for parent '.$arr["parent-uri"].' under id '.$newitem, LOGGER_DEBUG);
873
874                 // Add the conversation entry (but don't fetch the whole conversation)
875                 ostatus_store_conversation($newitem, $conversation_url);
876
877                 if ($mention) {
878                         $u = q("SELECT `notify-flags`, `language`, `username`, `email` FROM user WHERE uid = %d LIMIT 1", intval($uid));
879                         $r = q("SELECT `parent` FROM `item` WHERE `id` = %d", intval($newitem));
880
881                         notification(array(
882                                 'type'         => NOTIFY_TAGSELF,
883                                 'notify_flags' => $u[0]["notify-flags"],
884                                 'language'     => $u[0]["language"],
885                                 'to_name'      => $u[0]["username"],
886                                 'to_email'     => $u[0]["email"],
887                                 'uid'          => $uid,
888                                 'item'         => $arr,
889                                 'link'         => $a->get_baseurl().'/display/'.urlencode(get_item_guid($newitem)),
890                                 'source_name'  => $arr["author-name"],
891                                 'source_link'  => $arr["author-link"],
892                                 'source_photo' => $arr["author-avatar"],
893                                 'verb'         => ACTIVITY_TAG,
894                                 'otype'        => 'item',
895                                 'parent'       => $r[0]["parent"]
896                         ));
897                 }
898
899                 // If the newly created item is the top item then change the parent settings of the thread
900                 // This shouldn't happen anymore. This is supposed to be absolote.
901                 if ($arr["uri"] == $first_id) {
902                         logger('setting new parent to id '.$newitem);
903                         $new_parents = q("SELECT `id`, `uri`, `contact-id`, `type`, `verb`, `visible` FROM `item` WHERE `uid` = %d AND `id` = %d LIMIT 1",
904                                 intval($uid), intval($newitem));
905                         if ($new_parents)
906                                 $parent = $new_parents[0];
907                 }
908         }
909
910         if (($item_stored < 0) AND (count($item) > 0)) {
911                 //$arr["app"] .= " (OStatus-NoConvFound)";
912                 $item_stored = item_store($item, true);
913                 if ($item_stored) {
914                         logger("Uri ".$item["uri"]." wasn't found in conversation ".$conversation_url, LOGGER_DEBUG);
915                         ostatus_store_conversation($item_stored, $conversation_url);
916                 }
917         }
918
919         return($item_stored);
920 }
921
922 function ostatus_store_conversation($itemid, $conversation_url) {
923         global $a;
924
925         $conversation_url = ostatus_convert_href($conversation_url);
926
927         $messages = q("SELECT `uid`, `parent`, `created`, `received`, `guid` FROM `item` WHERE `id` = %d LIMIT 1", intval($itemid));
928         if (!$messages)
929                 return;
930         $message = $messages[0];
931
932         // Store conversation url if not done before
933         $conversation = q("SELECT `url` FROM `term` WHERE `uid` = %d AND `oid` = %d AND `otype` = %d AND `type` = %d",
934                 intval($message["uid"]), intval($itemid), intval(TERM_OBJ_POST), intval(TERM_CONVERSATION));
935
936         if (!$conversation) {
937                 $r = q("INSERT INTO `term` (`uid`, `oid`, `otype`, `type`, `term`, `url`, `created`, `received`, `guid`) VALUES (%d, %d, %d, %d, '%s', '%s', '%s', '%s', '%s')",
938                         intval($message["uid"]), intval($itemid), intval(TERM_OBJ_POST), intval(TERM_CONVERSATION),
939                         dbesc($message["created"]), dbesc($conversation_url), dbesc($message["created"]), dbesc($message["received"]), dbesc($message["guid"]));
940                 logger('Storing conversation url '.$conversation_url.' for id '.$itemid);
941         }
942 }
943 ?>