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