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