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