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