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