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