]> git.mxchange.org Git - friendica.git/blob - include/api.php
quattro: add "view in context" link in search results
[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         /* 
7          * Twitter-Like API
8          *  
9          */
10
11         $API = Array();
12         $called_api = Null; 
13
14         function api_date($str){
15                 //Wed May 23 06:01:13 +0000 2007
16                 return datetime_convert('UTC', 'UTC', $str, "D M d H:i:s +0000 Y" );
17         }
18          
19         
20         function api_register_func($path, $func, $auth=false){
21                 global $API;
22                 $API[$path] = array('func'=>$func,
23                                                         'auth'=>$auth);
24         }
25         
26         /**
27          * Simple HTTP Login
28          */
29
30         function api_login(&$a){
31                 // login with oauth
32                 try{
33                         $oauth = new FKOAuth1();
34                         list($consumer,$token) = $oauth->verify_request(OAuthRequest::from_request());
35                         if (!is_null($token)){
36                                 $oauth->loginUser($token->uid);
37                                 call_hooks('logged_in', $a->user);
38                                 return;
39                         }
40                         echo __file__.__line__.__function__."<pre>"; var_dump($consumer, $token); die();
41                 }catch(Exception $e){
42                         logger(__file__.__line__.__function__."\n".$e);
43                         //die(__file__.__line__.__function__."<pre>".$e); die();
44                 }
45
46                 
47                 
48                 // workaround for HTTP-auth in CGI mode
49                 if(x($_SERVER,'REDIRECT_REMOTE_USER')) {
50                         $userpass = base64_decode(substr($_SERVER["REDIRECT_REMOTE_USER"],6)) ;
51                         if(strlen($userpass)) {
52                                 list($name, $password) = explode(':', $userpass);
53                                 $_SERVER['PHP_AUTH_USER'] = $name;
54                                 $_SERVER['PHP_AUTH_PW'] = $password;
55                         }
56                 }
57
58                 if (!isset($_SERVER['PHP_AUTH_USER'])) {
59                    logger('API_login: ' . print_r($_SERVER,true), LOGGER_DEBUG);
60                     header('WWW-Authenticate: Basic realm="Friendica"');
61                     header('HTTP/1.0 401 Unauthorized');
62                     die('This api requires login');
63                 }
64                 
65                 $user = $_SERVER['PHP_AUTH_USER'];
66                 $encrypted = hash('whirlpool',trim($_SERVER['PHP_AUTH_PW']));
67                 
68                 
69                         /**
70                          *  next code from mod/auth.php. needs better solution
71                          */
72                         
73                 // process normal login request
74
75                 $r = q("SELECT * FROM `user` WHERE ( `email` = '%s' OR `nickname` = '%s' ) 
76                         AND `password` = '%s' AND `blocked` = 0 AND `account_expired` = 0 AND `verified` = 1 LIMIT 1",
77                         dbesc(trim($user)),
78                         dbesc(trim($user)),
79                         dbesc($encrypted)
80                 );
81                 if(count($r)){
82                         $record = $r[0];
83                 } else {
84                    logger('API_login failure: ' . print_r($_SERVER,true), LOGGER_DEBUG);
85                     header('WWW-Authenticate: Basic realm="Friendika"');
86                     header('HTTP/1.0 401 Unauthorized');
87                     die('This api requires login');
88                 }
89
90                 require_once('include/security.php');
91                 authenticate_success($record);
92
93                 call_hooks('logged_in', $a->user);
94
95         }
96         
97         /**************************
98          *  MAIN API ENTRY POINT  *
99          **************************/
100         function api_call(&$a){
101                 GLOBAL $API, $called_api;
102                 foreach ($API as $p=>$info){
103                         if (strpos($a->query_string, $p)===0){
104                                 $called_api= explode("/",$p);
105                                 //unset($_SERVER['PHP_AUTH_USER']);
106                                 if ($info['auth']===true && local_user()===false) {
107                                                 api_login($a);
108                                 }
109
110                                 load_contact_links(local_user());
111
112                                 logger('API call for ' . $a->user['username'] . ': ' . $a->query_string);               
113                                 logger('API parameters: ' . print_r($_REQUEST,true));
114                                 $type="json";           
115                                 if (strpos($a->query_string, ".xml")>0) $type="xml";
116                                 if (strpos($a->query_string, ".json")>0) $type="json";
117                                 if (strpos($a->query_string, ".rss")>0) $type="rss";
118                                 if (strpos($a->query_string, ".atom")>0) $type="atom";                          
119                                 
120                                 $r = call_user_func($info['func'], $a, $type);
121                                 if ($r===false) return;
122
123                                 switch($type){
124                                         case "xml":
125                                                 $r = mb_convert_encoding($r, "UTF-8",mb_detect_encoding($r));
126                                                 header ("Content-Type: text/xml");
127                                                 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
128                                                 break;
129                                         case "json": 
130                                                 //header ("Content-Type: application/json");  
131                                                 foreach($r as $rr)
132                                                     return json_encode($rr);
133                                                 break;
134                                         case "rss":
135                                                 header ("Content-Type: application/rss+xml");
136                                                 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
137                                                 break;
138                                         case "atom":
139                                                 header ("Content-Type: application/atom+xml");
140                                                 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
141                                                 break;
142                                                 
143                                 }
144                                 //echo "<pre>"; var_dump($r); die();
145                         }
146                 }
147                 $r = '<status><error>not implemented</error></status>';
148                 switch($type){
149                         case "xml":
150                                 header ("Content-Type: text/xml");
151                                 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
152                                 break;
153                         case "json": 
154                                 header ("Content-Type: application/json");  
155                             return json_encode(array('error' => 'not implemented'));
156                                 break;
157                         case "rss":
158                                 header ("Content-Type: application/rss+xml");
159                                 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
160                                 break;
161                         case "atom":
162                                 header ("Content-Type: application/atom+xml");
163                                 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
164                                 break;
165                                 
166                 }
167         }
168
169         /**
170          * RSS extra info
171          */
172         function api_rss_extra(&$a, $arr, $user_info){
173                 if (is_null($user_info)) $user_info = api_get_user($a);
174                 $arr['$user'] = $user_info;
175                 $arr['$rss'] = array(
176                         'alternate' => $user_info['url'],
177                         'self' => $a->get_baseurl(). "/". $a->query_string,
178                         'base' => $a->get_baseurl(),
179                         'updated' => api_date(null),
180                         'atom_updated' => datetime_convert('UTC','UTC','now',ATOM_TIME),
181                         'language' => $user_info['language'],
182                         'logo'  => $a->get_baseurl()."/images/friendika-32.png",
183                 );
184                 
185                 return $arr;
186         }
187          
188         /**
189          * Returns user info array.
190          */
191         function api_get_user(&$a, $contact_id = Null){
192                 global $called_api;
193                 $user = null;
194                 $extra_query = "";
195
196
197                 if(!is_null($contact_id)){
198                         $user=$contact_id;
199                         $extra_query = "AND `contact`.`id` = %d ";
200                 }
201                 
202                 if(is_null($user) && x($_GET, 'user_id')) {
203                         $user = intval($_GET['user_id']);       
204                         $extra_query = "AND `contact`.`id` = %d ";
205                 }
206                 if(is_null($user) && x($_GET, 'screen_name')) {
207                         $user = dbesc($_GET['screen_name']);    
208                         $extra_query = "AND `contact`.`nick` = '%s' ";
209                         if (local_user()!==false)  $extra_query .= "AND `contact`.`uid`=".intval(local_user());
210                         
211                 }
212                 
213                 if (is_null($user) && $a->argc > (count($called_api)-1)){
214                         $argid = count($called_api);
215                         list($user, $null) = explode(".",$a->argv[$argid]);
216                         if(is_numeric($user)){
217                                 $user = intval($user);
218                                 $extra_query = "AND `contact`.`id` = %d ";
219                         } else {
220                                 $user = dbesc($user);
221                                 $extra_query = "AND `contact`.`nick` = '%s' ";
222                                 if (local_user()!==false)  $extra_query .= "AND `contact`.`uid`=".intval(local_user());
223                         }
224                 }
225                 
226                 if (! $user) {
227                         if (local_user()===false) {
228                                 api_login($a); return False;
229                         } else {
230                                 $user = $_SESSION['uid'];
231                                 $extra_query = "AND `contact`.`uid` = %d AND `contact`.`self` = 1 ";
232                         }
233                         
234                 }
235                 
236                 logger('api_user: ' . $extra_query . ' ' , $user);
237                 // user info            
238                 $uinfo = q("SELECT *, `contact`.`id` as `cid` FROM `contact`
239                                 WHERE 1
240                                 $extra_query",
241                                 $user
242                 );
243                 if (count($uinfo)==0) {
244                         return False;
245                 }
246                 
247                 if($uinfo[0]['self']) {
248                         $usr = q("select * from user where uid = %d limit 1",
249                                 intval(local_user())
250                         );
251                         $profile = q("select * from profile where uid = %d and `is-default` = 1 limit 1",
252                                 intval(local_user())
253                         );
254
255                         // count public wall messages
256                         $r = q("SELECT COUNT(`id`) as `count` FROM `item`
257                                         WHERE  `uid` = %d
258                                         AND `type`='wall' 
259                                         AND `allow_cid`='' AND `allow_gid`='' AND `deny_cid`='' AND `deny_gid`=''",
260                                         intval($uinfo[0]['uid'])
261                         );
262                         $countitms = $r[0]['count'];
263                 }
264                 else {
265                         $r = q("SELECT COUNT(`id`) as `count` FROM `item`
266                                         WHERE  `contact-id` = %d
267                                         AND `allow_cid`='' AND `allow_gid`='' AND `deny_cid`='' AND `deny_gid`=''",
268                                         intval($uinfo[0]['id'])
269                         );
270                         $countitms = $r[0]['count'];
271                 }
272
273                 // count friends
274                 $r = q("SELECT COUNT(`id`) as `count` FROM `contact`
275                                 WHERE  `uid` = %d AND `rel` IN ( %d, %d )
276                                 AND `self`=0 AND `blocked`=0 AND `pending`=0 AND `hidden`=0", 
277                                 intval($uinfo[0]['uid']),
278                                 intval(CONTACT_IS_SHARING),
279                                 intval(CONTACT_IS_FRIEND)
280                 );
281                 $countfriends = $r[0]['count'];
282
283                 $r = q("SELECT COUNT(`id`) as `count` FROM `contact`
284                                 WHERE  `uid` = %d AND `rel` IN ( %d, %d )
285                                 AND `self`=0 AND `blocked`=0 AND `pending`=0 AND `hidden`=0", 
286                                 intval($uinfo[0]['uid']),
287                                 intval(CONTACT_IS_FOLLOWER),
288                                 intval(CONTACT_IS_FRIEND)
289                 );
290                 $countfollowers = $r[0]['count'];
291
292                 $r = q("SELECT count(`id`) as `count` FROM item where starred = 1 and uid = %d and deleted = 0",
293                         intval($uinfo[0]['uid'])
294                 );
295                 $starred = $r[0]['count'];
296         
297
298                 if(! $uinfo[0]['self']) {
299                         $countfriends = 0;
300                         $countfollowers = 0;
301                         $starred = 0;
302                 }
303
304                 $ret = Array(
305                         'self' => intval($uinfo[0]['self']),
306                         'uid' => intval($uinfo[0]['uid']),
307                         'id' => intval($uinfo[0]['cid']),
308                         'name' => $uinfo[0]['name'],
309                         'screen_name' => (($uinfo[0]['nick']) ? $uinfo[0]['nick'] : $uinfo[0]['name']),
310                         'location' => ($usr) ? $usr[0]['default-location'] : '',
311                         'profile_image_url' => $uinfo[0]['micro'],
312                         'url' => $uinfo[0]['url'],
313                         'contact_url' => $a->get_baseurl()."/contacts/".$uinfo[0]['cid'],
314                         'protected' => false,   
315                         'friends_count' => intval($countfriends),
316                         'created_at' => api_date($uinfo[0]['name-date']),
317                         'utc_offset' => "+00:00",
318                         'time_zone' => 'UTC', //$uinfo[0]['timezone'],
319                         'geo_enabled' => false,
320                         'statuses_count' => intval($countitms), #XXX: fix me 
321                         'lang' => 'en', #XXX: fix me
322                         'description' => (($profile) ? $profile[0]['pdesc'] : ''),
323                         'followers_count' => intval($countfollowers),
324                         'favourites_count' => intval($starred),
325                         'contributors_enabled' => false,
326                         'follow_request_sent' => true,
327                         'profile_background_color' => 'cfe8f6',
328                         'profile_text_color' => '000000',
329                         'profile_link_color' => 'FF8500',
330                         'profile_sidebar_fill_color' =>'AD0066',
331                         'profile_sidebar_border_color' => 'AD0066',
332                         'profile_background_image_url' => '',
333                         'profile_background_tile' => false,
334                         'profile_use_background_image' => false,
335                         'notifications' => false,
336                         'following' => '', #XXX: fix me
337                         'verified' => true, #XXX: fix me
338                         'status' => array()
339                 );
340         
341                 return $ret;
342                 
343         }
344
345         function api_item_get_user(&$a, $item) {
346                 // The author is our direct contact, in a conversation with us.
347                 if(link_compare($item['url'],$item['author-link'])) {
348                         return api_get_user($a,$item['cid']);
349                 }
350                 else {
351                         // The author may be a contact of ours, but is replying to somebody else. 
352                         // Figure out if we know him/her.
353                         $normalised = normalise_link((strlen($item['author-link'])) ? $item['author-link'] : $item['url']);
354             if(($normalised != 'mailbox') && (x($a->contacts[$normalised])))
355                                 return api_get_user($a,$a->contacts[$normalised]['id']);
356                 }
357                 // We don't know this person directly.
358                 
359                 list($nick, $name) = array_map("trim",explode("(",$item['author-name']));
360                 $name=str_replace(")","",$name);
361                 
362                 $ret = array(
363                         'uid' => 0,
364                         'id' => 0,
365                         'name' => $name,
366                         'screen_name' => $nick,
367                         'location' => '', //$uinfo[0]['default-location'],
368                         'profile_image_url' => $item['author-avatar'],
369                         'url' => $item['author-link'],
370                         'contact_url' => 0,
371                         'protected' => false,   #
372                         'friends_count' => 0,
373                         'created_at' => '',
374                         'utc_offset' => 0, #XXX: fix me
375                         'time_zone' => '', //$uinfo[0]['timezone'],
376                         'geo_enabled' => false,
377                         'statuses_count' => 0,
378                         'lang' => 'en', #XXX: fix me
379                         'description' => '',
380                         'followers_count' => 0,
381                         'favourites_count' => 0,
382                         'contributors_enabled' => false,
383                         'follow_request_sent' => false,
384                         'profile_background_color' => 'cfe8f6',
385                         'profile_text_color' => '000000',
386                         'profile_link_color' => 'FF8500',
387                         'profile_sidebar_fill_color' =>'AD0066',
388                         'profile_sidebar_border_color' => 'AD0066',
389                         'profile_background_image_url' => '',
390                         'profile_background_tile' => false,
391                         'profile_use_background_image' => false,
392                         'notifications' => false,
393                         'verified' => true, #XXX: fix me
394                         'followers' => '', #XXX: fix me
395                         'status' => array()
396                 );
397
398                 return $ret; 
399         }
400
401
402         /**
403          *  load api $templatename for $type and replace $data array
404          */
405         function api_apply_template($templatename, $type, $data){
406
407                 $a = get_app();
408
409                 switch($type){
410                         case "atom":
411                         case "rss":
412                         case "xml":
413                                 $data = array_xmlify($data);
414                                 $tpl = get_markup_template("api_".$templatename."_".$type.".tpl");
415                                 $ret = replace_macros($tpl, $data);
416                                 break;
417                         case "json":
418                                 $ret = $data;
419                                 break;
420                 }
421                 return $ret;
422         }
423         
424         /**
425          ** TWITTER API
426          */
427         
428         /**
429          * Returns an HTTP 200 OK response code and a representation of the requesting user if authentication was successful; 
430          * returns a 401 status code and an error message if not. 
431          * http://developer.twitter.com/doc/get/account/verify_credentials
432          */
433         function api_account_verify_credentials(&$a, $type){
434                 if (local_user()===false) return false;
435                 $user_info = api_get_user($a);
436                 
437                 return api_apply_template("user", $type, array('$user' => $user_info));
438
439         }
440         api_register_func('api/account/verify_credentials','api_account_verify_credentials', true);
441                 
442
443         /**
444          * get data from $_POST or $_GET
445          */
446         function requestdata($k){
447                 if (isset($_POST[$k])){
448                         return $_POST[$k];
449                 }
450                 if (isset($_GET[$k])){
451                         return $_GET[$k];
452                 }
453                 return null;
454         }
455
456         // TODO - media uploads
457         function api_statuses_update(&$a, $type) {
458                 if (local_user()===false) {
459                         logger('api_statuses_update: no user');
460                         return false;
461                 }
462                 $user_info = api_get_user($a);
463
464                 // convert $_POST array items to the form we use for web posts.
465
466                 // logger('api_post: ' . print_r($_POST,true));
467
468                 if(requestdata('htmlstatus')) {
469                         require_once('library/HTMLPurifier.auto.php');
470                         require_once('include/html2bbcode.php');
471
472                         $txt = requestdata('htmlstatus');
473                         if((strpos($txt,'<') !== false) || (strpos($txt,'>') !== false)) {
474
475                                 $txt = html2bb_video($txt);
476
477                                 $config = HTMLPurifier_Config::createDefault();
478                                 $config->set('Cache.DefinitionImpl', null);
479
480
481                                 $purifier = new HTMLPurifier($config);
482                                 $txt = $purifier->purify($txt);
483
484                                 $_REQUEST['body'] = html2bbcode($txt);
485                         }
486
487                 }
488                 else
489                         $_REQUEST['body'] = urldecode(requestdata('status'));
490
491                 $parent = requestdata('in_reply_to_status_id');
492                 if(ctype_digit($parent))
493                         $_REQUEST['parent'] = $parent;
494                 else
495                         $_REQUEST['parent_uri'] = $parent;
496
497                 if(requestdata('lat') && requestdata('long'))
498                         $_REQUEST['coord'] = sprintf("%s %s",requestdata('lat'),requestdata('long'));
499                 $_REQUEST['profile_uid'] = local_user();
500                 if(requestdata('parent'))
501                         $_REQUEST['type'] = 'net-comment';
502                 else
503                         $_REQUEST['type'] = 'wall';
504
505                 // set this so that the item_post() function is quiet and doesn't redirect or emit json
506
507                 $_REQUEST['api_source'] = true;
508
509                 // call out normal post function
510
511                 require_once('mod/item.php');
512                 item_post($a);  
513
514                 // this should output the last post (the one we just posted).
515                 return api_status_show($a,$type);
516         }
517         api_register_func('api/statuses/update','api_statuses_update', true);
518
519
520         function api_status_show(&$a, $type){
521                 $user_info = api_get_user($a);
522                 // get last public wall message
523                 $lastwall = q("SELECT `item`.*, `i`.`contact-id` as `reply_uid`, `i`.`nick` as `reply_author`
524                                 FROM `item`, `contact`,
525                                         (SELECT `item`.`id`, `item`.`contact-id`, `contact`.`nick` FROM `item`,`contact` WHERE `contact`.`id`=`item`.`contact-id`) as `i` 
526                                 WHERE `item`.`contact-id` = %d
527                                         AND `i`.`id` = `item`.`parent`
528                                         AND `contact`.`id`=`item`.`contact-id` AND `contact`.`self`=1
529                                         AND `type`!='activity'
530                                         AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''
531                                 ORDER BY `created` DESC 
532                                 LIMIT 1",
533                                 intval($user_info['id'])
534                 );
535
536                 if (count($lastwall)>0){
537                         $lastwall = $lastwall[0];
538                         
539                         $in_reply_to_status_id = '';
540                         $in_reply_to_user_id = '';
541                         $in_reply_to_screen_name = '';
542                         if ($lastwall['parent']!=$lastwall['id']) {
543                                 $in_reply_to_status_id=$lastwall['parent'];
544                                 $in_reply_to_user_id = $lastwall['reply_uid'];
545                                 $in_reply_to_screen_name = $lastwall['reply_author'];
546                         }  
547                         $status_info = array(
548                                 'created_at' => api_date($lastwall['created']),
549                                 'id' => $lastwall['contact-id'],
550                                 'text' => strip_tags(bbcode($lastwall['body'])),
551                                 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
552                                 'truncated' => false,
553                                 'in_reply_to_status_id' => $in_reply_to_status_id,
554                                 'in_reply_to_user_id' => $in_reply_to_user_id,
555                                 'favorited' => false,
556                                 'in_reply_to_screen_name' => $in_reply_to_screen_name,
557                                 'geo' => '',
558                                 'coordinates' => $lastwall['coord'],
559                                 'place' => $lastwall['location'],
560                                 'contributors' => ''                                    
561                         );
562                         $status_info['user'] = $user_info;
563                 }
564                 return  api_apply_template("status", $type, array('$status' => $status_info));
565                 
566         }
567
568
569
570
571                 
572         /**
573          * Returns extended information of a given user, specified by ID or screen name as per the required id parameter.
574          * The author's most recent status will be returned inline.
575          * http://developer.twitter.com/doc/get/users/show
576          */
577         function api_users_show(&$a, $type){
578                 $user_info = api_get_user($a);
579                 // get last public wall message
580                 $lastwall = q("SELECT `item`.*, `i`.`contact-id` as `reply_uid`, `i`.`nick` as `reply_author`
581                                 FROM `item`, `contact`,
582                                         (SELECT `item`.`id`, `item`.`contact-id`, `contact`.`nick` FROM `item`,`contact` WHERE `contact`.`id`=`item`.`contact-id`) as `i` 
583                                 WHERE `item`.`contact-id` = %d
584                                         AND `i`.`id` = `item`.`parent`
585                                         AND `contact`.`id`=`item`.`contact-id` AND `contact`.`self`=1
586                                         AND `type`!='activity'
587                                         AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''
588                                 ORDER BY `created` DESC 
589                                 LIMIT 1",
590                                 intval($user_info['id'])
591                 );
592
593                 if (count($lastwall)>0){
594                         $lastwall = $lastwall[0];
595                         
596                         $in_reply_to_status_id = '';
597                         $in_reply_to_user_id = '';
598                         $in_reply_to_screen_name = '';
599                         if ($lastwall['parent']!=$lastwall['id']) {
600                                 $in_reply_to_status_id=$lastwall['parent'];
601                                 $in_reply_to_user_id = $lastwall['reply_uid'];
602                                 $in_reply_to_screen_name = $lastwall['reply_author'];
603                         }  
604                         $user_info['status'] = array(
605                                 'created_at' => api_date($lastwall['created']),
606                                 'id' => $lastwall['contact-id'],
607                                 'text' => strip_tags(bbcode($lastwall['body'])),
608                                 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
609                                 'truncated' => false,
610                                 'in_reply_to_status_id' => $in_reply_to_status_id,
611                                 'in_reply_to_user_id' => $in_reply_to_user_id,
612                                 'favorited' => false,
613                                 'in_reply_to_screen_name' => $in_reply_to_screen_name,
614                                 'geo' => '',
615                                 'coordinates' => $lastwall['coord'],
616                                 'place' => $lastwall['location'],
617                                 'contributors' => ''                                    
618                         );
619                 }
620                 return  api_apply_template("user", $type, array('$user' => $user_info));
621                 
622         }
623         api_register_func('api/users/show','api_users_show');
624         
625         /**
626          * 
627          * http://developer.twitter.com/doc/get/statuses/home_timeline
628          * 
629          * TODO: Optional parameters
630          * TODO: Add reply info
631          */
632         function api_statuses_home_timeline(&$a, $type){
633                 if (local_user()===false) return false;
634                                 
635                 $user_info = api_get_user($a);
636                 // get last newtork messages
637
638
639                 // params
640                 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
641                 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
642                 if ($page<0) $page=0;
643                 $since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
644                 
645                 $start = $page*$count;
646
647                 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, 
648                         `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
649                         `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
650                         `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
651                         FROM `item`, `contact`
652                         WHERE `item`.`uid` = %d
653                         AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
654                         AND `contact`.`id` = `item`.`contact-id`
655                         AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
656                         $sql_extra
657                         AND `item`.`id`>%d
658                         ORDER BY `item`.`received` DESC LIMIT %d ,%d ",
659                         intval($user_info['uid']),
660                         intval($since_id),
661                         intval($start), intval($count)
662                 );
663
664                 $ret = api_format_items($r,$user_info);
665
666                 
667                 $data = array('$statuses' => $ret);
668                 switch($type){
669                         case "atom":
670                         case "rss":
671                                 $data = api_rss_extra($a, $data, $user_info);
672                 }
673                                 
674                 return  api_apply_template("timeline", $type, $data);
675         }
676         api_register_func('api/statuses/home_timeline','api_statuses_home_timeline', true);
677         api_register_func('api/statuses/friends_timeline','api_statuses_home_timeline', true);
678
679
680
681         function api_statuses_user_timeline(&$a, $type){
682                 if (local_user()===false) return false;
683                 
684                 $user_info = api_get_user($a);
685                 // get last newtork messages
686
687
688                 logger("api_statuses_user_timeline: local_user: ". local_user() .
689                            "\nuser_info: ".print_r($user_info, true) .
690                            "\n_REQUEST:  ".print_r($_REQUEST, true),
691                            LOGGER_DEBUG);
692
693                 // params
694                 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
695                 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
696                 if ($page<0) $page=0;
697                 $since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
698                 
699                 $start = $page*$count;
700
701                 if ($user_info['self']==1) $sql_extra = "AND `item`.`wall` = 1 ";
702
703                 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, 
704                         `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
705                         `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
706                         `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
707                         FROM `item`, `contact`
708                         WHERE `item`.`uid` = %d
709                         AND `item`.`contact-id` = %d
710                         AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
711                         AND `contact`.`id` = `item`.`contact-id`
712                         AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
713                         $sql_extra
714                         AND `item`.`id`>%d
715                         ORDER BY `item`.`received` DESC LIMIT %d ,%d ",
716                         intval(local_user()),
717                         intval($user_info['id']),
718                         intval($since_id),
719                         intval($start), intval($count)
720                 );
721
722                 $ret = api_format_items($r,$user_info);
723
724                 
725                 $data = array('$statuses' => $ret);
726                 switch($type){
727                         case "atom":
728                         case "rss":
729                                 $data = api_rss_extra($a, $data, $user_info);
730                 }
731                                 
732                 return  api_apply_template("timeline", $type, $data);
733         }
734
735         api_register_func('api/statuses/user_timeline','api_statuses_user_timeline', true);
736
737
738         function api_favorites(&$a, $type){
739                 if (local_user()===false) return false;
740                 
741                 $user_info = api_get_user($a);
742                 // in friendika starred item are private
743                 // return favorites only for self
744                 logger('api_favorites: self:' . $user_info['self']);
745                 
746                 if ($user_info['self']==0) {
747                         $ret = array();
748                 } else {
749                         
750                         
751                         // params
752                         $count = (x($_GET,'count')?$_GET['count']:20);
753                         $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
754                         if ($page<0) $page=0;
755                         
756                         $start = $page*$count;
757
758                         $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, 
759                                 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
760                                 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
761                                 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
762                                 FROM `item`, `contact`
763                                 WHERE `item`.`uid` = %d
764                                 AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
765                                 AND `item`.`starred` = 1
766                                 AND `contact`.`id` = `item`.`contact-id`
767                                 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
768                                 $sql_extra
769                                 ORDER BY `item`.`received` DESC LIMIT %d ,%d ",
770                                 intval($user_info['uid']),
771                                 intval($start), intval($count)
772                         );
773
774                         $ret = api_format_items($r,$user_info);
775                 
776                 }
777                 
778                 $data = array('$statuses' => $ret);
779                 switch($type){
780                         case "atom":
781                         case "rss":
782                                 $data = api_rss_extra($a, $data, $user_info);
783                 }
784                                 
785                 return  api_apply_template("timeline", $type, $data);
786         }
787
788         api_register_func('api/favorites','api_favorites', true);
789
790         
791         function api_format_items($r,$user_info) {
792
793                 //logger('api_format_items: ' . print_r($r,true));
794
795                 //logger('api_format_items: ' . print_r($user_info,true));
796
797                 $a = get_app();
798                 $ret = Array();
799
800                 foreach($r as $item) {
801                         localize_item($item);
802                         $status_user = (($item['cid']==$user_info['id'])?$user_info: api_item_get_user($a,$item));
803                         $status = array(
804                                 'created_at'=> api_date($item['created']),
805                                 'published' => api_date($item['created']),
806                                 'updated'   => api_date($item['edited']),
807                                 'id'            => intval($item['id']),
808                                 'message_id' => $item['uri'],
809                                 'text'          => strip_tags(bbcode($item['body'])),
810                                 'statusnet_html'                => bbcode($item['body']),
811                                 'source'    => (($item['app']) ? $item['app'] : 'web'),
812                                 'url'           => ($item['plink']!=''?$item['plink']:$item['author-link']),
813                                 'truncated' => False,
814                                 'in_reply_to_status_id' => ($item['parent']!=$item['id']? intval($item['parent']):''),
815                                 'in_reply_to_user_id' => '',
816                                 'favorited' => $item['starred'] ? true : false,
817                                 'in_reply_to_screen_name' => '',
818                                 'geo' => '',
819                                 'coordinates' => $item['coord'],
820                                 'place' => $item['location'],
821                                 'contributors' => '',
822                                 'annotations'  => '',
823                                 'entities'  => '',
824                                 'user' =>  $status_user ,
825                                 'objecttype' => (($item['object-type']) ? $item['object-type'] : ACTIVITY_OBJ_NOTE),
826                                 'verb' => (($item['verb']) ? $item['verb'] : ACTIVITY_POST),
827                                 'self' => $a->get_baseurl()."/api/statuses/show/".$item['id'].".".$type,
828                                 'edit' => $a->get_baseurl()."/api/statuses/show/".$item['id'].".".$type,                                
829                         );
830                         $ret[]=$status;
831                 };
832                 return $ret;
833         }
834
835
836         function api_account_rate_limit_status(&$a,$type) {
837
838                 $hash = array(
839                           'remaining_hits' => (string) 150,
840                           'hourly_limit' => (string) 150,
841                           'reset_time' => datetime_convert('UTC','UTC','now + 1 hour',ATOM_TIME),
842                           'reset_time_in_seconds' => strtotime('now + 1 hour')
843                 );
844
845                 return api_apply_template('ratelimit', $type, array('$hash' => $hash));
846
847         }
848         api_register_func('api/account/rate_limit_status','api_account_rate_limit_status',true);
849
850         /**
851          *  https://dev.twitter.com/docs/api/1/get/statuses/friends 
852          *  This function is deprecated by Twitter
853          *  returns: json, xml 
854          **/
855         function api_statuses_f(&$a, $type, $qtype) {
856                 if (local_user()===false) return false;
857                 $user_info = api_get_user($a);
858                 
859                 
860                 // friends and followers only for self
861                 if ($user_info['self']==0){
862                         return false;
863                 }
864                 
865                 if (x($_GET,'cursor') && $_GET['cursor']=='undefined'){
866                         /* this is to stop Hotot to load friends multiple times
867                         *  I'm not sure if I'm missing return something or
868                         *  is a bug in hotot. Workaround, meantime
869                         */
870                         
871                         /*$ret=Array();
872                         return array('$users' => $ret);*/
873                         return false;
874                 }
875                 
876                 if($qtype == 'friends')
877                         $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
878                 if($qtype == 'followers')
879                         $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
880  
881                 $r = q("SELECT id FROM `contact` WHERE `uid` = %d AND `self` = 0 AND `blocked` = 0 AND `pending` = 0 $sql_extra",
882                         intval(local_user())
883                 );
884
885                 $ret = array();
886                 foreach($r as $cid){
887                         $ret[] = api_get_user($a, $cid['id']);
888                 }
889
890                 
891                 return array('$users' => $ret);
892
893         }
894         function api_statuses_friends(&$a, $type){
895                 $data =  api_statuses_f($a,$type,"friends");
896                 if ($data===false) return false;
897                 return  api_apply_template("friends", $type, $data);
898         }
899         function api_statuses_followers(&$a, $type){
900                 $data = api_statuses_f($a,$type,"followers");
901                 if ($data===false) return false;
902                 return  api_apply_template("friends", $type, $data);
903         }
904         api_register_func('api/statuses/friends','api_statuses_friends',true);
905         api_register_func('api/statuses/followers','api_statuses_followers',true);
906
907
908
909
910
911
912         function api_statusnet_config(&$a,$type) {
913                 $name = $a->config['sitename'];
914                 $server = $a->get_hostname();
915                 $logo = $a->get_baseurl() . '/images/friendika-64.png';
916                 $email = $a->config['admin_email'];
917                 $closed = (($a->config['register_policy'] == REGISTER_CLOSED) ? 'true' : 'false');
918                 $private = (($a->config['system']['block_public']) ? 'true' : 'false');
919                 $textlimit = (string) (($a->config['max_import_size']) ? $a->config['max_import_size'] : 200000);
920                 if($a->config['api_import_size'])
921                         $texlimit = string($a->config['api_import_size']);
922                 $ssl = (($a->config['system']['have_ssl']) ? 'true' : 'false');
923                 $sslserver = (($ssl === 'true') ? str_replace('http:','https:',$a->get_baseurl()) : '');
924
925                 $config = array(
926                         'site' => array('name' => $name,'server' => $server, 'theme' => 'default', 'path' => '',
927                                 'logo' => $logo, 'fancy' => 'true', 'language' => 'en', 'email' => $email, 'broughtby' => '',
928                                 'broughtbyurl' => '', 'timezone' => 'UTC', 'closed' => $closed, 'inviteonly' => 'false',
929                                 'private' => $private, 'textlimit' => $textlimit, 'sslserver' => $sslserver, 'ssl' => $ssl,
930                                 'shorturllength' => '30'
931                         ),
932                 );  
933
934                 return api_apply_template('config', $type, array('$config' => $config));
935
936         }
937         api_register_func('api/statusnet/config','api_statusnet_config',false);
938
939         function api_statusnet_version(&$a,$type) {
940
941                 // liar
942
943                 if($type === 'xml') {
944                         header("Content-type: application/xml");
945                         echo '<?xml version="1.0" encoding="UTF-8"?>' . "\r\n" . '<version>0.9.7</version>' . "\r\n";
946                         killme();
947                 }
948                 elseif($type === 'json') {
949                         header("Content-type: application/json");
950                         echo '"0.9.7"';
951                         killme();
952                 }
953         }
954         api_register_func('api/statusnet/version','api_statusnet_version',false);
955
956
957         function api_ff_ids(&$a,$type,$qtype) {
958                 if(! local_user())
959                         return false;
960
961                 if($qtype == 'friends')
962                         $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
963                 if($qtype == 'followers')
964                         $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
965  
966
967                 $r = q("SELECT id FROM `contact` WHERE `uid` = %d AND `self` = 0 AND `blocked` = 0 AND `pending` = 0 $sql_extra",
968                         intval(local_user())
969                 );
970
971                 if(is_array($r)) {
972                         if($type === 'xml') {
973                                 header("Content-type: application/xml");
974                                 echo '<?xml version="1.0" encoding="UTF-8"?>' . "\r\n" . '<ids>' . "\r\n";
975                                 foreach($r as $rr)
976                                         echo '<id>' . $rr['id'] . '</id>' . "\r\n";
977                                 echo '</ids>' . "\r\n";
978                                 killme();
979                         }
980                         elseif($type === 'json') {
981                                 $ret = array();
982                                 header("Content-type: application/json");
983                                 foreach($r as $rr) $ret[] = $rr['id'];
984                                 echo json_encode($ret);
985                                 killme();
986                         }
987                 }
988         }
989
990         function api_friends_ids(&$a,$type) {
991                 api_ff_ids($a,$type,'friends');
992         }
993         function api_followers_ids(&$a,$type) {
994                 api_ff_ids($a,$type,'followers');
995         }
996         api_register_func('api/friends/ids','api_friends_ids',true);
997         api_register_func('api/followers/ids','api_followers_ids',true);
998
999
1000         function api_direct_messages_new(&$a, $type) {
1001                 if (local_user()===false) return false;
1002                 
1003                 if (!x($_POST, "text") || !x($_POST,"screen_name")) return;
1004                 
1005                 $sender = api_get_user($a);
1006                 
1007                 $r = q("SELECT `id` FROM `contact` WHERE `uid`=%d AND `nick`='%s'",
1008                                 intval(local_user()),
1009                                 dbesc($_POST['screen_name']));
1010                 
1011                 $recipient = api_get_user($a, $r[0]['id']);                     
1012                 
1013
1014                 require_once("include/message.php");
1015                 $sub = ( (strlen($_POST['text'])>10)?substr($_POST['text'],0,10)."...":$_POST['text']);
1016                 $id = send_message($recipient['id'], $_POST['text'], $sub);
1017                 
1018                 
1019                 if ($id>-1) {
1020                         $r = q("SELECT * FROM `mail` WHERE id=%d", intval($id));
1021                         $item = $r[0];
1022                         $ret=Array(
1023                                         'id' => $item['id'],
1024                                         'created_at'=> api_date($item['created']),
1025                                         'sender_id'=> $sender['id'] ,
1026                                         'sender_screen_name'=> $sender['screen_name'],
1027                                         'sender'=> $sender,
1028                                         'recipient_id'=> $recipient['id'],
1029                                         'recipient_screen_name'=> $recipient['screen_name'],
1030                                         'recipient'=> $recipient,
1031                                         
1032                                         'text'=> $item['title']."\n".strip_tags(bbcode($item['body'])) ,
1033                                         
1034                         );
1035                 
1036                 } else {
1037                         $ret = array("error"=>$id);     
1038                 }
1039                 
1040                 $data = Array('$messages'=>$ret);
1041                 
1042                 switch($type){
1043                         case "atom":
1044                         case "rss":
1045                                 $data = api_rss_extra($a, $data, $user_info);
1046                 }
1047                                 
1048                 return  api_apply_template("direct_messages", $type, $data);
1049                                 
1050         }
1051         api_register_func('api/direct_messages/new','api_direct_messages_new',true);
1052
1053     function api_direct_messages_box(&$a, $type, $box) {
1054                 if (local_user()===false) return false;
1055                 
1056                 $user_info = api_get_user($a);
1057                 
1058                 // params
1059                 $count = (x($_GET,'count')?$_GET['count']:20);
1060                 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1061                 if ($page<0) $page=0;
1062                 
1063                 $start = $page*$count;
1064                 
1065         
1066                 if ($box=="sentbox") {
1067                         $sql_extra = "`from-url`='%s'";
1068                 } else {
1069                         $sql_extra = "`from-url`!='%s'";
1070                 }
1071                 
1072                 $r = q("SELECT * FROM `mail` WHERE uid=%d AND $sql_extra ORDER BY created DESC LIMIT %d,%d",
1073                                 intval(local_user()),
1074                                 dbesc( $a->get_baseurl() . '/profile/' . $a->user['nickname'] ),
1075                                 intval($start), intval($count)
1076                            );
1077                 
1078                 $ret = Array();
1079                 foreach($r as $item){
1080                         switch ($box){
1081                                 case "inbox":
1082                                         $recipient = $user_info;
1083                                         $sender = api_get_user($a,$item['contact-id']);
1084                                         break;
1085                                 case "sentbox":
1086                                         $recipient = api_get_user($a,$item['contact-id']);
1087                                         $sender = $user_info;
1088                                         break;
1089                         }
1090                                 
1091                         $ret[]=Array(
1092                                 'id' => $item['id'],
1093                                 'created_at'=> api_date($item['created']),
1094                                 'sender_id'=> $sender['id'] ,
1095                                 'sender_screen_name'=> $sender['screen_name'],
1096                                 'sender'=> $sender,
1097                                 'recipient_id'=> $recipient['id'],
1098                                 'recipient_screen_name'=> $recipient['screen_name'],
1099                                 'recipient'=> $recipient,
1100                                 
1101                                 'text'=> $item['title']."\n".strip_tags(bbcode($item['body'])) ,
1102                                 
1103                         );
1104                         
1105                 }
1106                 
1107
1108                 $data = array('$messages' => $ret);
1109                 switch($type){
1110                         case "atom":
1111                         case "rss":
1112                                 $data = api_rss_extra($a, $data, $user_info);
1113                 }
1114                                 
1115                 return  api_apply_template("direct_messages", $type, $data);
1116                 
1117         }
1118
1119         function api_direct_messages_sentbox(&$a, $type){
1120                 return api_direct_messages_box($a, $type, "sentbox");
1121         }
1122         function api_direct_messages_inbox(&$a, $type){
1123                 return api_direct_messages_box($a, $type, "inbox");
1124         }
1125         api_register_func('api/direct_messages/sent','api_direct_messages_sentbox',true);
1126         api_register_func('api/direct_messages','api_direct_messages_inbox',true);
1127
1128
1129
1130         function api_oauth_request_token(&$a, $type){
1131                 try{
1132                         $oauth = new FKOAuth1();
1133                         $r = $oauth->fetch_request_token(OAuthRequest::from_request());
1134                 }catch(Exception $e){
1135                         echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage()); killme();
1136                 }
1137                 echo $r;
1138                 killme();       
1139         }
1140         function api_oauth_access_token(&$a, $type){
1141                 try{
1142                         $oauth = new FKOAuth1();
1143                         $r = $oauth->fetch_access_token(OAuthRequest::from_request());
1144                 }catch(Exception $e){
1145                         echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage()); killme();
1146                 }
1147                 echo $r;
1148                 killme();                       
1149         }
1150
1151         api_register_func('api/oauth/request_token', 'api_oauth_request_token', false);
1152         api_register_func('api/oauth/access_token', 'api_oauth_access_token', false);
1153
1154