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