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