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