]> git.mxchange.org Git - friendica.git/blob - include/api.php
api: fix call-time pass-by-reference error
[friendica.git] / include / api.php
1 <?php
2 /* To-Do:
3  - Detecting shared items and transfer them as retweeted items
4  - Automatically detect if incoming data is HTML or BBCode
5  - search for usernames should first search friendica, then the other open networks, then the closed ones
6 */
7         require_once("include/bbcode.php");
8         require_once("include/datetime.php");
9         require_once("include/conversation.php");
10         require_once("include/oauth.php");
11         require_once("include/html2plain.php");
12         /*
13          * Twitter-Like API
14          *
15          */
16
17         $API = Array();
18         $called_api = Null;
19
20         function api_user() {
21           // It is not sufficient to use local_user() to check whether someone is allowed to use the API,
22           // because this will open CSRF holes (just embed an image with src=friendicasite.com/api/statuses/update?status=CSRF
23           // into a page, and visitors will post something without noticing it).
24           // Instead, use this function.
25           if ($_SESSION["allow_api"])
26             return local_user();
27
28           return false;
29         }
30
31         function api_date($str){
32                 //Wed May 23 06:01:13 +0000 2007
33                 return datetime_convert('UTC', 'UTC', $str, "D M d H:i:s +0000 Y" );
34         }
35
36
37         function api_register_func($path, $func, $auth=false){
38                 global $API;
39                 $API[$path] = array('func'=>$func,
40                                                         'auth'=>$auth);
41         }
42
43         /**
44          * Simple HTTP Login
45          */
46
47         function api_login(&$a){
48                 // login with oauth
49                 try{
50                         $oauth = new FKOAuth1();
51                         list($consumer,$token) = $oauth->verify_request(OAuthRequest::from_request());
52                         if (!is_null($token)){
53                                 $oauth->loginUser($token->uid);
54                                 call_hooks('logged_in', $a->user);
55                                 return;
56                         }
57                         echo __file__.__line__.__function__."<pre>"; var_dump($consumer, $token); die();
58                 }catch(Exception $e){
59                         logger(__file__.__line__.__function__."\n".$e);
60                         //die(__file__.__line__.__function__."<pre>".$e); die();
61                 }
62
63
64
65                 // workaround for HTTP-auth in CGI mode
66                 if(x($_SERVER,'REDIRECT_REMOTE_USER')) {
67                         $userpass = base64_decode(substr($_SERVER["REDIRECT_REMOTE_USER"],6)) ;
68                         if(strlen($userpass)) {
69                                 list($name, $password) = explode(':', $userpass);
70                                 $_SERVER['PHP_AUTH_USER'] = $name;
71                                 $_SERVER['PHP_AUTH_PW'] = $password;
72                         }
73                 }
74
75                 if (!isset($_SERVER['PHP_AUTH_USER'])) {
76                         logger('API_login: ' . print_r($_SERVER,true), LOGGER_DEBUG);
77                         header('WWW-Authenticate: Basic realm="Friendica"');
78                         header('HTTP/1.0 401 Unauthorized');
79                         die((api_error($a, 'json', "This api requires login")));
80
81                         //die('This api requires login');
82                 }
83
84                 $user = $_SERVER['PHP_AUTH_USER'];
85                 $encrypted = hash('whirlpool',trim($_SERVER['PHP_AUTH_PW']));
86
87
88                 /**
89                  *  next code from mod/auth.php. needs better solution
90                  */
91
92                 // process normal login request
93
94                 $r = q("SELECT * FROM `user` WHERE ( `email` = '%s' OR `nickname` = '%s' )
95                         AND `password` = '%s' AND `blocked` = 0 AND `account_expired` = 0 AND `account_removed` = 0 AND `verified` = 1 LIMIT 1",
96                         dbesc(trim($user)),
97                         dbesc(trim($user)),
98                         dbesc($encrypted)
99                 );
100                 if(count($r)){
101                         $record = $r[0];
102                 } else {
103                    logger('API_login failure: ' . print_r($_SERVER,true), LOGGER_DEBUG);
104                     header('WWW-Authenticate: Basic realm="Friendica"');
105                     header('HTTP/1.0 401 Unauthorized');
106                     die('This api requires login');
107                 }
108
109                 require_once('include/security.php');
110                 authenticate_success($record); $_SESSION["allow_api"] = true;
111
112                 call_hooks('logged_in', $a->user);
113
114         }
115
116         /**************************
117          *  MAIN API ENTRY POINT  *
118          **************************/
119         function api_call(&$a){
120                 GLOBAL $API, $called_api;
121
122                 // preset
123                 $type="json";
124
125                 foreach ($API as $p=>$info){
126                         if (strpos($a->query_string, $p)===0){
127                                 $called_api= explode("/",$p);
128                                 //unset($_SERVER['PHP_AUTH_USER']);
129                                 if ($info['auth']===true && api_user()===false) {
130                                                 api_login($a);
131                                 }
132
133                                 load_contact_links(api_user());
134
135                                 logger('API call for ' . $a->user['username'] . ': ' . $a->query_string);
136                                 logger('API parameters: ' . print_r($_REQUEST,true));
137                                 $type="json";
138                                 if (strpos($a->query_string, ".xml")>0) $type="xml";
139                                 if (strpos($a->query_string, ".json")>0) $type="json";
140                                 if (strpos($a->query_string, ".rss")>0) $type="rss";
141                                 if (strpos($a->query_string, ".atom")>0) $type="atom";
142                                 if (strpos($a->query_string, ".as")>0) $type="as";
143
144                                 $r = call_user_func($info['func'], $a, $type);
145                                 if ($r===false) return;
146
147                                 switch($type){
148                                         case "xml":
149                                                 $r = mb_convert_encoding($r, "UTF-8",mb_detect_encoding($r));
150                                                 header ("Content-Type: text/xml");
151                                                 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
152                                                 break;
153                                         case "json":
154                                                 header ("Content-Type: application/json");
155                                                 foreach($r as $rr)
156                                                     return json_encode($rr);
157                                                 break;
158                                         case "rss":
159                                                 header ("Content-Type: application/rss+xml");
160                                                 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
161                                                 break;
162                                         case "atom":
163                                                 header ("Content-Type: application/atom+xml");
164                                                 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
165                                                 break;
166                                         case "as":
167                                                 //header ("Content-Type: application/json");
168                                                 //foreach($r as $rr)
169                                                 //    return json_encode($rr);
170                                                 return json_encode($r);
171                                                 break;
172
173                                 }
174                                 //echo "<pre>"; var_dump($r); die();
175                         }
176                 }
177                 header("HTTP/1.1 404 Not Found");
178                 logger('API call not implemented: '.$a->query_string." - ".print_r($_REQUEST,true));
179                 return(api_error($a, $type, "not implemented"));
180
181         }
182
183         function api_error(&$a, $type, $error) {
184                 $r = "<status><error>".$error."</error><request>".$a->query_string."</request></status>";
185                 switch($type){
186                         case "xml":
187                                 header ("Content-Type: text/xml");
188                                 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
189                                 break;
190                         case "json":
191                                 header ("Content-Type: application/json");
192                                 return json_encode(array('error' => $error, 'request' => $a->query_string));
193                                 break;
194                         case "rss":
195                                 header ("Content-Type: application/rss+xml");
196                                 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
197                                 break;
198                         case "atom":
199                                 header ("Content-Type: application/atom+xml");
200                                 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
201                                 break;
202                 }
203         }
204
205         /**
206          * RSS extra info
207          */
208         function api_rss_extra(&$a, $arr, $user_info){
209                 if (is_null($user_info)) $user_info = api_get_user($a);
210                 $arr['$user'] = $user_info;
211                 $arr['$rss'] = array(
212                         'alternate' => $user_info['url'],
213                         'self' => $a->get_baseurl(). "/". $a->query_string,
214                         'base' => $a->get_baseurl(),
215                         'updated' => api_date(null),
216                         'atom_updated' => datetime_convert('UTC','UTC','now',ATOM_TIME),
217                         'language' => $user_info['language'],
218                         'logo'  => $a->get_baseurl()."/images/friendica-32.png",
219                 );
220
221                 return $arr;
222         }
223
224
225         /**
226          * Unique contact to contact url.
227          */
228         function api_unique_id_to_url($id){
229                 $r = q("SELECT url FROM unique_contacts WHERE id=%d LIMIT 1",
230                         intval($id));
231                 if ($r)
232                         return ($r[0]["url"]);
233                 else
234                         return false;
235         }
236
237         /**
238          * Returns user info array.
239          */
240         function api_get_user(&$a, $contact_id = Null, $type = "json"){
241                 global $called_api;
242                 $user = null;
243                 $extra_query = "";
244                 $url = "";
245                 $nick = "";
246
247                 // Searching for contact URL
248                 if(!is_null($contact_id) AND (intval($contact_id) == 0)){
249                         $user = dbesc(normalise_link($contact_id));
250                         $url = $user;
251                         $extra_query = "AND `contact`.`nurl` = '%s' ";
252                         if (api_user()!==false)  $extra_query .= "AND `contact`.`uid`=".intval(api_user());
253                 }
254
255                 // Searching for unique contact id
256                 if(!is_null($contact_id) AND (intval($contact_id) != 0)){
257                         $user = dbesc(api_unique_id_to_url($contact_id));
258
259                         if ($user == "")
260                                 die(api_error($a, $type, t("User not found.")));
261
262                         $url = $user;
263                         $extra_query = "AND `contact`.`nurl` = '%s' ";
264                         if (api_user()!==false)  $extra_query .= "AND `contact`.`uid`=".intval(api_user());
265                 }
266
267                 if(is_null($user) && x($_GET, 'user_id')) {
268                         $user = dbesc(api_unique_id_to_url($_GET['user_id']));
269
270                         if ($user == "")
271                                 die(api_error($a, $type, t("User not found.")));
272
273                         $url = $user;
274                         $extra_query = "AND `contact`.`nurl` = '%s' ";
275                         if (api_user()!==false)  $extra_query .= "AND `contact`.`uid`=".intval(api_user());
276                 }
277                 if(is_null($user) && x($_GET, 'screen_name')) {
278                         $user = dbesc($_GET['screen_name']);
279                         $nick = $user;
280                         $extra_query = "AND `contact`.`nick` = '%s' ";
281                         if (api_user()!==false)  $extra_query .= "AND `contact`.`uid`=".intval(api_user());
282                 }
283
284                 if (is_null($user) AND ($a->argc > (count($called_api)-1)) AND (count($called_api) > 0)){
285                         $argid = count($called_api);
286                         list($user, $null) = explode(".",$a->argv[$argid]);
287                         if(is_numeric($user)){
288                                 $user = dbesc(api_unique_id_to_url($user));
289
290                                 if ($user == "")
291                                         return false;
292
293                                 $url = $user;
294                                 $extra_query = "AND `contact`.`nurl` = '%s' ";
295                                 if (api_user()!==false)  $extra_query .= "AND `contact`.`uid`=".intval(api_user());
296                         } else {
297                                 $user = dbesc($user);
298                                 $nick = $user;
299                                 $extra_query = "AND `contact`.`nick` = '%s' ";
300                                 if (api_user()!==false)  $extra_query .= "AND `contact`.`uid`=".intval(api_user());
301                         }
302                 }
303
304                 if (!$user) {
305                         if (api_user()===false) {
306                                 api_login($a); return False;
307                         } else {
308                                 $user = $_SESSION['uid'];
309                                 $extra_query = "AND `contact`.`uid` = %d AND `contact`.`self` = 1 ";
310                         }
311
312                 }
313
314                 logger('api_user: ' . $extra_query . ', user: ' . $user);
315                 // user info
316                 $uinfo = q("SELECT *, `contact`.`id` as `cid` FROM `contact`
317                                 WHERE 1
318                                 $extra_query",
319                                 $user
320                 );
321
322                 // if the contact wasn't found, fetch it from the unique contacts
323                 if (count($uinfo)==0) {
324                         $r = array();
325
326                         if ($url != "")
327                                 $r = q("SELECT * FROM unique_contacts WHERE url='%s' LIMIT 1", $url);
328                         elseif ($nick != "")
329                                 $r = q("SELECT * FROM unique_contacts WHERE nick='%s' LIMIT 1", $nick);
330
331                         if ($r) {
332                                 $ret = array(
333                                         'id' => $r[0]["id"],
334                                         'name' => $r[0]["name"],
335                                         'screen_name' => (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']),
336                                         'location' => NULL,
337                                         'description' => NULL,
338                                         'profile_image_url' => $r[0]["avatar"],
339                                         'profile_image_url_https' => $r[0]["avatar"],
340                                         'url' => $r[0]["url"],
341                                         'protected' => false,
342                                         'followers_count' => 0,
343                                         'friends_count' => 0,
344                                         'created_at' => api_date(0),
345                                         'favourites_count' => 0,
346                                         'utc_offset' => 0,
347                                         'time_zone' => 'UTC',
348                                         'statuses_count' => 0,
349                                         'following' => false,
350                                         'verified' => false,
351                                         'statusnet_blocking' => false,
352                                         'notifications' => false,
353                                         'statusnet_profile_url' => $r[0]["url"],
354                                         'uid' => 0,
355                                         'cid' => 0,
356                                         'self' => 0,
357                                 );
358
359                                 return $ret;
360                         } else
361                                 die(api_error($a, $type, t("User not found.")));
362
363                 }
364
365                 if($uinfo[0]['self']) {
366                         $usr = q("select * from user where uid = %d limit 1",
367                                 intval(api_user())
368                         );
369                         $profile = q("select * from profile where uid = %d and `is-default` = 1 limit 1",
370                                 intval(api_user())
371                         );
372
373                         // count public wall messages
374                         $r = q("SELECT COUNT(`id`) as `count` FROM `item`
375                                         WHERE  `uid` = %d
376                                         AND `type`='wall'
377                                         AND `allow_cid`='' AND `allow_gid`='' AND `deny_cid`='' AND `deny_gid`=''",
378                                         intval($uinfo[0]['uid'])
379                         );
380                         $countitms = $r[0]['count'];
381                 }
382                 else {
383                         $r = q("SELECT COUNT(`id`) as `count` FROM `item`
384                                         WHERE  `contact-id` = %d
385                                         AND `allow_cid`='' AND `allow_gid`='' AND `deny_cid`='' AND `deny_gid`=''",
386                                         intval($uinfo[0]['id'])
387                         );
388                         $countitms = $r[0]['count'];
389                 }
390
391                 // count friends
392                 $r = q("SELECT COUNT(`id`) as `count` FROM `contact`
393                                 WHERE  `uid` = %d AND `rel` IN ( %d, %d )
394                                 AND `self`=0 AND `blocked`=0 AND `pending`=0 AND `hidden`=0",
395                                 intval($uinfo[0]['uid']),
396                                 intval(CONTACT_IS_SHARING),
397                                 intval(CONTACT_IS_FRIEND)
398                 );
399                 $countfriends = $r[0]['count'];
400
401                 $r = q("SELECT COUNT(`id`) as `count` FROM `contact`
402                                 WHERE  `uid` = %d AND `rel` IN ( %d, %d )
403                                 AND `self`=0 AND `blocked`=0 AND `pending`=0 AND `hidden`=0",
404                                 intval($uinfo[0]['uid']),
405                                 intval(CONTACT_IS_FOLLOWER),
406                                 intval(CONTACT_IS_FRIEND)
407                 );
408                 $countfollowers = $r[0]['count'];
409
410                 $r = q("SELECT count(`id`) as `count` FROM item where starred = 1 and uid = %d and deleted = 0",
411                         intval($uinfo[0]['uid'])
412                 );
413                 $starred = $r[0]['count'];
414
415
416                 if(! $uinfo[0]['self']) {
417                         $countfriends = 0;
418                         $countfollowers = 0;
419                         $starred = 0;
420                 }
421
422                 // Fetching unique id
423                 $r = q("SELECT id FROM unique_contacts WHERE url='%s' LIMIT 1", dbesc(normalise_link($uinfo[0]['url'])));
424
425                 // If not there, then add it
426                 if (count($r) == 0) {
427                         q("INSERT INTO unique_contacts (url, name, nick, avatar) VALUES ('%s', '%s', '%s', '%s')",
428                                 dbesc(normalise_link($uinfo[0]['url'])), dbesc($uinfo[0]['name']),dbesc($uinfo[0]['nick']), dbesc($uinfo[0]['micro']));
429
430                         $r = q("SELECT id FROM unique_contacts WHERE url='%s' LIMIT 1", dbesc(normalise_link($uinfo[0]['url'])));
431                 }
432
433                 $ret = Array(
434                         'id' => intval($r[0]['id']),
435                         'name' => (($uinfo[0]['name']) ? $uinfo[0]['name'] : $uinfo[0]['nick']),
436                         'screen_name' => (($uinfo[0]['nick']) ? $uinfo[0]['nick'] : $uinfo[0]['name']),
437                         'location' => ($usr) ? $usr[0]['default-location'] : NULL,
438                         'description' => (($profile) ? $profile[0]['pdesc'] : NULL),
439                         'profile_image_url' => $uinfo[0]['micro'],
440                         'profile_image_url_https' => $uinfo[0]['micro'],
441                         'url' => $uinfo[0]['url'],
442                         'protected' => false,
443                         'followers_count' => intval($countfollowers),
444                         'friends_count' => intval($countfriends),
445                         'created_at' => api_date($uinfo[0]['name-date']),
446                         'favourites_count' => intval($starred),
447                         'utc_offset' => "0", // To-Do
448                         'time_zone' => 'UTC', // To-Do $uinfo[0]['timezone'],
449                         'statuses_count' => intval($countitms),
450                         'following' => true, //#XXX: fix me
451                         'verified' => true, //#XXX: fix me
452                         'statusnet_blocking' => false,
453                         'notifications' => false,
454                         'statusnet_profile_url' => $a->get_baseurl()."/contacts/".$uinfo[0]['cid'],
455                         'uid' => intval($uinfo[0]['uid']),
456                         'cid' => intval($uinfo[0]['cid']),
457                         'self' => $uinfo[0]['self'],
458                 );
459
460                 return $ret;
461
462         }
463
464         function api_item_get_user(&$a, $item) {
465
466                 $author = q("SELECT * FROM unique_contacts WHERE url='%s' LIMIT 1",
467                         dbesc(normalise_link($item['author-link'])));
468
469                 if (count($author) == 0) {
470                         q("INSERT INTO unique_contacts (url, name, avatar) VALUES ('%s', '%s', '%s')",
471                         dbesc(normalise_link($item["author-link"])), dbesc($item["author-name"]), dbesc($item["author-avatar"]));
472
473                         $author = q("SELECT id FROM unique_contacts WHERE url='%s' LIMIT 1",
474                                 dbesc(normalise_link($item['author-link'])));
475                 } else if ($item["author-link"].$item["author-name"] != $author[0]["url"].$author[0]["name"]) {
476                         q("UPDATE unique_contacts SET name = '%s', avatar = '%s' WHERE url = '%s'",
477                         dbesc($item["author-name"]), dbesc($item["author-avatar"]), dbesc(normalise_link($item["author-link"])));
478                 }
479
480                 $owner = q("SELECT id FROM unique_contacts WHERE url='%s' LIMIT 1",
481                         dbesc(normalise_link($item['owner-link'])));
482
483                 if (count($owner) == 0) {
484                         q("INSERT INTO unique_contacts (url, name, avatar) VALUES ('%s', '%s', '%s')",
485                         dbesc(normalise_link($item["owner-link"])), dbesc($item["owner-name"]), dbesc($item["owner-avatar"]));
486
487                         $owner = q("SELECT id FROM unique_contacts WHERE url='%s' LIMIT 1",
488                                 dbesc(normalise_link($item['owner-link'])));
489                 } else if ($item["owner-link"].$item["owner-name"] != $owner[0]["url"].$owner[0]["name"]) {
490                         q("UPDATE unique_contacts SET name = '%s', avatar = '%s' WHERE url = '%s'",
491                         dbesc($item["owner-name"]), dbesc($item["owner-avatar"]), dbesc(normalise_link($item["owner-link"])));
492                 }
493
494                 // Comments in threads may appear as wall-to-wall postings.
495                 // So only take the owner at the top posting.
496                 if ($item["id"] == $item["parent"])
497                         return api_get_user($a,$item["owner-link"]);
498                 else
499                         return api_get_user($a,$item["author-link"]);
500         }
501
502
503         /**
504          *  load api $templatename for $type and replace $data array
505          */
506         function api_apply_template($templatename, $type, $data){
507
508                 $a = get_app();
509
510                 switch($type){
511                         case "atom":
512                         case "rss":
513                         case "xml":
514                                 $data = array_xmlify($data);
515                                 $tpl = get_markup_template("api_".$templatename."_".$type.".tpl");
516                                 if(! $tpl) {
517                                         header ("Content-Type: text/xml");
518                                         echo '<?xml version="1.0" encoding="UTF-8"?>'."\n".'<status><error>not implemented</error></status>';
519                                         killme();
520                                 }
521                                 $ret = replace_macros($tpl, $data);
522                                 break;
523                         case "json":
524                                 $ret = $data;
525                                 break;
526                 }
527                 return $ret;
528         }
529
530         /**
531          ** TWITTER API
532          */
533
534         /**
535          * Returns an HTTP 200 OK response code and a representation of the requesting user if authentication was successful;
536          * returns a 401 status code and an error message if not.
537          * http://developer.twitter.com/doc/get/account/verify_credentials
538          */
539         function api_account_verify_credentials(&$a, $type){
540                 if (api_user()===false) return false;
541
542                 unset($_REQUEST["user_id"]);
543                 unset($_GET["user_id"]);
544
545                 $user_info = api_get_user($a);
546
547                 // "verified" isn't used here in the standard
548                 unset($user_info["verified"]);
549
550                 // - Adding last status
551                 $user_info["status"] = api_status_show($a,"raw");
552                 if (!count($user_info["status"]))
553                         unset($user_info["status"]);
554                 else
555                         unset($user_info["status"]["user"]);
556
557                 // "cid", "uid" and "self" are only needed for some internal stuff, so remove it from here
558                 unset($user_info["cid"]);
559                 unset($user_info["uid"]);
560                 unset($user_info["self"]);
561
562                 return api_apply_template("user", $type, array('$user' => $user_info));
563
564         }
565         api_register_func('api/account/verify_credentials','api_account_verify_credentials', true);
566
567
568         /**
569          * get data from $_POST or $_GET
570          */
571         function requestdata($k){
572                 if (isset($_POST[$k])){
573                         return $_POST[$k];
574                 }
575                 if (isset($_GET[$k])){
576                         return $_GET[$k];
577                 }
578                 return null;
579         }
580
581 /*Waitman Gobble Mod*/
582         function api_statuses_mediap(&$a, $type) {
583                 if (api_user()===false) {
584                         logger('api_statuses_update: no user');
585                         return false;
586                 }
587                 $user_info = api_get_user($a);
588
589                 $_REQUEST['type'] = 'wall';
590                 $_REQUEST['profile_uid'] = api_user();
591                 $_REQUEST['api_source'] = true;
592                 $txt = requestdata('status');
593                 //$txt = urldecode(requestdata('status'));
594
595                 require_once('library/HTMLPurifier.auto.php');
596                 require_once('include/html2bbcode.php');
597
598                 if((strpos($txt,'<') !== false) || (strpos($txt,'>') !== false)) {
599                         $txt = html2bb_video($txt);
600                         $config = HTMLPurifier_Config::createDefault();
601                         $config->set('Cache.DefinitionImpl', null);
602                         $purifier = new HTMLPurifier($config);
603                         $txt = $purifier->purify($txt);
604                 }
605                 $txt = html2bbcode($txt);
606
607                 $a->argv[1]=$user_info['screen_name']; //should be set to username?
608
609                 $_REQUEST['hush']='yeah'; //tell wall_upload function to return img info instead of echo
610                 require_once('mod/wall_upload.php');
611                 $bebop = wall_upload_post($a);
612
613                 //now that we have the img url in bbcode we can add it to the status and insert the wall item.
614                 $_REQUEST['body']=$txt."\n\n".$bebop;
615                 require_once('mod/item.php');
616                 item_post($a);
617
618                 // this should output the last post (the one we just posted).
619                 return api_status_show($a,$type);
620         }
621         api_register_func('api/statuses/mediap','api_statuses_mediap', true);
622 /*Waitman Gobble Mod*/
623
624
625         function api_statuses_update(&$a, $type) {
626                 if (api_user()===false) {
627                         logger('api_statuses_update: no user');
628                         return false;
629                 }
630                 $user_info = api_get_user($a);
631
632                 // convert $_POST array items to the form we use for web posts.
633
634                 // logger('api_post: ' . print_r($_POST,true));
635
636                 if(requestdata('htmlstatus')) {
637                         require_once('library/HTMLPurifier.auto.php');
638                         require_once('include/html2bbcode.php');
639
640                         $txt = requestdata('htmlstatus');
641                         if((strpos($txt,'<') !== false) || (strpos($txt,'>') !== false)) {
642
643                                 $txt = html2bb_video($txt);
644
645                                 $config = HTMLPurifier_Config::createDefault();
646                                 $config->set('Cache.DefinitionImpl', null);
647
648
649                                 $purifier = new HTMLPurifier($config);
650                                 $txt = $purifier->purify($txt);
651
652                                 $_REQUEST['body'] = html2bbcode($txt);
653                         }
654
655                 }
656                 else
657                         $_REQUEST['body'] = requestdata('status');
658
659                 $_REQUEST['title'] = requestdata('title');
660
661                 $parent = requestdata('in_reply_to_status_id');
662                 if(ctype_digit($parent))
663                         $_REQUEST['parent'] = $parent;
664                 else
665                         $_REQUEST['parent_uri'] = $parent;
666
667                 if(requestdata('lat') && requestdata('long'))
668                         $_REQUEST['coord'] = sprintf("%s %s",requestdata('lat'),requestdata('long'));
669                 $_REQUEST['profile_uid'] = api_user();
670
671                 if($parent)
672                         $_REQUEST['type'] = 'net-comment';
673                 else {
674                         $_REQUEST['type'] = 'wall';
675                         if(x($_FILES,'media')) {
676                                 // upload the image if we have one
677                                 $_REQUEST['hush']='yeah'; //tell wall_upload function to return img info instead of echo
678                                 require_once('mod/wall_upload.php');
679                                 $media = wall_upload_post($a);
680                                 if(strlen($media)>0)
681                                         $_REQUEST['body'] .= "\n\n".$media;
682                         }
683                 }
684
685                 // set this so that the item_post() function is quiet and doesn't redirect or emit json
686
687                 $_REQUEST['api_source'] = true;
688
689                 // call out normal post function
690
691                 require_once('mod/item.php');
692                 item_post($a);
693
694                 // this should output the last post (the one we just posted).
695                 return api_status_show($a,$type);
696         }
697         api_register_func('api/statuses/update','api_statuses_update', true);
698
699
700         function api_status_show(&$a, $type){
701                 $user_info = api_get_user($a);
702                 // get last public wall message
703                 $lastwall = q("SELECT `item`.*, `i`.`contact-id` as `reply_uid`, `c`.`nick` as `reply_author`, `i`.`author-link` AS `item-author`
704                                 FROM `item`, `contact`, `item` as `i`, `contact` as `c`
705                                 WHERE `item`.`contact-id` = %d AND `item`.`owner-link` = '%s'
706                                         AND `i`.`id` = `item`.`parent`
707                                         AND `contact`.`id`=`item`.`contact-id` AND `c`.`id`=`i`.`contact-id` AND `contact`.`self`=1
708                                         AND `item`.`type`!='activity'
709                                         AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''
710                                 ORDER BY `item`.`created` DESC
711                                 LIMIT 1",
712                                 intval($user_info['cid']),
713                                 dbesc($user_info['url'])
714                 );
715
716                 if (count($lastwall)>0){
717                         $lastwall = $lastwall[0];
718
719                         $in_reply_to_status_id = NULL;
720                         $in_reply_to_user_id = NULL;
721                         $in_reply_to_screen_name = NULL;
722                         if ($lastwall['parent']!=$lastwall['id']) {
723                                 $in_reply_to_status_id=$lastwall['parent'];
724                                 //$in_reply_to_user_id = $lastwall['reply_uid'];
725                                 //$in_reply_to_screen_name = $lastwall['reply_author'];
726
727                                 $r = q("SELECT * FROM unique_contacts WHERE `url` = '%s'", dbesc(normalise_link($lastwall['item-author'])));
728                                 if ($r) {
729                                         $in_reply_to_screen_name = $r[0]['name'];
730                                         $in_reply_to_user_id = $r[0]['id'];
731                                 }
732                         }
733                         $status_info = array(
734                                 'text' => trim(html2plain(bbcode($lastwall['body'], false, false, 2), 0)),
735                                 'truncated' => false,
736                                 'created_at' => api_date($lastwall['created']),
737                                 'in_reply_to_status_id' => $in_reply_to_status_id,
738                                 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
739                                 'id' => $lastwall['id'],
740                                 'in_reply_to_user_id' => $in_reply_to_user_id,
741                                 'in_reply_to_screen_name' => $in_reply_to_screen_name,
742                                 'geo' => NULL,
743                                 'favorited' => false,
744                                 // attachments
745                                 'user' => $user_info,
746                                 'statusnet_html'                => trim(bbcode($lastwall['body'], false, false)),
747                                 'statusnet_conversation_id'     => $lastwall['parent'],
748                         );
749
750                         if (($lastwall['item_network'] != "") AND ($status["source"] == 'web'))
751                                 $status_info["source"] = network_to_name($lastwall['item_network']);
752                         elseif (($lastwall['item_network'] != "") AND (network_to_name($lastwall['item_network']) != $status_info["source"]))
753                                 $status_info["source"] = trim($status_info["source"].' ('.network_to_name($lastwall['item_network']).')');
754
755                         // "cid", "uid" and "self" are only needed for some internal stuff, so remove it from here
756                         unset($status_info["user"]["cid"]);
757                         unset($status_info["user"]["uid"]);
758                         unset($status_info["user"]["self"]);
759                 }
760
761                 if ($type == "raw")
762                         return($status_info);
763
764                 return  api_apply_template("status", $type, array('$status' => $status_info));
765
766         }
767
768
769
770
771
772         /**
773          * Returns extended information of a given user, specified by ID or screen name as per the required id parameter.
774          * The author's most recent status will be returned inline.
775          * http://developer.twitter.com/doc/get/users/show
776          */
777         function api_users_show(&$a, $type){
778                 $user_info = api_get_user($a);
779
780                 $lastwall = q("SELECT `item`.*
781                                 FROM `item`, `contact`
782                                 WHERE `item`.`contact-id` = %d  AND `item`.`owner-link` = '%s'
783                                         AND `contact`.`id`=`item`.`contact-id`
784                                         AND `type`!='activity'
785                                         AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''
786                                 ORDER BY `created` DESC
787                                 LIMIT 1",
788                                 intval($user_info['cid']),
789                                 dbesc($user_info['url'])
790                 );
791
792                 if (count($lastwall)>0){
793                         $lastwall = $lastwall[0];
794
795                         $in_reply_to_status_id = NULL;
796                         $in_reply_to_user_id = NULL;
797                         $in_reply_to_screen_name = NULL;
798                         if ($lastwall['parent']!=$lastwall['id']) {
799                                 $reply = q("SELECT `item`.`id`, `item`.`contact-id` as `reply_uid`, `contact`.`nick` as `reply_author`, `item`.`author-link` AS `item-author`
800                                             FROM `item`,`contact` WHERE `contact`.`id`=`item`.`contact-id` AND `item`.`id` = %d", intval($lastwall['parent']));
801                                 if (count($reply)>0) {
802                                         $in_reply_to_status_id=$lastwall['parent'];
803                                         //$in_reply_to_user_id = $reply[0]['reply_uid'];
804                                         //$in_reply_to_screen_name = $reply[0]['reply_author'];
805                                         $r = q("SELECT * FROM unique_contacts WHERE `url` = '%s'", dbesc(normalise_link($reply[0]['item-author'])));
806                                         if ($r) {
807                                                 $in_reply_to_screen_name = $r[0]['name'];
808                                                 $in_reply_to_user_id = $r[0]['id'];
809                                         }
810                                 }
811                         }
812                         $user_info['status'] = array(
813                                 'text' => trim(html2plain(bbcode($lastwall['body'], false, false, 2), 0)),
814                                 'truncated' => false,
815                                 'created_at' => api_date($lastwall['created']),
816                                 'in_reply_to_status_id' => $in_reply_to_status_id,
817                                 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
818                                 'id' => $lastwall['contact-id'],
819                                 'in_reply_to_user_id' => $in_reply_to_user_id,
820                                 'in_reply_to_screen_name' => $in_reply_to_screen_name,
821                                 'geo' => NULL,
822                                 'favorited' => false,
823                                 'statusnet_html'                => trim(bbcode($lastwall['body'], false, false)),
824                                 'statusnet_conversation_id'     => $lastwall['parent'],
825                         );
826
827                         if (($lastwall['item_network'] != "") AND ($user_info["status"]["source"] == 'web'))
828                                 $user_info["status"]["source"] = network_to_name($lastwall['item_network']);
829                         if (($lastwall['item_network'] != "") AND (network_to_name($lastwall['item_network']) != $user_info["status"]["source"]))
830                                 $user_info["status"]["source"] = trim($user_info["status"]["source"].' ('.network_to_name($lastwall['item_network']).')');
831
832                 }
833
834                 // "cid", "uid" and "self" are only needed for some internal stuff, so remove it from here
835                 unset($user_info["cid"]);
836                 unset($user_info["uid"]);
837                 unset($user_info["self"]);
838
839                 return  api_apply_template("user", $type, array('$user' => $user_info));
840
841         }
842         api_register_func('api/users/show','api_users_show');
843
844         /**
845          *
846          * http://developer.twitter.com/doc/get/statuses/home_timeline
847          *
848          * TODO: Optional parameters
849          * TODO: Add reply info
850          */
851         function api_statuses_home_timeline(&$a, $type){
852                 if (api_user()===false) return false;
853
854                 unset($_REQUEST["user_id"]);
855                 unset($_GET["user_id"]);
856
857                 $user_info = api_get_user($a);
858                 // get last newtork messages
859
860
861                 // params
862                 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
863                 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
864                 if ($page<0) $page=0;
865                 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
866                 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
867                 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
868                 $exclude_replies = (x($_REQUEST,'exclude_replies')?1:0);
869                 $conversation_id = (x($_REQUEST,'conversation_id')?$_REQUEST['conversation_id']:0);
870
871                 $start = $page*$count;
872
873                 //$include_entities = (x($_REQUEST,'include_entities')?$_REQUEST['include_entities']:false);
874
875                 $sql_extra = '';
876                 if ($max_id > 0)
877                         $sql_extra .= ' AND `item`.`id` <= '.intval($max_id);
878                 if ($exclude_replies > 0)
879                         $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
880                 if ($conversation_id > 0)
881                         $sql_extra .= ' AND `item`.`parent` = '.intval($conversation_id);
882
883                 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
884                         `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
885                         `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
886                         `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
887                         FROM `item`, `contact`
888                         WHERE `item`.`uid` = %d
889                         AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
890                         AND `contact`.`id` = `item`.`contact-id`
891                         AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
892                         $sql_extra
893                         AND `item`.`id`>%d
894                         ORDER BY `item`.`received` DESC LIMIT %d ,%d ",
895                         //intval($user_info['uid']),
896                         intval(api_user()),
897                         intval($since_id),
898                         intval($start), intval($count)
899                 );
900
901                 $ret = api_format_items($r,$user_info);
902
903                 // We aren't going to try to figure out at the item, group, and page
904                 // level which items you've seen and which you haven't. If you're looking
905                 // at the network timeline just mark everything seen. 
906
907                 $r = q("UPDATE `item` SET `unseen` = 0 
908                         WHERE `unseen` = 1 AND `uid` = %d",
909                         //intval($user_info['uid'])
910                         intval(api_user())
911                 );
912
913
914                 $data = array('$statuses' => $ret);
915                 switch($type){
916                         case "atom":
917                         case "rss":
918                                 $data = api_rss_extra($a, $data, $user_info);
919                                 break;
920                         case "as":
921                                 $as = api_format_as($a, $ret, $user_info);
922                                 $as['title'] = $a->config['sitename']." Home Timeline";
923                                 $as['link']['url'] = $a->get_baseurl()."/".$user_info["screen_name"]."/all";
924                                 return($as);
925                                 break;
926                 }
927
928                 return  api_apply_template("timeline", $type, $data);
929         }
930         api_register_func('api/statuses/home_timeline','api_statuses_home_timeline', true);
931         api_register_func('api/statuses/friends_timeline','api_statuses_home_timeline', true);
932
933         function api_statuses_public_timeline(&$a, $type){
934                 if (api_user()===false) return false;
935
936                 $user_info = api_get_user($a);
937                 // get last newtork messages
938
939
940                 // params
941                 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
942                 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
943                 if ($page<0) $page=0;
944                 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
945                 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
946                 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
947                 $exclude_replies = (x($_REQUEST,'exclude_replies')?1:0);
948                 $conversation_id = (x($_REQUEST,'conversation_id')?$_REQUEST['conversation_id']:0);
949
950                 $start = $page*$count;
951
952                 //$include_entities = (x($_REQUEST,'include_entities')?$_REQUEST['include_entities']:false);
953
954                 if ($max_id > 0)
955                         $sql_extra = 'AND `item`.`id` <= '.intval($max_id);
956                 if ($exclude_replies > 0)
957                         $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
958                 if ($conversation_id > 0)
959                         $sql_extra .= ' AND `item`.`parent` = '.intval($conversation_id);
960
961                 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
962                         `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
963                         `contact`.`network`, `contact`.`thumb`, `contact`.`self`, `contact`.`writable`,
964                         `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`,
965                         `user`.`nickname`, `user`.`hidewall`
966                         FROM `item` LEFT JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
967                         LEFT JOIN `user` ON `user`.`uid` = `item`.`uid`
968                         WHERE `item`.`visible` = 1 AND `item`.`deleted` = 0 and `item`.`moderated` = 0
969                         AND `item`.`allow_cid` = ''  AND `item`.`allow_gid` = ''
970                         AND `item`.`deny_cid`  = '' AND `item`.`deny_gid`  = ''
971                         AND `item`.`private` = 0 AND `item`.`wall` = 1 AND `user`.`hidewall` = 0
972                         AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
973                         $sql_extra
974                         AND `item`.`id`>%d
975                         ORDER BY `received` DESC LIMIT %d, %d ",
976                         intval($since_id),
977                         intval($start),
978                         intval($count));
979
980                 $ret = api_format_items($r,$user_info);
981
982
983                 $data = array('$statuses' => $ret);
984                 switch($type){
985                         case "atom":
986                         case "rss":
987                                 $data = api_rss_extra($a, $data, $user_info);
988                                 break;
989                         case "as":
990                                 $as = api_format_as($a, $ret, $user_info);
991                                 $as['title'] = $a->config['sitename']." Public Timeline";
992                                 $as['link']['url'] = $a->get_baseurl()."/";
993                                 return($as);
994                                 break;
995                 }
996
997                 return  api_apply_template("timeline", $type, $data);
998         }
999         api_register_func('api/statuses/public_timeline','api_statuses_public_timeline', true);
1000
1001         /**
1002          * 
1003          */
1004         function api_statuses_show(&$a, $type){
1005                 if (api_user()===false) return false;
1006
1007                 $user_info = api_get_user($a);
1008
1009                 // params
1010                 $id = intval($a->argv[3]);
1011
1012                 if ($id == 0)
1013                         $id = intval($_REQUEST["id"]);
1014
1015                 logger('API: api_statuses_show: '.$id);
1016
1017                 //$include_entities = (x($_REQUEST,'include_entities')?$_REQUEST['include_entities']:false);
1018                 $conversation = (x($_REQUEST,'conversation')?1:0);
1019
1020                 $sql_extra = '';
1021                 if ($conversation)
1022                         $sql_extra .= " AND `item`.`parent` = %d ORDER BY `received` ASC ";
1023                 else
1024                         $sql_extra .= " AND `item`.`id` = %d";
1025
1026                 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1027                         `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1028                         `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1029                         `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1030                         FROM `item`, `contact`
1031                         WHERE `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1032                         AND `contact`.`id` = `item`.`contact-id`
1033                         AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1034                         $sql_extra",
1035                         intval($id)
1036                 );
1037
1038                 if (!$r)
1039                         die(api_error($a, $type, t("There is no status with this id.")));
1040
1041                 $ret = api_format_items($r,$user_info);
1042
1043                 if ($conversation) {
1044                         $data = array('$statuses' => $ret);
1045                         return api_apply_template("timeline", $type, $data);
1046                 } else {
1047                         $data = array('$status' => $ret[0]);
1048                         /*switch($type){
1049                                 case "atom":
1050                                 case "rss":
1051                                         $data = api_rss_extra($a, $data, $user_info);
1052                         }*/
1053                         return  api_apply_template("status", $type, $data);
1054                 }
1055         }
1056         api_register_func('api/statuses/show','api_statuses_show', true);
1057
1058
1059         /**
1060          * 
1061          */
1062         function api_statuses_repeat(&$a, $type){
1063                 if (api_user()===false) return false;
1064
1065                 $user_info = api_get_user($a);
1066
1067                 // params
1068                 $id = intval($a->argv[3]);
1069
1070                 if ($id == 0)
1071                         $id = intval($_REQUEST["id"]);
1072
1073                 logger('API: api_statuses_repeat: '.$id);
1074
1075                 //$include_entities = (x($_REQUEST,'include_entities')?$_REQUEST['include_entities']:false);
1076
1077                 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`, `contact`.`nick` as `reply_author`,
1078                         `contact`.`name`, `contact`.`photo` as `reply_photo`, `contact`.`url` as `reply_url`, `contact`.`rel`,
1079                         `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1080                         `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1081                         FROM `item`, `contact`
1082                         WHERE `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1083                         AND `contact`.`id` = `item`.`contact-id`
1084                         AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1085                         $sql_extra
1086                         AND `item`.`id`=%d",
1087                         intval($id)
1088                 );
1089
1090                 if ($r[0]['body'] != "") {
1091                         if (!intval(get_config('system','old_share'))) {
1092                                 $post = "[share author='".str_replace("'", "&#039;", $r[0]['reply_author']).
1093                                                 "' profile='".$r[0]['reply_url'].
1094                                                 "' avatar='".$r[0]['reply_photo'].
1095                                                 "' link='".$r[0]['plink']."']";
1096
1097                                 $post .= $r[0]['body'];
1098                                 $post .= "[/share]";
1099                                 $_REQUEST['body'] = $post;
1100                         } else
1101                                 $_REQUEST['body'] = html_entity_decode("&#x2672; ", ENT_QUOTES, 'UTF-8')."[url=".$r[0]['reply_url']."]".$r[0]['reply_author']."[/url] \n".$r[0]['body'];
1102
1103                         $_REQUEST['profile_uid'] = api_user();
1104                         $_REQUEST['type'] = 'wall';
1105                         $_REQUEST['api_source'] = true;
1106
1107                         require_once('mod/item.php');
1108                         item_post($a);
1109                 }
1110
1111                 if ($type == 'xml')
1112                         $ok = "true";
1113                 else
1114                         $ok = "ok";
1115
1116                 return api_apply_template('test', $type, array('$ok' => $ok));
1117         }
1118         api_register_func('api/statuses/retweet','api_statuses_repeat', true);
1119
1120         /**
1121          * 
1122          */
1123         function api_statuses_destroy(&$a, $type){
1124                 if (api_user()===false) return false;
1125
1126                 $user_info = api_get_user($a);
1127
1128                 // params
1129                 $id = intval($a->argv[3]);
1130
1131                 if ($id == 0)
1132                         $id = intval($_REQUEST["id"]);
1133
1134                 logger('API: api_statuses_destroy: '.$id);
1135
1136                 require_once('include/items.php');
1137                 drop_item($id, false);
1138
1139                 if ($type == 'xml')
1140                         $ok = "true";
1141                 else
1142                         $ok = "ok";
1143
1144                 return api_apply_template('test', $type, array('$ok' => $ok));
1145         }
1146         api_register_func('api/statuses/destroy','api_statuses_destroy', true);
1147
1148         /**
1149          * 
1150          * http://developer.twitter.com/doc/get/statuses/mentions
1151          * 
1152          */
1153         function api_statuses_mentions(&$a, $type){
1154                 if (api_user()===false) return false;
1155
1156                 unset($_REQUEST["user_id"]);
1157                 unset($_GET["user_id"]);
1158
1159                 $user_info = api_get_user($a);
1160                 // get last newtork messages
1161
1162
1163                 // params
1164                 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1165                 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1166                 if ($page<0) $page=0;
1167                 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1168                 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1169                 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1170
1171                 $start = $page*$count;
1172
1173                 //$include_entities = (x($_REQUEST,'include_entities')?$_REQUEST['include_entities']:false);
1174
1175                 // Ugly code - should be changed
1176                 $myurl = $a->get_baseurl() . '/profile/'. $a->user['nickname'];
1177                 $myurl = substr($myurl,strpos($myurl,'://')+3);
1178                 //$myurl = str_replace(array('www.','.'),array('','\\.'),$myurl);
1179                 $myurl = str_replace('www.','',$myurl);
1180                 $diasp_url = str_replace('/profile/','/u/',$myurl);
1181
1182                 $sql_extra .= sprintf(" AND `item`.`parent` IN (SELECT distinct(`parent`) from item where `author-link` IN ('https://%s', 'http://%s') OR `mention`)",
1183                         dbesc(protect_sprintf($myurl)),
1184                         dbesc(protect_sprintf($myurl))
1185                 );
1186
1187                 if ($max_id > 0)
1188                         $sql_extra .= ' AND `item`.`id` <= '.intval($max_id);
1189
1190                 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1191                         `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1192                         `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1193                         `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1194                         FROM `item`, `contact`
1195                         WHERE `item`.`uid` = %d
1196                         AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1197                         AND `contact`.`id` = `item`.`contact-id`
1198                         AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1199                         $sql_extra
1200                         AND `item`.`id`>%d
1201                         ORDER BY `item`.`received` DESC LIMIT %d ,%d ",
1202                         //intval($user_info['uid']),
1203                         intval(api_user()),
1204                         intval($since_id),
1205                         intval($start), intval($count)
1206                 );
1207
1208                 $ret = api_format_items($r,$user_info);
1209
1210
1211                 $data = array('$statuses' => $ret);
1212                 switch($type){
1213                         case "atom":
1214                         case "rss":
1215                                 $data = api_rss_extra($a, $data, $user_info);
1216                                 break;
1217                         case "as":
1218                                 $as = api_format_as($a, $ret, $user_info);
1219                                 $as["title"] = $a->config['sitename']." Mentions";
1220                                 $as['link']['url'] = $a->get_baseurl()."/";
1221                                 return($as);
1222                                 break;
1223                 }
1224
1225                 return  api_apply_template("timeline", $type, $data);
1226         }
1227         api_register_func('api/statuses/mentions','api_statuses_mentions', true);
1228         api_register_func('api/statuses/replies','api_statuses_mentions', true);
1229
1230
1231         function api_statuses_user_timeline(&$a, $type){
1232                 if (api_user()===false) return false;
1233
1234                 $user_info = api_get_user($a);
1235                 // get last network messages
1236
1237                 logger("api_statuses_user_timeline: api_user: ". api_user() .
1238                            "\nuser_info: ".print_r($user_info, true) .
1239                            "\n_REQUEST:  ".print_r($_REQUEST, true),
1240                            LOGGER_DEBUG);
1241
1242                 // params
1243                 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1244                 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1245                 if ($page<0) $page=0;
1246                 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1247                 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1248                 $exclude_replies = (x($_REQUEST,'exclude_replies')?1:0);
1249                 $conversation_id = (x($_REQUEST,'conversation_id')?$_REQUEST['conversation_id']:0);
1250
1251                 $start = $page*$count;
1252
1253                 $sql_extra = '';
1254                 if ($user_info['self']==1)
1255                         $sql_extra .= " AND `item`.`wall` = 1 ";
1256
1257                 if ($exclude_replies > 0)
1258                         $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
1259                 if ($conversation_id > 0)
1260                         $sql_extra .= ' AND `item`.`parent` = '.intval($conversation_id);
1261
1262                 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1263                         `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1264                         `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1265                         `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1266                         FROM `item`, `contact`
1267                         WHERE `item`.`uid` = %d
1268                         AND `item`.`contact-id` = %d
1269                         AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1270                         AND `contact`.`id` = `item`.`contact-id`
1271                         AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1272                         $sql_extra
1273                         AND `item`.`id`>%d
1274                         ORDER BY `item`.`received` DESC LIMIT %d ,%d ",
1275                         intval(api_user()),
1276                         intval($user_info['cid']),
1277                         intval($since_id),
1278                         intval($start), intval($count)
1279                 );
1280
1281                 $ret = api_format_items($r,$user_info, true);
1282
1283                 $data = array('$statuses' => $ret);
1284                 switch($type){
1285                         case "atom":
1286                         case "rss":
1287                                 $data = api_rss_extra($a, $data, $user_info);
1288                 }
1289
1290                 return  api_apply_template("timeline", $type, $data);
1291         }
1292
1293         api_register_func('api/statuses/user_timeline','api_statuses_user_timeline', true);
1294
1295
1296         function api_favorites(&$a, $type){
1297                 global $called_api;
1298
1299                 if (api_user()===false) return false;
1300
1301                 $called_api= array();
1302
1303                 $user_info = api_get_user($a);
1304
1305                 // in friendica starred item are private
1306                 // return favorites only for self
1307                 logger('api_favorites: self:' . $user_info['self']);
1308
1309                 if ($user_info['self']==0) {
1310                         $ret = array();
1311                 } else {
1312
1313                         // params
1314                         $count = (x($_GET,'count')?$_GET['count']:20);
1315                         $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1316                         if ($page<0) $page=0;
1317
1318                         $start = $page*$count;
1319
1320                         $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1321                                 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1322                                 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1323                                 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1324                                 FROM `item`, `contact`
1325                                 WHERE `item`.`uid` = %d
1326                                 AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1327                                 AND `item`.`starred` = 1
1328                                 AND `contact`.`id` = `item`.`contact-id`
1329                                 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1330                                 $sql_extra
1331                                 ORDER BY `item`.`received` DESC LIMIT %d ,%d ",
1332                                 //intval($user_info['uid']),
1333                                 intval(api_user()),
1334                                 intval($start), intval($count)
1335                         );
1336
1337                         $ret = api_format_items($r,$user_info);
1338
1339                 }
1340
1341                 $data = array('$statuses' => $ret);
1342                 switch($type){
1343                         case "atom":
1344                         case "rss":
1345                                 $data = api_rss_extra($a, $data, $user_info);
1346                 }
1347
1348                 return  api_apply_template("timeline", $type, $data);
1349         }
1350
1351         api_register_func('api/favorites','api_favorites', true);
1352
1353         function api_format_as($a, $ret, $user_info) {
1354
1355                 $as = array();
1356                 $as['title'] = $a->config['sitename']." Public Timeline";
1357                 $items = array();
1358                 foreach ($ret as $item) {
1359                         $singleitem["actor"]["displayName"] = $item["user"]["name"];
1360                         $singleitem["actor"]["id"] = $item["user"]["contact_url"];
1361                         $avatar[0]["url"] = $item["user"]["profile_image_url"];
1362                         $avatar[0]["rel"] = "avatar";
1363                         $avatar[0]["type"] = "";
1364                         $avatar[0]["width"] = 96;
1365                         $avatar[0]["height"] = 96;
1366                         $avatar[1]["url"] = $item["user"]["profile_image_url"];
1367                         $avatar[1]["rel"] = "avatar";
1368                         $avatar[1]["type"] = "";
1369                         $avatar[1]["width"] = 48;
1370                         $avatar[1]["height"] = 48;
1371                         $avatar[2]["url"] = $item["user"]["profile_image_url"];
1372                         $avatar[2]["rel"] = "avatar";
1373                         $avatar[2]["type"] = "";
1374                         $avatar[2]["width"] = 24;
1375                         $avatar[2]["height"] = 24;
1376                         $singleitem["actor"]["avatarLinks"] = $avatar;
1377
1378                         $singleitem["actor"]["image"]["url"] = $item["user"]["profile_image_url"];
1379                         $singleitem["actor"]["image"]["rel"] = "avatar";
1380                         $singleitem["actor"]["image"]["type"] = "";
1381                         $singleitem["actor"]["image"]["width"] = 96;
1382                         $singleitem["actor"]["image"]["height"] = 96;
1383                         $singleitem["actor"]["type"] = "person";
1384                         $singleitem["actor"]["url"] = $item["person"]["contact_url"];
1385                         $singleitem["actor"]["statusnet:profile_info"]["local_id"] = $item["user"]["id"];
1386                         $singleitem["actor"]["statusnet:profile_info"]["following"] = $item["user"]["following"] ? "true" : "false";
1387                         $singleitem["actor"]["statusnet:profile_info"]["blocking"] = "false";
1388                         $singleitem["actor"]["contact"]["preferredUsername"] = $item["user"]["screen_name"];
1389                         $singleitem["actor"]["contact"]["displayName"] = $item["user"]["name"];
1390                         $singleitem["actor"]["contact"]["addresses"] = "";
1391
1392                         $singleitem["body"] = $item["text"];
1393                         $singleitem["object"]["displayName"] = $item["text"];
1394                         $singleitem["object"]["id"] = $item["url"];
1395                         $singleitem["object"]["type"] = "note";
1396                         $singleitem["object"]["url"] = $item["url"];
1397                         //$singleitem["context"] =;
1398                         $singleitem["postedTime"] = date("c", strtotime($item["published"]));
1399                         $singleitem["provider"]["objectType"] = "service";
1400                         $singleitem["provider"]["displayName"] = "Test";
1401                         $singleitem["provider"]["url"] = "http://test.tld";
1402                         $singleitem["title"] = $item["text"];
1403                         $singleitem["verb"] = "post";
1404                         $singleitem["statusnet:notice_info"]["local_id"] = $item["id"];
1405                                 $singleitem["statusnet:notice_info"]["source"] = $item["source"];
1406                                 $singleitem["statusnet:notice_info"]["favorite"] = "false";
1407                                 $singleitem["statusnet:notice_info"]["repeated"] = "false";
1408                                 //$singleitem["original"] = $item;
1409                                 $items[] = $singleitem;
1410                 }
1411                 $as['items'] = $items;
1412                 $as['link']['url'] = $a->get_baseurl()."/".$user_info["screen_name"]."/all";
1413                 $as['link']['rel'] = "alternate";
1414                 $as['link']['type'] = "text/html";
1415                 return($as);
1416         }
1417
1418         function api_format_messages($item, $recipient, $sender) {
1419                 // standard meta information
1420                 $ret=Array(
1421                                 'id'                    => $item['id'],
1422                                 'sender_id'             => $sender['id'] ,
1423                                 'text'                  => "",
1424                                 'recipient_id'          => $recipient['id'],
1425                                 'created_at'            => api_date($item['created']),
1426                                 'sender_screen_name'    => $sender['screen_name'],
1427                                 'recipient_screen_name' => $recipient['screen_name'],
1428                                 'sender'                => $sender,
1429                                 'recipient'             => $recipient,
1430                 );
1431
1432                 // "cid", "uid" and "self" are only needed for some internal stuff, so remove it from here
1433                 unset($ret["sender"]["cid"]);
1434                 unset($ret["sender"]["uid"]);
1435                 unset($ret["sender"]["self"]);
1436                 unset($ret["recipient"]["cid"]);
1437                 unset($ret["recipient"]["uid"]);
1438                 unset($ret["recipient"]["self"]);
1439
1440                 //don't send title to regular StatusNET requests to avoid confusing these apps
1441                 if (x($_GET, 'getText')) {
1442                         $ret['title'] = $item['title'] ;
1443                         if ($_GET["getText"] == "html") {
1444                                 $ret['text'] = bbcode($item['body'], false, false);
1445                         }
1446                         elseif ($_GET["getText"] == "plain") {
1447                                 //$ret['text'] = html2plain(bbcode($item['body'], false, false, true), 0);
1448                                 $ret['text'] = trim(html2plain(bbcode($item['body'], false, false, 2), 0));
1449                         }
1450                 }
1451                 else {
1452                         $ret['text'] = $item['title']."\n".html2plain(bbcode($item['body'], false, false, 2), 0);
1453                 }
1454                 if (isset($_GET["getUserObjects"]) && $_GET["getUserObjects"] == "false") {
1455                         unset($ret['sender']);
1456                         unset($ret['recipient']);
1457                 }
1458
1459                 return $ret;
1460         }
1461
1462         function api_format_items($r,$user_info, $filter_user = false) {
1463
1464                 $a = get_app();
1465                 $ret = Array();
1466
1467                 foreach($r as $item) {
1468                         localize_item($item);
1469                         $status_user = api_item_get_user($a,$item);
1470
1471                         // Look if the posts are matching if they should be filtered by user id
1472                         if ($filter_user AND ($status_user["id"] != $user_info["id"]))
1473                                 continue;
1474
1475                         if ($item['thr-parent'] != $item['uri']) {
1476                                 $r = q("SELECT id FROM item WHERE uid=%d AND uri='%s' LIMIT 1",
1477                                         intval(api_user()),
1478                                         dbesc($item['thr-parent']));
1479                                 if ($r)
1480                                         $in_reply_to_status_id = $r[0]['id'];
1481                                 else
1482                                         $in_reply_to_status_id = $item['parent'];
1483
1484                                 $in_reply_to_screen_name = NULL;
1485                                 $in_reply_to_user_id = NULL;
1486
1487                                 $r = q("SELECT `author-link` FROM item WHERE uid=%d AND id=%d LIMIT 1",
1488                                         intval(api_user()),
1489                                         intval($in_reply_to_status_id));
1490                                 if ($r) {
1491                                         $r = q("SELECT * FROM unique_contacts WHERE `url` = '%s'", dbesc(normalise_link($r[0]['author-link'])));
1492
1493                                         if ($r) {
1494                                                 $in_reply_to_screen_name = $r[0]['name'];
1495                                                 $in_reply_to_user_id = $r[0]['id'];
1496                                         }
1497                                 }
1498                         } else {
1499                                 $in_reply_to_screen_name = NULL;
1500                                 $in_reply_to_user_id = NULL;
1501                                 $in_reply_to_status_id = NULL;
1502                         }
1503
1504                         // Workaround for ostatus messages where the title is identically to the body
1505                         $statusbody = trim(html2plain(bbcode($item['body'], false, false, 2), 0));
1506
1507                         $statustitle = trim($item['title']);
1508
1509                         if (($statustitle != '') and (strpos($statusbody, $statustitle) !== false))
1510                                 $statustext = trim($statusbody);
1511                         else
1512                                 $statustext = trim($statustitle."\n\n".$statusbody);
1513
1514                         if (($item["network"] == NETWORK_FEED) and (strlen($statustext)> 1000))
1515                                 $statustext = substr($statustext, 0, 1000)."... \n".$item["plink"];
1516
1517                         $status = array(
1518                                 'text'          => $statustext,
1519                                 'truncated' => False,
1520                                 'created_at'=> api_date($item['created']),
1521                                 'in_reply_to_status_id' => $in_reply_to_status_id,
1522                                 'source'    => (($item['app']) ? $item['app'] : 'web'),
1523                                 'id'            => intval($item['id']),
1524                                 'in_reply_to_user_id' => $in_reply_to_user_id,
1525                                 'in_reply_to_screen_name' => $in_reply_to_screen_name,
1526                                 'geo' => NULL,
1527                                 'favorited' => $item['starred'] ? true : false,
1528                                 //'attachments' => array(),
1529                                 'user' =>  $status_user ,
1530                                 'statusnet_html'                => trim(bbcode($item['body'], false, false)),
1531                                 'statusnet_conversation_id'     => $item['parent'],
1532                         );
1533
1534                         if (($item['item_network'] != "") AND ($status["source"] == 'web'))
1535                                 $status["source"] = network_to_name($item['item_network']);
1536                         else if (($item['item_network'] != "") AND (network_to_name($item['item_network']) != $status["source"]))
1537                                 $status["source"] = trim($status["source"].' ('.network_to_name($item['item_network']).')');
1538
1539
1540                         // Retweets are only valid for top postings
1541                         if (($item['owner-link'] != $item['author-link']) AND ($item["id"] == $item["parent"])) {
1542                                 $retweeted_status = $status;
1543                                 $retweeted_status["user"] = api_get_user($a,$item["author-link"]);
1544
1545                                 $status["retweeted_status"] = $retweeted_status;
1546                         }
1547
1548                         // "cid", "uid" and "self" are only needed for some internal stuff, so remove it from here
1549                         unset($status["user"]["cid"]);
1550                         unset($status["user"]["uid"]);
1551                         unset($status["user"]["self"]);
1552
1553                         // 'geo' => array('type' => 'Point',
1554                         //                   'coordinates' => array((float) $notice->lat,
1555                         //                                          (float) $notice->lon));
1556
1557                         // Seesmic doesn't like the following content
1558                         // completely disabled to make friendica totally compatible to the statusnet API
1559                         /*if ($_SERVER['HTTP_USER_AGENT'] != 'Seesmic') {
1560                                 $status2 = array(
1561                                         'updated'   => api_date($item['edited']),
1562                                         'published' => api_date($item['created']),
1563                                         'message_id' => $item['uri'],
1564                                         'url'           => ($item['plink']!=''?$item['plink']:$item['author-link']),
1565                                         'coordinates' => $item['coord'],
1566                                         'place' => $item['location'],
1567                                         'contributors' => '',
1568                                         'annotations'  => '',
1569                                         'entities'  => '',
1570                                         'objecttype' => (($item['object-type']) ? $item['object-type'] : ACTIVITY_OBJ_NOTE),
1571                                         'verb' => (($item['verb']) ? $item['verb'] : ACTIVITY_POST),
1572                                         'self' => $a->get_baseurl()."/api/statuses/show/".$item['id'].".".$type,
1573                                         'edit' => $a->get_baseurl()."/api/statuses/show/".$item['id'].".".$type,
1574                                 );
1575
1576                                 $status = array_merge($status, $status2);
1577                         }*/
1578
1579                         $ret[] = $status;
1580                 };
1581                 return $ret;
1582         }
1583
1584
1585         function api_account_rate_limit_status(&$a,$type) {
1586
1587                 $hash = array(
1588                           'reset_time_in_seconds' => strtotime('now + 1 hour'),
1589                           'remaining_hits' => (string) 150,
1590                           'hourly_limit' => (string) 150,
1591                           'reset_time' => api_date(datetime_convert('UTC','UTC','now + 1 hour',ATOM_TIME)),
1592                 );
1593                 if ($type == "xml")
1594                         $hash['resettime_in_seconds'] = $hash['reset_time_in_seconds'];
1595
1596                 return api_apply_template('ratelimit', $type, array('$hash' => $hash));
1597
1598         }
1599         api_register_func('api/account/rate_limit_status','api_account_rate_limit_status',true);
1600
1601         function api_help_test(&$a,$type) {
1602
1603                 if ($type == 'xml')
1604                         $ok = "true";
1605                 else
1606                         $ok = "ok";
1607
1608                 return api_apply_template('test', $type, array('$ok' => $ok));
1609
1610         }
1611         api_register_func('api/help/test','api_help_test',false);
1612
1613         /**
1614          *  https://dev.twitter.com/docs/api/1/get/statuses/friends 
1615          *  This function is deprecated by Twitter
1616          *  returns: json, xml 
1617          **/
1618         function api_statuses_f(&$a, $type, $qtype) {
1619                 if (api_user()===false) return false;
1620                 $user_info = api_get_user($a);
1621
1622
1623                 // friends and followers only for self
1624                 if ($user_info['self']==0){
1625                         return false;
1626                 }
1627
1628                 if (x($_GET,'cursor') && $_GET['cursor']=='undefined'){
1629                         /* this is to stop Hotot to load friends multiple times
1630                         *  I'm not sure if I'm missing return something or
1631                         *  is a bug in hotot. Workaround, meantime
1632                         */
1633
1634                         /*$ret=Array();
1635                         return array('$users' => $ret);*/
1636                         return false;
1637                 }
1638
1639                 if($qtype == 'friends')
1640                         $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
1641                 if($qtype == 'followers')
1642                         $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
1643
1644                 $r = q("SELECT id FROM `contact` WHERE `uid` = %d AND `self` = 0 AND `blocked` = 0 AND `pending` = 0 $sql_extra",
1645                         intval(api_user())
1646                 );
1647
1648                 $ret = array();
1649                 foreach($r as $cid){
1650                         $user =  api_get_user($a, $cid['id']);
1651                         // "cid", "uid" and "self" are only needed for some internal stuff, so remove it from here
1652                         unset($user["cid"]);
1653                         unset($user["uid"]);
1654                         unset($user["self"]);
1655
1656                         if ($user)
1657                                 $ret[] = $user;
1658                 }
1659
1660
1661                 return array('$users' => $ret);
1662
1663         }
1664         function api_statuses_friends(&$a, $type){
1665                 $data =  api_statuses_f($a,$type,"friends");
1666                 if ($data===false) return false;
1667                 return  api_apply_template("friends", $type, $data);
1668         }
1669         function api_statuses_followers(&$a, $type){
1670                 $data = api_statuses_f($a,$type,"followers");
1671                 if ($data===false) return false;
1672                 return  api_apply_template("friends", $type, $data);
1673         }
1674         api_register_func('api/statuses/friends','api_statuses_friends',true);
1675         api_register_func('api/statuses/followers','api_statuses_followers',true);
1676
1677
1678
1679
1680
1681
1682         function api_statusnet_config(&$a,$type) {
1683                 $name = $a->config['sitename'];
1684                 $server = $a->get_hostname();
1685                 $logo = $a->get_baseurl() . '/images/friendica-64.png';
1686                 $email = $a->config['admin_email'];
1687                 $closed = (($a->config['register_policy'] == REGISTER_CLOSED) ? 'true' : 'false');
1688                 $private = (($a->config['system']['block_public']) ? 'true' : 'false');
1689                 $textlimit = (string) (($a->config['max_import_size']) ? $a->config['max_import_size'] : 200000);
1690                 if($a->config['api_import_size'])
1691                         $texlimit = string($a->config['api_import_size']);
1692                 $ssl = (($a->config['system']['have_ssl']) ? 'true' : 'false');
1693                 $sslserver = (($ssl === 'true') ? str_replace('http:','https:',$a->get_baseurl()) : '');
1694
1695                 $config = array(
1696                         'site' => array('name' => $name,'server' => $server, 'theme' => 'default', 'path' => '',
1697                                 'logo' => $logo, 'fancy' => true, 'language' => 'en', 'email' => $email, 'broughtby' => '',
1698                                 'broughtbyurl' => '', 'timezone' => 'UTC', 'closed' => $closed, 'inviteonly' => false,
1699                                 'private' => $private, 'textlimit' => $textlimit, 'sslserver' => $sslserver, 'ssl' => $ssl,
1700                                 'shorturllength' => '30',
1701                                 'friendica' => array(
1702                                                 'FRIENDICA_PLATFORM' => FRIENDICA_PLATFORM,
1703                                                 'FRIENDICA_VERSION' => FRIENDICA_VERSION,
1704                                                 'DFRN_PROTOCOL_VERSION' => DFRN_PROTOCOL_VERSION,
1705                                                 'DB_UPDATE_VERSION' => DB_UPDATE_VERSION
1706                                                 )
1707                         ),
1708                 );
1709
1710                 return api_apply_template('config', $type, array('$config' => $config));
1711
1712         }
1713         api_register_func('api/statusnet/config','api_statusnet_config',false);
1714
1715         function api_statusnet_version(&$a,$type) {
1716
1717                 // liar
1718
1719                 if($type === 'xml') {
1720                         header("Content-type: application/xml");
1721                         echo '<?xml version="1.0" encoding="UTF-8"?>' . "\r\n" . '<version>0.9.7</version>' . "\r\n";
1722                         killme();
1723                 }
1724                 elseif($type === 'json') {
1725                         header("Content-type: application/json");
1726                         echo '"0.9.7"';
1727                         killme();
1728                 }
1729         }
1730         api_register_func('api/statusnet/version','api_statusnet_version',false);
1731
1732
1733         function api_ff_ids(&$a,$type,$qtype) {
1734                 if(! api_user())
1735                         return false;
1736
1737                 if($qtype == 'friends')
1738                         $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
1739                 if($qtype == 'followers')
1740                         $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
1741
1742
1743                 $r = q("SELECT unique_contacts.id FROM contact, unique_contacts WHERE contact.nurl = unique_contacts.url AND `uid` = %d AND `self` = 0 AND `blocked` = 0 AND `pending` = 0 $sql_extra",
1744                         intval(api_user())
1745                 );
1746
1747                 if(is_array($r)) {
1748
1749                         if($type === 'xml') {
1750                                 header("Content-type: application/xml");
1751                                 echo '<?xml version="1.0" encoding="UTF-8"?>' . "\r\n" . '<ids>' . "\r\n";
1752                                 foreach($r as $rr)
1753                                         echo '<id>' . $rr['id'] . '</id>' . "\r\n";
1754                                 echo '</ids>' . "\r\n";
1755                                 killme();
1756                         }
1757                         elseif($type === 'json') {
1758                                 $ret = array();
1759                                 header("Content-type: application/json");
1760                                 foreach($r as $rr) $ret[] = $rr['id'];
1761                                 echo json_encode($ret);
1762                                 killme();
1763                         }
1764                 }
1765         }
1766
1767         function api_friends_ids(&$a,$type) {
1768                 api_ff_ids($a,$type,'friends');
1769         }
1770         function api_followers_ids(&$a,$type) {
1771                 api_ff_ids($a,$type,'followers');
1772         }
1773         api_register_func('api/friends/ids','api_friends_ids',true);
1774         api_register_func('api/followers/ids','api_followers_ids',true);
1775
1776
1777         function api_direct_messages_new(&$a, $type) {
1778                 if (api_user()===false) return false;
1779
1780                 if (!x($_POST, "text") OR (!x($_POST,"screen_name") AND !x($_POST,"user_id"))) return;
1781
1782                 $sender = api_get_user($a);
1783
1784                 require_once("include/message.php");
1785
1786                 if ($_POST['screen_name']) {
1787                         $r = q("SELECT `id`, `nurl` FROM `contact` WHERE `uid`=%d AND `nick`='%s'",
1788                                         intval(api_user()),
1789                                         dbesc($_POST['screen_name']));
1790
1791                         $recipient = api_get_user($a, $r[0]['nurl']);
1792                 } else
1793                         $recipient = api_get_user($a, $_POST['user_id']);
1794
1795                 $replyto = '';
1796                 $sub     = '';
1797                 if (x($_REQUEST,'replyto')) {
1798                         $r = q('SELECT `parent-uri`, `title` FROM `mail` WHERE `uid`=%d AND `id`=%d',
1799                                         intval(api_user()),
1800                                         intval($_REQUEST['replyto']));
1801                         $replyto = $r[0]['parent-uri'];
1802                         $sub     = $r[0]['title'];
1803                 }
1804                 else {
1805                         if (x($_REQUEST,'title')) {
1806                                 $sub = $_REQUEST['title'];
1807                         }
1808                         else {
1809                                 $sub = ((strlen($_POST['text'])>10)?substr($_POST['text'],0,10)."...":$_POST['text']);
1810                         }
1811                 }
1812
1813                 $id = send_message($recipient['cid'], $_POST['text'], $sub, $replyto);
1814
1815                 if ($id>-1) {
1816                         $r = q("SELECT * FROM `mail` WHERE id=%d", intval($id));
1817                         $ret = api_format_messages($r[0], $recipient, $sender);
1818
1819                 } else {
1820                         $ret = array("error"=>$id);
1821                 }
1822
1823                 $data = Array('$messages'=>$ret);
1824
1825                 switch($type){
1826                         case "atom":
1827                         case "rss":
1828                                 $data = api_rss_extra($a, $data, $user_info);
1829                 }
1830
1831                 return  api_apply_template("direct_messages", $type, $data);
1832
1833         }
1834         api_register_func('api/direct_messages/new','api_direct_messages_new',true);
1835
1836         function api_direct_messages_box(&$a, $type, $box) {
1837                 if (api_user()===false) return false;
1838
1839                 unset($_REQUEST["user_id"]);
1840                 unset($_GET["user_id"]);
1841
1842                 $user_info = api_get_user($a);
1843
1844                 // params
1845                 $count = (x($_GET,'count')?$_GET['count']:20);
1846                 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1847                 if ($page<0) $page=0;
1848
1849                 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1850
1851                 $start = $page*$count;
1852
1853                 //$profile_url = $a->get_baseurl() . '/profile/' . $a->user['nickname'];
1854                 $profile_url = $user_info["url"];
1855
1856                 if ($box=="sentbox") {
1857                         $sql_extra = "`mail`.`from-url`='".dbesc( $profile_url )."'";
1858                 }
1859                 elseif ($box=="conversation") {
1860                         $sql_extra = "`mail`.`parent-uri`='".dbesc( $_GET["uri"] )  ."'";
1861                 }
1862                 elseif ($box=="all") {
1863                         $sql_extra = "true";
1864                 }
1865                 elseif ($box=="inbox") {
1866                         $sql_extra = "`mail`.`from-url`!='".dbesc( $profile_url )."'";
1867                 }
1868
1869                 $r = q("SELECT `mail`.*, `contact`.`nurl` AS `contact-url` FROM `mail`,`contact` WHERE `mail`.`contact-id` = `contact`.`id` AND `mail`.`uid`=%d AND $sql_extra AND `mail`.`id` > %d ORDER BY `mail`.`created` DESC LIMIT %d,%d",
1870                                 intval(api_user()),
1871                                 intval($since_id),
1872                                 intval($start), intval($count)
1873                 );
1874
1875                 $ret = Array();
1876                 foreach($r as $item) {
1877                         if ($box == "inbox" || $item['from-url'] != $profile_url){
1878                                 $recipient = $user_info;
1879                                 $sender = api_get_user($a,normalise_link($item['contact-url']));
1880                         }
1881                         elseif ($box == "sentbox" || $item['from-url'] != $profile_url){
1882                                 $recipient = api_get_user($a,normalise_link($item['contact-url']));
1883                                 $sender = $user_info;
1884
1885                         }
1886
1887                         $ret[]=api_format_messages($item, $recipient, $sender);
1888                 }
1889
1890
1891                 $data = array('$messages' => $ret);
1892                 switch($type){
1893                         case "atom":
1894                         case "rss":
1895                                 $data = api_rss_extra($a, $data, $user_info);
1896                 }
1897
1898                 return  api_apply_template("direct_messages", $type, $data);
1899
1900         }
1901
1902         function api_direct_messages_sentbox(&$a, $type){
1903                 return api_direct_messages_box($a, $type, "sentbox");
1904         }
1905         function api_direct_messages_inbox(&$a, $type){
1906                 return api_direct_messages_box($a, $type, "inbox");
1907         }
1908         function api_direct_messages_all(&$a, $type){
1909                 return api_direct_messages_box($a, $type, "all");
1910         }
1911         function api_direct_messages_conversation(&$a, $type){
1912                 return api_direct_messages_box($a, $type, "conversation");
1913         }
1914         api_register_func('api/direct_messages/conversation','api_direct_messages_conversation',true);
1915         api_register_func('api/direct_messages/all','api_direct_messages_all',true);
1916         api_register_func('api/direct_messages/sent','api_direct_messages_sentbox',true);
1917         api_register_func('api/direct_messages','api_direct_messages_inbox',true);
1918
1919
1920
1921         function api_oauth_request_token(&$a, $type){
1922                 try{
1923                         $oauth = new FKOAuth1();
1924                         $r = $oauth->fetch_request_token(OAuthRequest::from_request());
1925                 }catch(Exception $e){
1926                         echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage()); killme();
1927                 }
1928                 echo $r;
1929                 killme();
1930         }
1931         function api_oauth_access_token(&$a, $type){
1932                 try{
1933                         $oauth = new FKOAuth1();
1934                         $r = $oauth->fetch_access_token(OAuthRequest::from_request());
1935                 }catch(Exception $e){
1936                         echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage()); killme();
1937                 }
1938                 echo $r;
1939                 killme();
1940         }
1941
1942         api_register_func('api/oauth/request_token', 'api_oauth_request_token', false);
1943         api_register_func('api/oauth/access_token', 'api_oauth_access_token', false);
1944
1945 /*
1946 Not implemented by now:
1947 favorites
1948 favorites/create
1949 favorites/destroy
1950 statuses/retweets_of_me
1951 friendships/create
1952 friendships/destroy
1953 friendships/exists
1954 friendships/show
1955 account/update_location
1956 account/update_profile_background_image
1957 account/update_profile_image
1958 blocks/create
1959 blocks/destroy
1960
1961 Not implemented in status.net:
1962 statuses/retweeted_to_me
1963 statuses/retweeted_by_me
1964 direct_messages/destroy
1965 account/end_session
1966 account/update_delivery_device
1967 notifications/follow
1968 notifications/leave
1969 blocks/exists
1970 blocks/blocking
1971 lists
1972 */
1973