]> git.mxchange.org Git - friendica.git/blob - include/api.php
New indexes for the API
[friendica.git] / include / api.php
1 <?php
2 /**
3  * @file include/api.php
4  * Friendica implementation of statusnet/twitter API
5  *
6  * @todo Automatically detect if incoming data is HTML or BBCode
7  */
8         require_once('include/HTTPExceptions.php');
9
10         require_once('include/bbcode.php');
11         require_once('include/datetime.php');
12         require_once('include/conversation.php');
13         require_once('include/oauth.php');
14         require_once('include/html2plain.php');
15         require_once('mod/share.php');
16         require_once('include/Photo.php');
17         require_once('mod/item.php');
18         require_once('include/security.php');
19         require_once('include/contact_selectors.php');
20         require_once('include/html2bbcode.php');
21         require_once('mod/wall_upload.php');
22         require_once('mod/proxy.php');
23         require_once('include/message.php');
24         require_once('include/group.php');
25         require_once('include/like.php');
26         require_once('include/NotificationsManager.php');
27         require_once('include/plaintext.php');
28         require_once('include/xml.php');
29
30
31         define('API_METHOD_ANY','*');
32         define('API_METHOD_GET','GET');
33         define('API_METHOD_POST','POST,PUT');
34         define('API_METHOD_DELETE','POST,DELETE');
35
36
37
38         $API = Array();
39         $called_api = Null;
40
41         /**
42          * @brief Auth API user
43          *
44          * It is not sufficient to use local_user() to check whether someone is allowed to use the API,
45          * because this will open CSRF holes (just embed an image with src=friendicasite.com/api/statuses/update?status=CSRF
46          * into a page, and visitors will post something without noticing it).
47          */
48         function api_user() {
49                 if ($_SESSION['allow_api'])
50                         return local_user();
51
52                 return false;
53         }
54
55         /**
56          * @brief Get source name from API client
57          *
58          * Clients can send 'source' parameter to be show in post metadata
59          * as "sent via <source>".
60          * Some clients doesn't send a source param, we support ones we know
61          * (only Twidere, atm)
62          *
63          * @return string
64          *              Client source name, default to "api" if unset/unknown
65          */
66         function api_source() {
67                 if (requestdata('source'))
68                         return (requestdata('source'));
69
70                 // Support for known clients that doesn't send a source name
71                 if (strstr($_SERVER['HTTP_USER_AGENT'], "Twidere"))
72                         return ("Twidere");
73
74                 logger("Unrecognized user-agent ".$_SERVER['HTTP_USER_AGENT'], LOGGER_DEBUG);
75
76                 return ("api");
77         }
78
79         /**
80          * @brief Format date for API
81          *
82          * @param string $str Source date, as UTC
83          * @return string Date in UTC formatted as "D M d H:i:s +0000 Y"
84          */
85         function api_date($str){
86                 //Wed May 23 06:01:13 +0000 2007
87                 return datetime_convert('UTC', 'UTC', $str, "D M d H:i:s +0000 Y" );
88         }
89
90         /**
91          * @brief Register API endpoint
92          *
93          * Register a function to be the endpont for defined API path.
94          *
95          * @param string $path API URL path, relative to $a->get_baseurl()
96          * @param string $func Function name to call on path request
97          * @param bool $auth API need logged user
98          * @param string $method
99          *      HTTP method reqiured to call this endpoint.
100          *      One of API_METHOD_ANY, API_METHOD_GET, API_METHOD_POST.
101          *  Default to API_METHOD_ANY
102          */
103         function api_register_func($path, $func, $auth=false, $method=API_METHOD_ANY){
104                 global $API;
105                 $API[$path] = array(
106                         'func'=>$func,
107                         'auth'=>$auth,
108                         'method'=> $method
109                 );
110
111                 // Workaround for hotot
112                 $path = str_replace("api/", "api/1.1/", $path);
113                 $API[$path] = array(
114                         'func'=>$func,
115                         'auth'=>$auth,
116                         'method'=> $method
117                 );
118         }
119
120         /**
121          * @brief Login API user
122          *
123          * Log in user via OAuth1 or Simple HTTP Auth.
124          * Simple Auth allow username in form of <pre>user@server</pre>, ignoring server part
125          *
126          * @param App $a
127          * @hook 'authenticate'
128          *              array $addon_auth
129          *                      'username' => username from login form
130          *                      'password' => password from login form
131          *                      'authenticated' => return status,
132          *                      'user_record' => return authenticated user record
133          * @hook 'logged_in'
134          *              array $user     logged user record
135          */
136         function api_login(&$a){
137                 // login with oauth
138                 try{
139                         $oauth = new FKOAuth1();
140                         list($consumer,$token) = $oauth->verify_request(OAuthRequest::from_request());
141                         if (!is_null($token)){
142                                 $oauth->loginUser($token->uid);
143                                 call_hooks('logged_in', $a->user);
144                                 return;
145                         }
146                         echo __file__.__line__.__function__."<pre>"; var_dump($consumer, $token); die();
147                 }catch(Exception $e){
148                         logger($e);
149                 }
150
151
152
153                 // workaround for HTTP-auth in CGI mode
154                 if(x($_SERVER,'REDIRECT_REMOTE_USER')) {
155                         $userpass = base64_decode(substr($_SERVER["REDIRECT_REMOTE_USER"],6)) ;
156                         if(strlen($userpass)) {
157                                 list($name, $password) = explode(':', $userpass);
158                                 $_SERVER['PHP_AUTH_USER'] = $name;
159                                 $_SERVER['PHP_AUTH_PW'] = $password;
160                         }
161                 }
162
163                 if (!isset($_SERVER['PHP_AUTH_USER'])) {
164                         logger('API_login: ' . print_r($_SERVER,true), LOGGER_DEBUG);
165                         header('WWW-Authenticate: Basic realm="Friendica"');
166                         throw new UnauthorizedException("This API requires login");
167                 }
168
169                 $user = $_SERVER['PHP_AUTH_USER'];
170                 $password = $_SERVER['PHP_AUTH_PW'];
171                 $encrypted = hash('whirlpool',trim($password));
172
173                 // allow "user@server" login (but ignore 'server' part)
174                 $at=strstr($user, "@", true);
175                 if ( $at ) $user=$at;
176
177                 /**
178                  *  next code from mod/auth.php. needs better solution
179                  */
180                 $record = null;
181
182                 $addon_auth = array(
183                         'username' => trim($user),
184                         'password' => trim($password),
185                         'authenticated' => 0,
186                         'user_record' => null
187                 );
188
189                 /**
190                  *
191                  * A plugin indicates successful login by setting 'authenticated' to non-zero value and returning a user record
192                  * Plugins should never set 'authenticated' except to indicate success - as hooks may be chained
193                  * and later plugins should not interfere with an earlier one that succeeded.
194                  *
195                  */
196
197                 call_hooks('authenticate', $addon_auth);
198
199                 if(($addon_auth['authenticated']) && (count($addon_auth['user_record']))) {
200                         $record = $addon_auth['user_record'];
201                 }
202                 else {
203                         // process normal login request
204
205                         $r = q("SELECT * FROM `user` WHERE (`email` = '%s' OR `nickname` = '%s')
206                                 AND `password` = '%s' AND NOT `blocked` AND NOT `account_expired` AND NOT `account_removed` AND `verified` LIMIT 1",
207                                 dbesc(trim($user)),
208                                 dbesc(trim($user)),
209                                 dbesc($encrypted)
210                         );
211                         if(count($r))
212                                 $record = $r[0];
213                 }
214
215                 if((! $record) || (! count($record))) {
216                         logger('API_login failure: ' . print_r($_SERVER,true), LOGGER_DEBUG);
217                         header('WWW-Authenticate: Basic realm="Friendica"');
218                         #header('HTTP/1.0 401 Unauthorized');
219                         #die('This api requires login');
220                         throw new UnauthorizedException("This API requires login");
221                 }
222
223                 authenticate_success($record);
224
225                 $_SESSION["allow_api"] = true;
226
227                 call_hooks('logged_in', $a->user);
228
229         }
230
231         /**
232          * @brief Check HTTP method of called API
233          *
234          * API endpoints can define which HTTP method to accept when called.
235          * This function check the current HTTP method agains endpoint
236          * registered method.
237          *
238          * @param string $method Required methods, uppercase, separated by comma
239          * @return bool
240          */
241          function api_check_method($method) {
242                 if ($method=="*") return True;
243                 return strpos($method, $_SERVER['REQUEST_METHOD']) !== false;
244          }
245
246         /**
247          * @brief Main API entry point
248          *
249          * Authenticate user, call registered API function, set HTTP headers
250          *
251          * @param App $a
252          * @return string API call result
253          */
254         function api_call(&$a){
255                 GLOBAL $API, $called_api;
256
257                 $type="json";
258                 if (strpos($a->query_string, ".xml")>0) $type="xml";
259                 if (strpos($a->query_string, ".json")>0) $type="json";
260                 if (strpos($a->query_string, ".rss")>0) $type="rss";
261                 if (strpos($a->query_string, ".atom")>0) $type="atom";
262                 try {
263                         foreach ($API as $p=>$info){
264                                 if (strpos($a->query_string, $p)===0){
265                                         if (!api_check_method($info['method'])){
266                                                 throw new MethodNotAllowedException();
267                                         }
268
269                                         $called_api= explode("/",$p);
270                                         //unset($_SERVER['PHP_AUTH_USER']);
271                                         if ($info['auth']===true && api_user()===false) {
272                                                         api_login($a);
273                                         }
274
275                                         logger('API call for ' . $a->user['username'] . ': ' . $a->query_string);
276                                         logger('API parameters: ' . print_r($_REQUEST,true));
277
278                                         $stamp =  microtime(true);
279                                         $r = call_user_func($info['func'], $a, $type);
280                                         $duration = (float)(microtime(true)-$stamp);
281                                         logger("API call duration: ".round($duration, 2)."\t".$a->query_string, LOGGER_DEBUG);
282
283                                         if ($r===false) {
284                                                 // api function returned false withour throw an
285                                                 // exception. This should not happend, throw a 500
286                                                 throw new InternalServerErrorException();
287                                         }
288
289                                         switch($type){
290                                                 case "xml":
291                                                         header ("Content-Type: text/xml");
292                                                         return $r;
293                                                         break;
294                                                 case "json":
295                                                         header ("Content-Type: application/json");
296                                                         foreach($r as $rr)
297                                                                 $json = json_encode($rr);
298                                                                 if ($_GET['callback'])
299                                                                         $json = $_GET['callback']."(".$json.")";
300                                                                 return $json;
301                                                         break;
302                                                 case "rss":
303                                                         header ("Content-Type: application/rss+xml");
304                                                         return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
305                                                         break;
306                                                 case "atom":
307                                                         header ("Content-Type: application/atom+xml");
308                                                         return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
309                                                         break;
310
311                                         }
312                                 }
313                         }
314                         throw new NotImplementedException();
315                 } catch (HTTPException $e) {
316                         header("HTTP/1.1 {$e->httpcode} {$e->httpdesc}");
317                         return api_error($a, $type, $e);
318                 }
319         }
320
321         /**
322          * @brief Format API error string
323          *
324          * @param Api $a
325          * @param string $type Return type (xml, json, rss, as)
326          * @param HTTPException $error Error object
327          * @return strin error message formatted as $type
328          */
329         function api_error(&$a, $type, $e) {
330                 $error = ($e->getMessage()!==""?$e->getMessage():$e->httpdesc);
331                 # TODO:  https://dev.twitter.com/overview/api/response-codes
332
333                 $error = array("error" => $error,
334                                 "code" => $e->httpcode." ".$e->httpdesc,
335                                 "request" => $a->query_string);
336
337                 $ret = api_format_data('status', $type, array('status' => $error));
338
339                 switch($type){
340                         case "xml":
341                                 header ("Content-Type: text/xml");
342                                 return $ret;
343                                 break;
344                         case "json":
345                                 header ("Content-Type: application/json");
346                                 return json_encode($ret);
347                                 break;
348                         case "rss":
349                                 header ("Content-Type: application/rss+xml");
350                                 return $ret;
351                                 break;
352                         case "atom":
353                                 header ("Content-Type: application/atom+xml");
354                                 return $ret;
355                                 break;
356                 }
357         }
358
359         /**
360          * @brief Set values for RSS template
361          *
362          * @param App $a
363          * @param array $arr Array to be passed to template
364          * @param array $user_info
365          * @return array
366          */
367         function api_rss_extra(&$a, $arr, $user_info){
368                 if (is_null($user_info)) $user_info = api_get_user($a);
369                 $arr['$user'] = $user_info;
370                 $arr['$rss'] = array(
371                         'alternate' => $user_info['url'],
372                         'self' => $a->get_baseurl(). "/". $a->query_string,
373                         'base' => $a->get_baseurl(),
374                         'updated' => api_date(null),
375                         'atom_updated' => datetime_convert('UTC','UTC','now',ATOM_TIME),
376                         'language' => $user_info['language'],
377                         'logo'  => $a->get_baseurl()."/images/friendica-32.png",
378                 );
379
380                 return $arr;
381         }
382
383
384         /**
385          * @brief Unique contact to contact url.
386          *
387          * @param int $id Contact id
388          * @return bool|string
389          *              Contact url or False if contact id is unknown
390          */
391         function api_unique_id_to_url($id){
392                 $r = q("SELECT `url` FROM `gcontact` WHERE `id`=%d LIMIT 1",
393                         intval($id));
394                 if ($r)
395                         return ($r[0]["url"]);
396                 else
397                         return false;
398         }
399
400         /**
401          * @brief Get user info array.
402          *
403          * @param Api $a
404          * @param int|string $contact_id Contact ID or URL
405          * @param string $type Return type (for errors)
406          */
407         function api_get_user(&$a, $contact_id = Null, $type = "json"){
408                 global $called_api;
409                 $user = null;
410                 $extra_query = "";
411                 $url = "";
412                 $nick = "";
413
414                 logger("api_get_user: Fetching user data for user ".$contact_id, LOGGER_DEBUG);
415
416                 // Searching for contact URL
417                 if(!is_null($contact_id) AND (intval($contact_id) == 0)){
418                         $user = dbesc(normalise_link($contact_id));
419                         $url = $user;
420                         $extra_query = "AND `contact`.`nurl` = '%s' ";
421                         if (api_user()!==false)  $extra_query .= "AND `contact`.`uid`=".intval(api_user());
422                 }
423
424                 // Searching for unique contact id
425                 if(!is_null($contact_id) AND (intval($contact_id) != 0)){
426                         $user = dbesc(api_unique_id_to_url($contact_id));
427
428                         if ($user == "")
429                                 throw new BadRequestException("User not found.");
430
431                         $url = $user;
432                         $extra_query = "AND `contact`.`nurl` = '%s' ";
433                         if (api_user()!==false)  $extra_query .= "AND `contact`.`uid`=".intval(api_user());
434                 }
435
436                 if(is_null($user) && x($_GET, 'user_id')) {
437                         $user = dbesc(api_unique_id_to_url($_GET['user_id']));
438
439                         if ($user == "")
440                                 throw new BadRequestException("User not found.");
441
442                         $url = $user;
443                         $extra_query = "AND `contact`.`nurl` = '%s' ";
444                         if (api_user()!==false)  $extra_query .= "AND `contact`.`uid`=".intval(api_user());
445                 }
446                 if(is_null($user) && x($_GET, 'screen_name')) {
447                         $user = dbesc($_GET['screen_name']);
448                         $nick = $user;
449                         $extra_query = "AND `contact`.`nick` = '%s' ";
450                         if (api_user()!==false)  $extra_query .= "AND `contact`.`uid`=".intval(api_user());
451                 }
452
453                 if (is_null($user) AND ($a->argc > (count($called_api)-1)) AND (count($called_api) > 0)){
454                         $argid = count($called_api);
455                         list($user, $null) = explode(".",$a->argv[$argid]);
456                         if(is_numeric($user)){
457                                 $user = dbesc(api_unique_id_to_url($user));
458
459                                 if ($user == "")
460                                         return false;
461
462                                 $url = $user;
463                                 $extra_query = "AND `contact`.`nurl` = '%s' ";
464                                 if (api_user()!==false)  $extra_query .= "AND `contact`.`uid`=".intval(api_user());
465                         } else {
466                                 $user = dbesc($user);
467                                 $nick = $user;
468                                 $extra_query = "AND `contact`.`nick` = '%s' ";
469                                 if (api_user()!==false)  $extra_query .= "AND `contact`.`uid`=".intval(api_user());
470                         }
471                 }
472
473                 logger("api_get_user: user ".$user, LOGGER_DEBUG);
474
475                 if (!$user) {
476                         if (api_user()===false) {
477                                 api_login($a);
478                                 return False;
479                         } else {
480                                 $user = $_SESSION['uid'];
481                                 $extra_query = "AND `contact`.`uid` = %d AND `contact`.`self` ";
482                         }
483
484                 }
485
486                 logger('api_user: ' . $extra_query . ', user: ' . $user);
487                 // user info
488                 $uinfo = q("SELECT *, `contact`.`id` as `cid` FROM `contact`
489                                 WHERE 1
490                                 $extra_query",
491                                 $user
492                 );
493
494                 // Selecting the id by priority, friendica first
495                 api_best_nickname($uinfo);
496
497                 // if the contact wasn't found, fetch it from the unique contacts
498                 if (count($uinfo)==0) {
499                         $r = array();
500
501                         if ($url != "")
502                                 $r = q("SELECT * FROM `gcontact` WHERE `nurl`='%s' LIMIT 1", dbesc(normalise_link($url)));
503
504                         if ($r) {
505                                 // If no nick where given, extract it from the address
506                                 if (($r[0]['nick'] == "") OR ($r[0]['name'] == $r[0]['nick']))
507                                         $r[0]['nick'] = api_get_nick($r[0]["url"]);
508
509                                 $ret = array(
510                                         'id' => $r[0]["id"],
511                                         'id_str' => (string) $r[0]["id"],
512                                         'name' => $r[0]["name"],
513                                         'screen_name' => (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']),
514                                         'location' => $r[0]["location"],
515                                         'description' => $r[0]["about"],
516                                         'url' => $r[0]["url"],
517                                         'protected' => false,
518                                         'followers_count' => 0,
519                                         'friends_count' => 0,
520                                         'listed_count' => 0,
521                                         'created_at' => api_date($r[0]["created"]),
522                                         'favourites_count' => 0,
523                                         'utc_offset' => 0,
524                                         'time_zone' => 'UTC',
525                                         'geo_enabled' => false,
526                                         'verified' => false,
527                                         'statuses_count' => 0,
528                                         'lang' => '',
529                                         'contributors_enabled' => false,
530                                         'is_translator' => false,
531                                         'is_translation_enabled' => false,
532                                         'profile_image_url' => $r[0]["photo"],
533                                         'profile_image_url_https' => $r[0]["photo"],
534                                         'following' => false,
535                                         'follow_request_sent' => false,
536                                         'notifications' => false,
537                                         'statusnet_blocking' => false,
538                                         'notifications' => false,
539                                         'statusnet_profile_url' => $r[0]["url"],
540                                         'uid' => 0,
541                                         'cid' => get_contact($r[0]["url"], api_user()),
542                                         'self' => 0,
543                                         'network' => $r[0]["network"],
544                                 );
545
546                                 return $ret;
547                         } else {
548                                 throw new BadRequestException("User not found.");
549                         }
550                 }
551
552                 if($uinfo[0]['self']) {
553
554                         if ($uinfo[0]['network'] == "")
555                                 $uinfo[0]['network'] = NETWORK_DFRN;
556
557                         $usr = q("select * from user where uid = %d limit 1",
558                                 intval(api_user())
559                         );
560                         $profile = q("select * from profile where uid = %d and `is-default` = 1 limit 1",
561                                 intval(api_user())
562                         );
563
564                         //AND `allow_cid`='' AND `allow_gid`='' AND `deny_cid`='' AND `deny_gid`=''",
565                         // count public wall messages
566                         $r = q("SELECT count(*) as `count` FROM `item`
567                                         WHERE  `uid` = %d
568                                         AND `type`='wall'",
569                                         intval($uinfo[0]['uid'])
570                         );
571                         $countitms = $r[0]['count'];
572                 }
573                 else {
574                         //AND `allow_cid`='' AND `allow_gid`='' AND `deny_cid`='' AND `deny_gid`=''",
575                         $r = q("SELECT count(*) as `count` FROM `item`
576                                         WHERE  `contact-id` = %d",
577                                         intval($uinfo[0]['id'])
578                         );
579                         $countitms = $r[0]['count'];
580                 }
581
582                 // count friends
583                 $r = q("SELECT count(*) as `count` FROM `contact`
584                                 WHERE  `uid` = %d AND `rel` IN ( %d, %d )
585                                 AND `self`=0 AND `blocked`=0 AND `pending`=0 AND `hidden`=0",
586                                 intval($uinfo[0]['uid']),
587                                 intval(CONTACT_IS_SHARING),
588                                 intval(CONTACT_IS_FRIEND)
589                 );
590                 $countfriends = $r[0]['count'];
591
592                 $r = q("SELECT count(*) as `count` FROM `contact`
593                                 WHERE  `uid` = %d AND `rel` IN ( %d, %d )
594                                 AND `self`=0 AND `blocked`=0 AND `pending`=0 AND `hidden`=0",
595                                 intval($uinfo[0]['uid']),
596                                 intval(CONTACT_IS_FOLLOWER),
597                                 intval(CONTACT_IS_FRIEND)
598                 );
599                 $countfollowers = $r[0]['count'];
600
601                 $r = q("SELECT count(*) as `count` FROM item where starred = 1 and uid = %d and deleted = 0",
602                         intval($uinfo[0]['uid'])
603                 );
604                 $starred = $r[0]['count'];
605
606
607                 if(! $uinfo[0]['self']) {
608                         $countfriends = 0;
609                         $countfollowers = 0;
610                         $starred = 0;
611                 }
612
613                 // Add a nick if it isn't present there
614                 if (($uinfo[0]['nick'] == "") OR ($uinfo[0]['name'] == $uinfo[0]['nick'])) {
615                         $uinfo[0]['nick'] = api_get_nick($uinfo[0]["url"]);
616                 }
617
618                 $network_name = network_to_name($uinfo[0]['network'], $uinfo[0]['url']);
619
620                 $gcontact_id  = get_gcontact_id(array("url" => $uinfo[0]['url'], "network" => $uinfo[0]['network'],
621                                                         "photo" => $uinfo[0]['micro'], "name" => $uinfo[0]['name']));
622
623                 $ret = Array(
624                         'id' => intval($gcontact_id),
625                         'id_str' => (string) intval($gcontact_id),
626                         'name' => (($uinfo[0]['name']) ? $uinfo[0]['name'] : $uinfo[0]['nick']),
627                         'screen_name' => (($uinfo[0]['nick']) ? $uinfo[0]['nick'] : $uinfo[0]['name']),
628                         'location' => ($usr) ? $usr[0]['default-location'] : $network_name,
629                         'description' => (($profile) ? $profile[0]['pdesc'] : NULL),
630                         'profile_image_url' => $uinfo[0]['micro'],
631                         'profile_image_url_https' => $uinfo[0]['micro'],
632                         'url' => $uinfo[0]['url'],
633                         'protected' => false,
634                         'followers_count' => intval($countfollowers),
635                         'friends_count' => intval($countfriends),
636                         'created_at' => api_date($uinfo[0]['created']),
637                         'favourites_count' => intval($starred),
638                         'utc_offset' => "0",
639                         'time_zone' => 'UTC',
640                         'statuses_count' => intval($countitms),
641                         'following' => (($uinfo[0]['rel'] == CONTACT_IS_FOLLOWER) OR ($uinfo[0]['rel'] == CONTACT_IS_FRIEND)),
642                         'verified' => true,
643                         'statusnet_blocking' => false,
644                         'notifications' => false,
645                         //'statusnet_profile_url' => $a->get_baseurl()."/contacts/".$uinfo[0]['cid'],
646                         'statusnet_profile_url' => $uinfo[0]['url'],
647                         'uid' => intval($uinfo[0]['uid']),
648                         'cid' => intval($uinfo[0]['cid']),
649                         'self' => $uinfo[0]['self'],
650                         'network' => $uinfo[0]['network'],
651                 );
652
653                 return $ret;
654
655         }
656
657         /**
658          * @brief return api-formatted array for item's author and owner
659          *
660          * @param App $a
661          * @param array $item : item from db
662          * @return array(array:author, array:owner)
663          */
664         function api_item_get_user(&$a, $item) {
665
666                 // Make sure that there is an entry in the global contacts for author and owner
667                 get_gcontact_id(array("url" => $item['author-link'], "network" => $item['network'],
668                                         "photo" => $item['author-avatar'], "name" => $item['author-name']));
669
670                 get_gcontact_id(array("url" => $item['owner-link'], "network" => $item['network'],
671                                         "photo" => $item['owner-avatar'], "name" => $item['owner-name']));
672
673                 $status_user = api_get_user($a,$item["author-link"]);
674                 $status_user["protected"] = (($item["allow_cid"] != "") OR
675                                                 ($item["allow_gid"] != "") OR
676                                                 ($item["deny_cid"] != "") OR
677                                                 ($item["deny_gid"] != "") OR
678                                                 $item["private"]);
679
680                 $owner_user = api_get_user($a,$item["owner-link"]);
681
682                 return (array($status_user, $owner_user));
683         }
684
685         /**
686          * @brief walks recursively through an array with the possibility to change value and key
687          *
688          * @param array $array The array to walk through
689          * @param string $callback The callback function
690          *
691          * @return array the transformed array
692          */
693         function api_walk_recursive(array &$array, callable $callback) {
694
695                 $new_array = array();
696
697                 foreach ($array as $k => $v) {
698                         if (is_array($v)) {
699                                 if ($callback($v, $k))
700                                         $new_array[$k] = api_walk_recursive($v, $callback);
701                         } else {
702                                 if ($callback($v, $k))
703                                         $new_array[$k] = $v;
704                         }
705                 }
706                 $array = $new_array;
707
708                 return $array;
709         }
710
711         /**
712          * @brief Callback function to transform the array in an array that can be transformed in a XML file
713          *
714          * @param variant $item Array item value
715          * @param string $key Array key
716          *
717          * @return boolean Should the array item be deleted?
718          */
719         function api_reformat_xml(&$item, &$key) {
720                 if (is_bool($item))
721                         $item = ($item ? "true" : "false");
722
723                 if (substr($key, 0, 10) == "statusnet_")
724                         $key = "statusnet:".substr($key, 10);
725                 elseif (substr($key, 0, 10) == "friendica_")
726                         $key = "friendica:".substr($key, 10);
727                 //else
728                 //      $key = "default:".$key;
729
730                 return true;
731         }
732
733         /**
734          * @brief Creates the XML from a JSON style array
735          *
736          * @param array $data JSON style array
737          * @param string $root_element Name of the root element
738          *
739          * @return string The XML data
740          */
741         function api_create_xml($data, $root_element) {
742                 $childname = key($data);
743                 $data2 = array_pop($data);
744                 $key = key($data2);
745
746                 $namespaces = array("" => "http://api.twitter.com",
747                                         "statusnet" => "http://status.net/schema/api/1/",
748                                         "friendica" => "http://friendi.ca/schema/api/1/",
749                                         "georss" => "http://www.georss.org/georss");
750
751                 /// @todo Auto detection of needed namespaces
752                 if (in_array($root_element, array("ok", "hash", "config", "version", "ids", "notes", "photos")))
753                         $namespaces = array();
754
755                 if (is_array($data2))
756                         api_walk_recursive($data2, "api_reformat_xml");
757
758                 if ($key == "0") {
759                         $data4 = array();
760                         $i = 1;
761
762                         foreach ($data2 AS $item)
763                                 $data4[$i++.":".$childname] = $item;
764
765                         $data2 = $data4;
766                 }
767
768                 $data3 = array($root_element => $data2);
769                 $ret = xml::from_array($data3, $xml, false, $namespaces);
770                 return $ret;
771         }
772
773         /**
774          * @brief Formats the data according to the data type
775          *
776          * @param string $root_element Name of the root element
777          * @param string $type Return type (atom, rss, xml, json)
778          * @param array $data JSON style array
779          *
780          * @return (string|object) XML data or JSON data
781          */
782         function api_format_data($root_element, $type, $data){
783
784                 $a = get_app();
785
786                 switch($type){
787                         case "atom":
788                         case "rss":
789                         case "xml":
790                                 $ret = api_create_xml($data, $root_element);
791                                 break;
792                         case "json":
793                                 $ret = $data;
794                                 break;
795                 }
796
797                 return $ret;
798         }
799
800         /**
801          ** TWITTER API
802          */
803
804         /**
805          * Returns an HTTP 200 OK response code and a representation of the requesting user if authentication was successful;
806          * returns a 401 status code and an error message if not.
807          * http://developer.twitter.com/doc/get/account/verify_credentials
808          */
809         function api_account_verify_credentials(&$a, $type){
810                 if (api_user()===false) throw new ForbiddenException();
811
812                 unset($_REQUEST["user_id"]);
813                 unset($_GET["user_id"]);
814
815                 unset($_REQUEST["screen_name"]);
816                 unset($_GET["screen_name"]);
817
818                 $skip_status = (x($_REQUEST,'skip_status')?$_REQUEST['skip_status']:false);
819
820                 $user_info = api_get_user($a);
821
822                 // "verified" isn't used here in the standard
823                 unset($user_info["verified"]);
824
825                 // - Adding last status
826                 if (!$skip_status) {
827                         $user_info["status"] = api_status_show($a,"raw");
828                         if (!count($user_info["status"]))
829                                 unset($user_info["status"]);
830                         else
831                                 unset($user_info["status"]["user"]);
832                 }
833
834                 // "uid" and "self" are only needed for some internal stuff, so remove it from here
835                 unset($user_info["uid"]);
836                 unset($user_info["self"]);
837
838                 return api_format_data("user", $type, array('user' => $user_info));
839
840         }
841         api_register_func('api/account/verify_credentials','api_account_verify_credentials', true);
842
843
844         /**
845          * get data from $_POST or $_GET
846          */
847         function requestdata($k){
848                 if (isset($_POST[$k])){
849                         return $_POST[$k];
850                 }
851                 if (isset($_GET[$k])){
852                         return $_GET[$k];
853                 }
854                 return null;
855         }
856
857 /*Waitman Gobble Mod*/
858         function api_statuses_mediap(&$a, $type) {
859                 if (api_user()===false) {
860                         logger('api_statuses_update: no user');
861                         throw new ForbiddenException();
862                 }
863                 $user_info = api_get_user($a);
864
865                 $_REQUEST['type'] = 'wall';
866                 $_REQUEST['profile_uid'] = api_user();
867                 $_REQUEST['api_source'] = true;
868                 $txt = requestdata('status');
869                 //$txt = urldecode(requestdata('status'));
870
871                 if((strpos($txt,'<') !== false) || (strpos($txt,'>') !== false)) {
872
873                         $txt = html2bb_video($txt);
874                         $config = HTMLPurifier_Config::createDefault();
875                         $config->set('Cache.DefinitionImpl', null);
876                         $purifier = new HTMLPurifier($config);
877                         $txt = $purifier->purify($txt);
878                 }
879                 $txt = html2bbcode($txt);
880
881                 $a->argv[1]=$user_info['screen_name']; //should be set to username?
882
883                 $_REQUEST['hush']='yeah'; //tell wall_upload function to return img info instead of echo
884                 $bebop = wall_upload_post($a);
885
886                 //now that we have the img url in bbcode we can add it to the status and insert the wall item.
887                 $_REQUEST['body']=$txt."\n\n".$bebop;
888                 item_post($a);
889
890                 // this should output the last post (the one we just posted).
891                 return api_status_show($a,$type);
892         }
893         api_register_func('api/statuses/mediap','api_statuses_mediap', true, API_METHOD_POST);
894 /*Waitman Gobble Mod*/
895
896
897         function api_statuses_update(&$a, $type) {
898                 if (api_user()===false) {
899                         logger('api_statuses_update: no user');
900                         throw new ForbiddenException();
901                 }
902
903                 $user_info = api_get_user($a);
904
905                 // convert $_POST array items to the form we use for web posts.
906
907                 // logger('api_post: ' . print_r($_POST,true));
908
909                 if(requestdata('htmlstatus')) {
910                         $txt = requestdata('htmlstatus');
911                         if((strpos($txt,'<') !== false) || (strpos($txt,'>') !== false)) {
912                                 $txt = html2bb_video($txt);
913
914                                 $config = HTMLPurifier_Config::createDefault();
915                                 $config->set('Cache.DefinitionImpl', null);
916
917                                 $purifier = new HTMLPurifier($config);
918                                 $txt = $purifier->purify($txt);
919
920                                 $_REQUEST['body'] = html2bbcode($txt);
921                         }
922
923                 } else
924                         $_REQUEST['body'] = requestdata('status');
925
926                 $_REQUEST['title'] = requestdata('title');
927
928                 $parent = requestdata('in_reply_to_status_id');
929
930                 // Twidere sends "-1" if it is no reply ...
931                 if ($parent == -1)
932                         $parent = "";
933
934                 if(ctype_digit($parent))
935                         $_REQUEST['parent'] = $parent;
936                 else
937                         $_REQUEST['parent_uri'] = $parent;
938
939                 if(requestdata('lat') && requestdata('long'))
940                         $_REQUEST['coord'] = sprintf("%s %s",requestdata('lat'),requestdata('long'));
941                 $_REQUEST['profile_uid'] = api_user();
942
943                 if($parent)
944                         $_REQUEST['type'] = 'net-comment';
945                 else {
946                         // Check for throttling (maximum posts per day, week and month)
947                         $throttle_day = get_config('system','throttle_limit_day');
948                         if ($throttle_day > 0) {
949                                 $datefrom = date("Y-m-d H:i:s", time() - 24*60*60);
950
951                                 $r = q("SELECT COUNT(*) AS `posts_day` FROM `item` WHERE `uid`=%d AND `wall`
952                                         AND `created` > '%s' AND `id` = `parent`",
953                                         intval(api_user()), dbesc($datefrom));
954
955                                 if ($r)
956                                         $posts_day = $r[0]["posts_day"];
957                                 else
958                                         $posts_day = 0;
959
960                                 if ($posts_day > $throttle_day) {
961                                         logger('Daily posting limit reached for user '.api_user(), LOGGER_DEBUG);
962                                         #die(api_error($a, $type, sprintf(t("Daily posting limit of %d posts reached. The post was rejected."), $throttle_day)));
963                                         throw new TooManyRequestsException(sprintf(t("Daily posting limit of %d posts reached. The post was rejected."), $throttle_day));
964                                 }
965                         }
966
967                         $throttle_week = get_config('system','throttle_limit_week');
968                         if ($throttle_week > 0) {
969                                 $datefrom = date("Y-m-d H:i:s", time() - 24*60*60*7);
970
971                                 $r = q("SELECT COUNT(*) AS `posts_week` FROM `item` WHERE `uid`=%d AND `wall`
972                                         AND `created` > '%s' AND `id` = `parent`",
973                                         intval(api_user()), dbesc($datefrom));
974
975                                 if ($r)
976                                         $posts_week = $r[0]["posts_week"];
977                                 else
978                                         $posts_week = 0;
979
980                                 if ($posts_week > $throttle_week) {
981                                         logger('Weekly posting limit reached for user '.api_user(), LOGGER_DEBUG);
982                                         #die(api_error($a, $type, sprintf(t("Weekly posting limit of %d posts reached. The post was rejected."), $throttle_week)));
983                                         throw new TooManyRequestsException(sprintf(t("Weekly posting limit of %d posts reached. The post was rejected."), $throttle_week));
984
985                                 }
986                         }
987
988                         $throttle_month = get_config('system','throttle_limit_month');
989                         if ($throttle_month > 0) {
990                                 $datefrom = date("Y-m-d H:i:s", time() - 24*60*60*30);
991
992                                 $r = q("SELECT COUNT(*) AS `posts_month` FROM `item` WHERE `uid`=%d AND `wall`
993                                         AND `created` > '%s' AND `id` = `parent`",
994                                         intval(api_user()), dbesc($datefrom));
995
996                                 if ($r)
997                                         $posts_month = $r[0]["posts_month"];
998                                 else
999                                         $posts_month = 0;
1000
1001                                 if ($posts_month > $throttle_month) {
1002                                         logger('Monthly posting limit reached for user '.api_user(), LOGGER_DEBUG);
1003                                         #die(api_error($a, $type, sprintf(t("Monthly posting limit of %d posts reached. The post was rejected."), $throttle_month)));
1004                                         throw new TooManyRequestsException(sprintf(t("Monthly posting limit of %d posts reached. The post was rejected."), $throttle_month));
1005                                 }
1006                         }
1007
1008                         $_REQUEST['type'] = 'wall';
1009                 }
1010
1011                 if(x($_FILES,'media')) {
1012                         // upload the image if we have one
1013                         $_REQUEST['hush']='yeah'; //tell wall_upload function to return img info instead of echo
1014                         $media = wall_upload_post($a);
1015                         if(strlen($media)>0)
1016                                 $_REQUEST['body'] .= "\n\n".$media;
1017                 }
1018
1019                 // To-Do: Multiple IDs
1020                 if (requestdata('media_ids')) {
1021                         $r = q("SELECT `resource-id`, `scale`, `nickname`, `type` FROM `photo` INNER JOIN `user` ON `user`.`uid` = `photo`.`uid` WHERE `resource-id` IN (SELECT `resource-id` FROM `photo` WHERE `id` = %d) AND `scale` > 0 AND `photo`.`uid` = %d ORDER BY `photo`.`width` DESC LIMIT 1",
1022                                 intval(requestdata('media_ids')), api_user());
1023                         if ($r) {
1024                                 $phototypes = Photo::supportedTypes();
1025                                 $ext = $phototypes[$r[0]['type']];
1026                                 $_REQUEST['body'] .= "\n\n".'[url='.$a->get_baseurl().'/photos/'.$r[0]['nickname'].'/image/'.$r[0]['resource-id'].']';
1027                                 $_REQUEST['body'] .= '[img]'.$a->get_baseurl()."/photo/".$r[0]['resource-id']."-".$r[0]['scale'].".".$ext."[/img][/url]";
1028                         }
1029                 }
1030
1031                 // set this so that the item_post() function is quiet and doesn't redirect or emit json
1032
1033                 $_REQUEST['api_source'] = true;
1034
1035                 if (!x($_REQUEST, "source"))
1036                         $_REQUEST["source"] = api_source();
1037
1038                 // call out normal post function
1039
1040                 item_post($a);
1041
1042                 // this should output the last post (the one we just posted).
1043                 return api_status_show($a,$type);
1044         }
1045         api_register_func('api/statuses/update','api_statuses_update', true, API_METHOD_POST);
1046         api_register_func('api/statuses/update_with_media','api_statuses_update', true, API_METHOD_POST);
1047
1048
1049         function api_media_upload(&$a, $type) {
1050                 if (api_user()===false) {
1051                         logger('no user');
1052                         throw new ForbiddenException();
1053                 }
1054
1055                 $user_info = api_get_user($a);
1056
1057                 if(!x($_FILES,'media')) {
1058                         // Output error
1059                         throw new BadRequestException("No media.");
1060                 }
1061
1062                 $media = wall_upload_post($a, false);
1063                 if(!$media) {
1064                         // Output error
1065                         throw new InternalServerErrorException();
1066                 }
1067
1068                 $returndata = array();
1069                 $returndata["media_id"] = $media["id"];
1070                 $returndata["media_id_string"] = (string)$media["id"];
1071                 $returndata["size"] = $media["size"];
1072                 $returndata["image"] = array("w" => $media["width"],
1073                                                 "h" => $media["height"],
1074                                                 "image_type" => $media["type"]);
1075
1076                 logger("Media uploaded: ".print_r($returndata, true), LOGGER_DEBUG);
1077
1078                 return array("media" => $returndata);
1079         }
1080         api_register_func('api/media/upload','api_media_upload', true, API_METHOD_POST);
1081
1082         function api_status_show(&$a, $type){
1083                 $user_info = api_get_user($a);
1084
1085                 logger('api_status_show: user_info: '.print_r($user_info, true), LOGGER_DEBUG);
1086
1087                 if ($type == "raw")
1088                         $privacy_sql = "AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''";
1089                 else
1090                         $privacy_sql = "";
1091
1092                 // get last public wall message
1093                 $lastwall = q("SELECT `item`.*, `i`.`contact-id` as `reply_uid`, `i`.`author-link` AS `item-author`
1094                                 FROM `item`, `item` as `i`
1095                                 WHERE `item`.`contact-id` = %d AND `item`.`uid` = %d
1096                                         AND ((`item`.`author-link` IN ('%s', '%s')) OR (`item`.`owner-link` IN ('%s', '%s')))
1097                                         AND `i`.`id` = `item`.`parent`
1098                                         AND `item`.`type`!='activity' $privacy_sql
1099                                 ORDER BY `item`.`id` DESC
1100                                 LIMIT 1",
1101                                 intval($user_info['cid']),
1102                                 intval(api_user()),
1103                                 dbesc($user_info['url']),
1104                                 dbesc(normalise_link($user_info['url'])),
1105                                 dbesc($user_info['url']),
1106                                 dbesc(normalise_link($user_info['url']))
1107                 );
1108
1109                 if (count($lastwall)>0){
1110                         $lastwall = $lastwall[0];
1111
1112                         $in_reply_to_status_id = NULL;
1113                         $in_reply_to_user_id = NULL;
1114                         $in_reply_to_status_id_str = NULL;
1115                         $in_reply_to_user_id_str = NULL;
1116                         $in_reply_to_screen_name = NULL;
1117                         if (intval($lastwall['parent']) != intval($lastwall['id'])) {
1118                                 $in_reply_to_status_id= intval($lastwall['parent']);
1119                                 $in_reply_to_status_id_str = (string) intval($lastwall['parent']);
1120
1121                                 $r = q("SELECT * FROM `gcontact` WHERE `nurl` = '%s'", dbesc(normalise_link($lastwall['item-author'])));
1122                                 if ($r) {
1123                                         if ($r[0]['nick'] == "")
1124                                                 $r[0]['nick'] = api_get_nick($r[0]["url"]);
1125
1126                                         $in_reply_to_screen_name = (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']);
1127                                         $in_reply_to_user_id = intval($r[0]['id']);
1128                                         $in_reply_to_user_id_str = (string) intval($r[0]['id']);
1129                                 }
1130                         }
1131
1132                         // There seems to be situation, where both fields are identical:
1133                         // https://github.com/friendica/friendica/issues/1010
1134                         // This is a bugfix for that.
1135                         if (intval($in_reply_to_status_id) == intval($lastwall['id'])) {
1136                                 logger('api_status_show: this message should never appear: id: '.$lastwall['id'].' similar to reply-to: '.$in_reply_to_status_id, LOGGER_DEBUG);
1137                                 $in_reply_to_status_id = NULL;
1138                                 $in_reply_to_user_id = NULL;
1139                                 $in_reply_to_status_id_str = NULL;
1140                                 $in_reply_to_user_id_str = NULL;
1141                                 $in_reply_to_screen_name = NULL;
1142                         }
1143
1144                         $converted = api_convert_item($lastwall);
1145
1146                         if ($type == "xml")
1147                                 $geo = "georss:point";
1148                         else
1149                                 $geo = "geo";
1150
1151                         $status_info = array(
1152                                 'created_at' => api_date($lastwall['created']),
1153                                 'id' => intval($lastwall['id']),
1154                                 'id_str' => (string) $lastwall['id'],
1155                                 'text' => $converted["text"],
1156                                 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
1157                                 'truncated' => false,
1158                                 'in_reply_to_status_id' => $in_reply_to_status_id,
1159                                 'in_reply_to_status_id_str' => $in_reply_to_status_id_str,
1160                                 'in_reply_to_user_id' => $in_reply_to_user_id,
1161                                 'in_reply_to_user_id_str' => $in_reply_to_user_id_str,
1162                                 'in_reply_to_screen_name' => $in_reply_to_screen_name,
1163                                 'user' => $user_info,
1164                                 $geo => NULL,
1165                                 'coordinates' => "",
1166                                 'place' => "",
1167                                 'contributors' => "",
1168                                 'is_quote_status' => false,
1169                                 'retweet_count' => 0,
1170                                 'favorite_count' => 0,
1171                                 'favorited' => $lastwall['starred'] ? true : false,
1172                                 'retweeted' => false,
1173                                 'possibly_sensitive' => false,
1174                                 'lang' => "",
1175                                 'statusnet_html'                => $converted["html"],
1176                                 'statusnet_conversation_id'     => $lastwall['parent'],
1177                         );
1178
1179                         if (count($converted["attachments"]) > 0)
1180                                 $status_info["attachments"] = $converted["attachments"];
1181
1182                         if (count($converted["entities"]) > 0)
1183                                 $status_info["entities"] = $converted["entities"];
1184
1185                         if (($lastwall['item_network'] != "") AND ($status["source"] == 'web'))
1186                                 $status_info["source"] = network_to_name($lastwall['item_network'], $user_info['url']);
1187                         elseif (($lastwall['item_network'] != "") AND (network_to_name($lastwall['item_network'], $user_info['url']) != $status_info["source"]))
1188                                 $status_info["source"] = trim($status_info["source"].' ('.network_to_name($lastwall['item_network'], $user_info['url']).')');
1189
1190                         // "uid" and "self" are only needed for some internal stuff, so remove it from here
1191                         unset($status_info["user"]["uid"]);
1192                         unset($status_info["user"]["self"]);
1193                 }
1194
1195                 logger('status_info: '.print_r($status_info, true), LOGGER_DEBUG);
1196
1197                 if ($type == "raw")
1198                         return($status_info);
1199
1200                 return  api_format_data("statuses", $type, array('status' => $status_info));
1201
1202         }
1203
1204
1205
1206
1207
1208         /**
1209          * Returns extended information of a given user, specified by ID or screen name as per the required id parameter.
1210          * The author's most recent status will be returned inline.
1211          * http://developer.twitter.com/doc/get/users/show
1212          */
1213         function api_users_show(&$a, $type){
1214                 $user_info = api_get_user($a);
1215                 $lastwall = q("SELECT `item`.*
1216                                 FROM `item`
1217                                 INNER JOIN `contact` ON `contact`.`id`=`item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1218                                 WHERE `item`.`uid` = %d AND `verb` = '%s' AND `item`.`contact-id` = %d
1219                                         AND ((`item`.`author-link` IN ('%s', '%s')) OR (`item`.`owner-link` IN ('%s', '%s')))
1220                                         AND `type`!='activity'
1221                                         AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''
1222                                 ORDER BY `id` DESC
1223                                 LIMIT 1",
1224                                 intval(api_user()),
1225                                 dbesc(ACTIVITY_POST),
1226                                 intval($user_info['cid']),
1227                                 dbesc($user_info['url']),
1228                                 dbesc(normalise_link($user_info['url'])),
1229                                 dbesc($user_info['url']),
1230                                 dbesc(normalise_link($user_info['url']))
1231                 );
1232
1233                 if (count($lastwall)>0){
1234                         $lastwall = $lastwall[0];
1235
1236                         $in_reply_to_status_id = NULL;
1237                         $in_reply_to_user_id = NULL;
1238                         $in_reply_to_status_id_str = NULL;
1239                         $in_reply_to_user_id_str = NULL;
1240                         $in_reply_to_screen_name = NULL;
1241                         if ($lastwall['parent']!=$lastwall['id']) {
1242                                 $reply = q("SELECT `item`.`id`, `item`.`contact-id` as `reply_uid`, `contact`.`nick` as `reply_author`, `item`.`author-link` AS `item-author`
1243                                                 FROM `item`,`contact` WHERE `contact`.`id`=`item`.`contact-id` AND `item`.`id` = %d", intval($lastwall['parent']));
1244                                 if (count($reply)>0) {
1245                                         $in_reply_to_status_id = intval($lastwall['parent']);
1246                                         $in_reply_to_status_id_str = (string) intval($lastwall['parent']);
1247
1248                                         $r = q("SELECT * FROM `gcontact` WHERE `nurl` = '%s'", dbesc(normalise_link($reply[0]['item-author'])));
1249                                         if ($r) {
1250                                                 if ($r[0]['nick'] == "")
1251                                                         $r[0]['nick'] = api_get_nick($r[0]["url"]);
1252
1253                                                 $in_reply_to_screen_name = (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']);
1254                                                 $in_reply_to_user_id = intval($r[0]['id']);
1255                                                 $in_reply_to_user_id_str = (string) intval($r[0]['id']);
1256                                         }
1257                                 }
1258                         }
1259
1260                         $converted = api_convert_item($lastwall);
1261
1262                         if ($type == "xml")
1263                                 $geo = "georss:point";
1264                         else
1265                                 $geo = "geo";
1266
1267                         $user_info['status'] = array(
1268                                 'text' => $converted["text"],
1269                                 'truncated' => false,
1270                                 'created_at' => api_date($lastwall['created']),
1271                                 'in_reply_to_status_id' => $in_reply_to_status_id,
1272                                 'in_reply_to_status_id_str' => $in_reply_to_status_id_str,
1273                                 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
1274                                 'id' => intval($lastwall['contact-id']),
1275                                 'id_str' => (string) $lastwall['contact-id'],
1276                                 'in_reply_to_user_id' => $in_reply_to_user_id,
1277                                 'in_reply_to_user_id_str' => $in_reply_to_user_id_str,
1278                                 'in_reply_to_screen_name' => $in_reply_to_screen_name,
1279                                 $geo => NULL,
1280                                 'favorited' => $lastwall['starred'] ? true : false,
1281                                 'statusnet_html'                => $converted["html"],
1282                                 'statusnet_conversation_id'     => $lastwall['parent'],
1283                         );
1284
1285                         if (count($converted["attachments"]) > 0)
1286                                 $user_info["status"]["attachments"] = $converted["attachments"];
1287
1288                         if (count($converted["entities"]) > 0)
1289                                 $user_info["status"]["entities"] = $converted["entities"];
1290
1291                         if (($lastwall['item_network'] != "") AND ($user_info["status"]["source"] == 'web'))
1292                                 $user_info["status"]["source"] = network_to_name($lastwall['item_network'], $user_info['url']);
1293                         if (($lastwall['item_network'] != "") AND (network_to_name($lastwall['item_network'], $user_info['url']) != $user_info["status"]["source"]))
1294                                 $user_info["status"]["source"] = trim($user_info["status"]["source"].' ('.network_to_name($lastwall['item_network'], $user_info['url']).')');
1295
1296                 }
1297
1298                 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1299                 unset($user_info["uid"]);
1300                 unset($user_info["self"]);
1301
1302                 return  api_format_data("user", $type, array('user' => $user_info));
1303
1304         }
1305         api_register_func('api/users/show','api_users_show');
1306
1307
1308         function api_users_search(&$a, $type) {
1309                 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1310
1311                 $userlist = array();
1312
1313                 if (isset($_GET["q"])) {
1314                         $r = q("SELECT id FROM `gcontact` WHERE `name`='%s'", dbesc($_GET["q"]));
1315                         if (!count($r))
1316                                 $r = q("SELECT `id` FROM `gcontact` WHERE `nick`='%s'", dbesc($_GET["q"]));
1317
1318                         if (count($r)) {
1319                                 $k = 0;
1320                                 foreach ($r AS $user) {
1321                                         $user_info = api_get_user($a, $user["id"], "json");
1322
1323                                         if ($type == "xml")
1324                                                 $userlist[$k++.":user"] = $user_info;
1325                                         else
1326                                                 $userlist[] = $user_info;
1327                                 }
1328                                 $userlist = array("users" => $userlist);
1329                         } else {
1330                                 throw new BadRequestException("User not found.");
1331                         }
1332                 } else {
1333                         throw new BadRequestException("User not found.");
1334                 }
1335                 return api_format_data("users", $type, $userlist);
1336         }
1337
1338         api_register_func('api/users/search','api_users_search');
1339
1340         /**
1341          *
1342          * http://developer.twitter.com/doc/get/statuses/home_timeline
1343          *
1344          * TODO: Optional parameters
1345          * TODO: Add reply info
1346          */
1347         function api_statuses_home_timeline(&$a, $type){
1348                 if (api_user()===false) throw new ForbiddenException();
1349
1350                 unset($_REQUEST["user_id"]);
1351                 unset($_GET["user_id"]);
1352
1353                 unset($_REQUEST["screen_name"]);
1354                 unset($_GET["screen_name"]);
1355
1356                 $user_info = api_get_user($a);
1357                 // get last newtork messages
1358
1359
1360                 // params
1361                 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1362                 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1363                 if ($page<0) $page=0;
1364                 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1365                 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1366                 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1367                 $exclude_replies = (x($_REQUEST,'exclude_replies')?1:0);
1368                 $conversation_id = (x($_REQUEST,'conversation_id')?$_REQUEST['conversation_id']:0);
1369
1370                 $start = $page*$count;
1371
1372                 $sql_extra = '';
1373                 if ($max_id > 0)
1374                         $sql_extra .= ' AND `item`.`id` <= '.intval($max_id);
1375                 if ($exclude_replies > 0)
1376                         $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
1377                 if ($conversation_id > 0)
1378                         $sql_extra .= ' AND `item`.`parent` = '.intval($conversation_id);
1379
1380                 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1381                         `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1382                         `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1383                         `contact`.`id` AS `cid`
1384                         FROM `item`
1385                         STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1386                                 AND NOT `contact`.`blocked` AND NOT `contact`.`pending`
1387                         WHERE `item`.`uid` = %d AND `verb` = '%s'
1388                         AND `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
1389                         $sql_extra
1390                         AND `item`.`id`>%d
1391                         ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1392                         intval(api_user()),
1393                         dbesc(ACTIVITY_POST),
1394                         intval($since_id),
1395                         intval($start), intval($count)
1396                 );
1397
1398                 $ret = api_format_items($r,$user_info, false, $type);
1399
1400                 // Set all posts from the query above to seen
1401                 $idarray = array();
1402                 foreach ($r AS $item)
1403                         $idarray[] = intval($item["id"]);
1404
1405                 $idlist = implode(",", $idarray);
1406
1407                 if ($idlist != "") {
1408                         $unseen = q("SELECT `id` FROM `item` WHERE `unseen` AND `id` IN (%s)", $idlist);
1409
1410                         if ($unseen)
1411                                 $r = q("UPDATE `item` SET `unseen` = 0 WHERE `unseen` AND `id` IN (%s)", $idlist);
1412                 }
1413
1414                 $data = array('status' => $ret);
1415                 switch($type){
1416                         case "atom":
1417                         case "rss":
1418                                 $data = api_rss_extra($a, $data, $user_info);
1419                                 break;
1420                 }
1421
1422                 return  api_format_data("statuses", $type, $data);
1423         }
1424         api_register_func('api/statuses/home_timeline','api_statuses_home_timeline', true);
1425         api_register_func('api/statuses/friends_timeline','api_statuses_home_timeline', true);
1426
1427         function api_statuses_public_timeline(&$a, $type){
1428                 if (api_user()===false) throw new ForbiddenException();
1429
1430                 $user_info = api_get_user($a);
1431                 // get last newtork messages
1432
1433
1434                 // params
1435                 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1436                 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1437                 if ($page<0) $page=0;
1438                 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1439                 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1440                 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1441                 $exclude_replies = (x($_REQUEST,'exclude_replies')?1:0);
1442                 $conversation_id = (x($_REQUEST,'conversation_id')?$_REQUEST['conversation_id']:0);
1443
1444                 $start = $page*$count;
1445
1446                 if ($max_id > 0)
1447                         $sql_extra = 'AND `item`.`id` <= '.intval($max_id);
1448                 if ($exclude_replies > 0)
1449                         $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
1450                 if ($conversation_id > 0)
1451                         $sql_extra .= ' AND `item`.`parent` = '.intval($conversation_id);
1452
1453                 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1454                         `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1455                         `contact`.`network`, `contact`.`thumb`, `contact`.`self`, `contact`.`writable`,
1456                         `contact`.`id` AS `cid`,
1457                         `user`.`nickname`, `user`.`hidewall`
1458                         FROM `item`
1459                         STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1460                                 AND NOT `contact`.`blocked` AND NOT `contact`.`pending`
1461                         STRAIGHT_JOIN `user` ON `user`.`uid` = `item`.`uid`
1462                                 AND NOT `user`.`hidewall`
1463                         WHERE `verb` = '%s' AND `item`.`visible` AND NOT `item`.`deleted` AND NOT `item`.`moderated`
1464                         AND `item`.`allow_cid` = ''  AND `item`.`allow_gid` = ''
1465                         AND `item`.`deny_cid`  = '' AND `item`.`deny_gid`  = ''
1466                         AND NOT `item`.`private` AND `item`.`wall`
1467                         $sql_extra
1468                         AND `item`.`id`>%d
1469                         ORDER BY `item`.`id` DESC LIMIT %d, %d ",
1470                         dbesc(ACTIVITY_POST),
1471                         intval($since_id),
1472                         intval($start),
1473                         intval($count));
1474
1475                 $ret = api_format_items($r,$user_info, false, $type);
1476
1477
1478                 $data = array('status' => $ret);
1479                 switch($type){
1480                         case "atom":
1481                         case "rss":
1482                                 $data = api_rss_extra($a, $data, $user_info);
1483                                 break;
1484                 }
1485
1486                 return  api_format_data("statuses", $type, $data);
1487         }
1488         api_register_func('api/statuses/public_timeline','api_statuses_public_timeline', true);
1489
1490         /**
1491          *
1492          */
1493         function api_statuses_show(&$a, $type){
1494                 if (api_user()===false) throw new ForbiddenException();
1495
1496                 $user_info = api_get_user($a);
1497
1498                 // params
1499                 $id = intval($a->argv[3]);
1500
1501                 if ($id == 0)
1502                         $id = intval($_REQUEST["id"]);
1503
1504                 // Hotot workaround
1505                 if ($id == 0)
1506                         $id = intval($a->argv[4]);
1507
1508                 logger('API: api_statuses_show: '.$id);
1509
1510                 $conversation = (x($_REQUEST,'conversation')?1:0);
1511
1512                 $sql_extra = '';
1513                 if ($conversation)
1514                         $sql_extra .= " AND `item`.`parent` = %d ORDER BY `id` ASC ";
1515                 else
1516                         $sql_extra .= " AND `item`.`id` = %d";
1517
1518                 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1519                         `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1520                         `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1521                         `contact`.`id` AS `cid`
1522                         FROM `item`
1523                         INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1524                                 AND NOT `contact`.`blocked` AND NOT `contact`.`pending`
1525                         WHERE `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
1526                         AND `item`.`uid` = %d AND `item`.`verb` = '%s'
1527                         $sql_extra",
1528                         intval(api_user()),
1529                         dbesc(ACTIVITY_POST),
1530                         intval($id)
1531                 );
1532
1533                 if (!$r) {
1534                         throw new BadRequestException("There is no status with this id.");
1535                 }
1536
1537                 $ret = api_format_items($r,$user_info, false, $type);
1538
1539                 if ($conversation) {
1540                         $data = array('status' => $ret);
1541                         return api_format_data("statuses", $type, $data);
1542                 } else {
1543                         $data = array('status' => $ret[0]);
1544                         return  api_format_data("status", $type, $data);
1545                 }
1546         }
1547         api_register_func('api/statuses/show','api_statuses_show', true);
1548
1549
1550         /**
1551          *
1552          */
1553         function api_conversation_show(&$a, $type){
1554                 if (api_user()===false) throw new ForbiddenException();
1555
1556                 $user_info = api_get_user($a);
1557
1558                 // params
1559                 $id = intval($a->argv[3]);
1560                 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1561                 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1562                 if ($page<0) $page=0;
1563                 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1564                 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1565
1566                 $start = $page*$count;
1567
1568                 if ($id == 0)
1569                         $id = intval($_REQUEST["id"]);
1570
1571                 // Hotot workaround
1572                 if ($id == 0)
1573                         $id = intval($a->argv[4]);
1574
1575                 logger('API: api_conversation_show: '.$id);
1576
1577                 $r = q("SELECT `parent` FROM `item` WHERE `id` = %d", intval($id));
1578                 if ($r)
1579                         $id = $r[0]["parent"];
1580
1581                 $sql_extra = '';
1582
1583                 if ($max_id > 0)
1584                         $sql_extra = ' AND `item`.`id` <= '.intval($max_id);
1585
1586                 // Not sure why this query was so complicated. We should keep it here for a while,
1587                 // just to make sure that we really don't need it.
1588                 //      FROM `item` INNER JOIN (SELECT `uri`,`parent` FROM `item` WHERE `id` = %d) AS `temp1`
1589                 //      ON (`item`.`thr-parent` = `temp1`.`uri` AND `item`.`parent` = `temp1`.`parent`)
1590
1591                 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1592                         `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1593                         `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1594                         `contact`.`id` AS `cid`
1595                         FROM `item`
1596                         STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1597                                 AND NOT `contact`.`blocked` AND NOT `contact`.`pending`
1598                         WHERE `item`.`parent` = %d AND `item`.`visible`
1599                         AND NOT `item`.`moderated` AND NOT `item`.`deleted`
1600                         AND `item`.`uid` = %d AND `item`.`verb` = '%s'
1601                         AND `item`.`id`>%d $sql_extra
1602                         ORDER BY `item`.`id` DESC LIMIT %d ,%d",
1603                         intval($id), intval(api_user()),
1604                         dbesc(ACTIVITY_POST),
1605                         intval($since_id),
1606                         intval($start), intval($count)
1607                 );
1608
1609                 if (!$r)
1610                         throw new BadRequestException("There is no conversation with this id.");
1611
1612                 $ret = api_format_items($r,$user_info, false, $type);
1613
1614                 $data = array('status' => $ret);
1615                 return api_format_data("statuses", $type, $data);
1616         }
1617         api_register_func('api/conversation/show','api_conversation_show', true);
1618         api_register_func('api/statusnet/conversation','api_conversation_show', true);
1619
1620
1621         /**
1622          *
1623          */
1624         function api_statuses_repeat(&$a, $type){
1625                 global $called_api;
1626
1627                 if (api_user()===false) throw new ForbiddenException();
1628
1629                 $user_info = api_get_user($a);
1630
1631                 // params
1632                 $id = intval($a->argv[3]);
1633
1634                 if ($id == 0)
1635                         $id = intval($_REQUEST["id"]);
1636
1637                 // Hotot workaround
1638                 if ($id == 0)
1639                         $id = intval($a->argv[4]);
1640
1641                 logger('API: api_statuses_repeat: '.$id);
1642
1643                 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`, `contact`.`nick` as `reply_author`,
1644                         `contact`.`name`, `contact`.`photo` as `reply_photo`, `contact`.`url` as `reply_url`, `contact`.`rel`,
1645                         `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1646                         `contact`.`id` AS `cid`
1647                         FROM `item`
1648                         INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1649                                 AND NOT `contact`.`blocked` AND NOT `contact`.`pending`
1650                         WHERE `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
1651                         AND NOT `item`.`private` AND `item`.`allow_cid` = '' AND `item`.`allow`.`gid` = ''
1652                         AND `item`.`deny_cid` = '' AND `item`.`deny_gid` = ''
1653                         $sql_extra
1654                         AND `item`.`id`=%d",
1655                         intval($id)
1656                 );
1657
1658                 if ($r[0]['body'] != "") {
1659                         if (!intval(get_config('system','old_share'))) {
1660                                 if (strpos($r[0]['body'], "[/share]") !== false) {
1661                                         $pos = strpos($r[0]['body'], "[share");
1662                                         $post = substr($r[0]['body'], $pos);
1663                                 } else {
1664                                         $post = share_header($r[0]['author-name'], $r[0]['author-link'], $r[0]['author-avatar'], $r[0]['guid'], $r[0]['created'], $r[0]['plink']);
1665
1666                                         $post .= $r[0]['body'];
1667                                         $post .= "[/share]";
1668                                 }
1669                                 $_REQUEST['body'] = $post;
1670                         } else
1671                                 $_REQUEST['body'] = html_entity_decode("&#x2672; ", ENT_QUOTES, 'UTF-8')."[url=".$r[0]['reply_url']."]".$r[0]['reply_author']."[/url] \n".$r[0]['body'];
1672
1673                         $_REQUEST['profile_uid'] = api_user();
1674                         $_REQUEST['type'] = 'wall';
1675                         $_REQUEST['api_source'] = true;
1676
1677                         if (!x($_REQUEST, "source"))
1678                                 $_REQUEST["source"] = api_source();
1679
1680                         item_post($a);
1681                 } else
1682                         throw new ForbiddenException();
1683
1684                 // this should output the last post (the one we just posted).
1685                 $called_api = null;
1686                 return(api_status_show($a,$type));
1687         }
1688         api_register_func('api/statuses/retweet','api_statuses_repeat', true, API_METHOD_POST);
1689
1690         /**
1691          *
1692          */
1693         function api_statuses_destroy(&$a, $type){
1694                 if (api_user()===false) throw new ForbiddenException();
1695
1696                 $user_info = api_get_user($a);
1697
1698                 // params
1699                 $id = intval($a->argv[3]);
1700
1701                 if ($id == 0)
1702                         $id = intval($_REQUEST["id"]);
1703
1704                 // Hotot workaround
1705                 if ($id == 0)
1706                         $id = intval($a->argv[4]);
1707
1708                 logger('API: api_statuses_destroy: '.$id);
1709
1710                 $ret = api_statuses_show($a, $type);
1711
1712                 drop_item($id, false);
1713
1714                 return($ret);
1715         }
1716         api_register_func('api/statuses/destroy','api_statuses_destroy', true, API_METHOD_DELETE);
1717
1718         /**
1719          *
1720          * http://developer.twitter.com/doc/get/statuses/mentions
1721          *
1722          */
1723         function api_statuses_mentions(&$a, $type){
1724                 if (api_user()===false) throw new ForbiddenException();
1725
1726                 unset($_REQUEST["user_id"]);
1727                 unset($_GET["user_id"]);
1728
1729                 unset($_REQUEST["screen_name"]);
1730                 unset($_GET["screen_name"]);
1731
1732                 $user_info = api_get_user($a);
1733                 // get last newtork messages
1734
1735
1736                 // params
1737                 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1738                 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1739                 if ($page<0) $page=0;
1740                 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1741                 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1742                 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1743
1744                 $start = $page*$count;
1745
1746                 // Ugly code - should be changed
1747                 $myurl = $a->get_baseurl() . '/profile/'. $a->user['nickname'];
1748                 $myurl = substr($myurl,strpos($myurl,'://')+3);
1749                 //$myurl = str_replace(array('www.','.'),array('','\\.'),$myurl);
1750                 $myurl = str_replace('www.','',$myurl);
1751                 $diasp_url = str_replace('/profile/','/u/',$myurl);
1752
1753                 if ($max_id > 0)
1754                         $sql_extra = ' AND `item`.`id` <= '.intval($max_id);
1755
1756                 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1757                         `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1758                         `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1759                         `contact`.`id` AS `cid`
1760                         FROM `item` FORCE INDEX (`uid_id`)
1761                         STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1762                                 AND NOT `contact`.`blocked` AND NOT `contact`.`pending`
1763                         WHERE `item`.`uid` = %d AND `verb` = '%s'
1764                         AND NOT (`item`.`author-link` IN ('https://%s', 'http://%s'))
1765                         AND `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
1766                         AND `item`.`parent` IN (SELECT `iid` FROM `thread` WHERE `uid` = %d AND `mention` AND !`ignored`)
1767                         $sql_extra
1768                         AND `item`.`id`>%d
1769                         ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1770                         intval(api_user()),
1771                         dbesc(ACTIVITY_POST),
1772                         dbesc(protect_sprintf($myurl)),
1773                         dbesc(protect_sprintf($myurl)),
1774                         intval(api_user()),
1775                         intval($since_id),
1776                         intval($start), intval($count)
1777                 );
1778
1779                 $ret = api_format_items($r,$user_info, false, $type);
1780
1781
1782                 $data = array('status' => $ret);
1783                 switch($type){
1784                         case "atom":
1785                         case "rss":
1786                                 $data = api_rss_extra($a, $data, $user_info);
1787                                 break;
1788                 }
1789
1790                 return  api_format_data("statuses", $type, $data);
1791         }
1792         api_register_func('api/statuses/mentions','api_statuses_mentions', true);
1793         api_register_func('api/statuses/replies','api_statuses_mentions', true);
1794
1795
1796         function api_statuses_user_timeline(&$a, $type){
1797                 if (api_user()===false) throw new ForbiddenException();
1798
1799                 $user_info = api_get_user($a);
1800                 // get last network messages
1801
1802                 logger("api_statuses_user_timeline: api_user: ". api_user() .
1803                            "\nuser_info: ".print_r($user_info, true) .
1804                            "\n_REQUEST:  ".print_r($_REQUEST, true),
1805                            LOGGER_DEBUG);
1806
1807                 // params
1808                 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1809                 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1810                 if ($page<0) $page=0;
1811                 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1812                 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1813                 $exclude_replies = (x($_REQUEST,'exclude_replies')?1:0);
1814                 $conversation_id = (x($_REQUEST,'conversation_id')?$_REQUEST['conversation_id']:0);
1815
1816                 $start = $page*$count;
1817
1818                 $sql_extra = '';
1819                 if ($user_info['self']==1)
1820                         $sql_extra .= " AND `item`.`wall` = 1 ";
1821
1822                 if ($exclude_replies > 0)
1823                         $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
1824                 if ($conversation_id > 0)
1825                         $sql_extra .= ' AND `item`.`parent` = '.intval($conversation_id);
1826
1827                 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1828                         `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1829                         `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1830                         `contact`.`id` AS `cid`
1831                         FROM `item` FORCE INDEX (`uid_contactid_id`)
1832                         STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1833                                 AND NOT `contact`.`blocked` AND NOT `contact`.`pending`
1834                         WHERE `item`.`uid` = %d AND `verb` = '%s'
1835                         AND `item`.`contact-id` = %d
1836                         AND `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
1837                         $sql_extra
1838                         AND `item`.`id`>%d
1839                         ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1840                         intval(api_user()),
1841                         dbesc(ACTIVITY_POST),
1842                         intval($user_info['cid']),
1843                         intval($since_id),
1844                         intval($start), intval($count)
1845                 );
1846
1847                 $ret = api_format_items($r,$user_info, true, $type);
1848
1849                 $data = array('status' => $ret);
1850                 switch($type){
1851                         case "atom":
1852                         case "rss":
1853                                 $data = api_rss_extra($a, $data, $user_info);
1854                 }
1855
1856                 return  api_format_data("statuses", $type, $data);
1857         }
1858         api_register_func('api/statuses/user_timeline','api_statuses_user_timeline', true);
1859
1860
1861         /**
1862          * Star/unstar an item
1863          * param: id : id of the item
1864          *
1865          * api v1 : https://web.archive.org/web/20131019055350/https://dev.twitter.com/docs/api/1/post/favorites/create/%3Aid
1866          */
1867         function api_favorites_create_destroy(&$a, $type){
1868                 if (api_user()===false) throw new ForbiddenException();
1869
1870                 // for versioned api.
1871                 /// @TODO We need a better global soluton
1872                 $action_argv_id=2;
1873                 if ($a->argv[1]=="1.1") $action_argv_id=3;
1874
1875                 if ($a->argc<=$action_argv_id) throw new BadRequestException("Invalid request.");
1876                 $action = str_replace(".".$type,"",$a->argv[$action_argv_id]);
1877                 if ($a->argc==$action_argv_id+2) {
1878                         $itemid = intval($a->argv[$action_argv_id+1]);
1879                 } else {
1880                         $itemid = intval($_REQUEST['id']);
1881                 }
1882
1883                 $item = q("SELECT * FROM item WHERE id=%d AND uid=%d",
1884                                 $itemid, api_user());
1885
1886                 if ($item===false || count($item)==0)
1887                         throw new BadRequestException("Invalid item.");
1888
1889                 switch($action){
1890                         case "create":
1891                                 $item[0]['starred']=1;
1892                                 break;
1893                         case "destroy":
1894                                 $item[0]['starred']=0;
1895                                 break;
1896                         default:
1897                                 throw new BadRequestException("Invalid action ".$action);
1898                 }
1899                 $r = q("UPDATE item SET starred=%d WHERE id=%d AND uid=%d",
1900                                 $item[0]['starred'], $itemid, api_user());
1901
1902                 q("UPDATE thread SET starred=%d WHERE iid=%d AND uid=%d",
1903                         $item[0]['starred'], $itemid, api_user());
1904
1905                 if ($r===false)
1906                         throw InternalServerErrorException("DB error");
1907
1908
1909                 $user_info = api_get_user($a);
1910                 $rets = api_format_items($item,$user_info, false, $type);
1911                 $ret = $rets[0];
1912
1913                 $data = array('status' => $ret);
1914                 switch($type){
1915                         case "atom":
1916                         case "rss":
1917                                 $data = api_rss_extra($a, $data, $user_info);
1918                 }
1919
1920                 return api_format_data("status", $type, $data);
1921         }
1922         api_register_func('api/favorites/create', 'api_favorites_create_destroy', true, API_METHOD_POST);
1923         api_register_func('api/favorites/destroy', 'api_favorites_create_destroy', true, API_METHOD_DELETE);
1924
1925         function api_favorites(&$a, $type){
1926                 global $called_api;
1927
1928                 if (api_user()===false) throw new ForbiddenException();
1929
1930                 $called_api= array();
1931
1932                 $user_info = api_get_user($a);
1933
1934                 // in friendica starred item are private
1935                 // return favorites only for self
1936                 logger('api_favorites: self:' . $user_info['self']);
1937
1938                 if ($user_info['self']==0) {
1939                         $ret = array();
1940                 } else {
1941                         $sql_extra = "";
1942
1943                         // params
1944                         $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1945                         $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1946                         $count = (x($_GET,'count')?$_GET['count']:20);
1947                         $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1948                         if ($page<0) $page=0;
1949
1950                         $start = $page*$count;
1951
1952                         if ($max_id > 0)
1953                                 $sql_extra .= ' AND `item`.`id` <= '.intval($max_id);
1954
1955                         $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1956                                 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1957                                 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1958                                 `contact`.`id` AS `cid`
1959                                 FROM `item`, `contact`
1960                                 WHERE `item`.`uid` = %d
1961                                 AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1962                                 AND `item`.`starred` = 1
1963                                 AND `contact`.`id` = `item`.`contact-id`
1964                                 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1965                                 $sql_extra
1966                                 AND `item`.`id`>%d
1967                                 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1968                                 intval(api_user()),
1969                                 intval($since_id),
1970                                 intval($start), intval($count)
1971                         );
1972
1973                         $ret = api_format_items($r,$user_info, false, $type);
1974
1975                 }
1976
1977                 $data = array('status' => $ret);
1978                 switch($type){
1979                         case "atom":
1980                         case "rss":
1981                                 $data = api_rss_extra($a, $data, $user_info);
1982                 }
1983
1984                 return  api_format_data("statuses", $type, $data);
1985         }
1986         api_register_func('api/favorites','api_favorites', true);
1987
1988         function api_format_messages($item, $recipient, $sender) {
1989                 // standard meta information
1990                 $ret=Array(
1991                                 'id'                    => $item['id'],
1992                                 'sender_id'             => $sender['id'] ,
1993                                 'text'                  => "",
1994                                 'recipient_id'          => $recipient['id'],
1995                                 'created_at'            => api_date($item['created']),
1996                                 'sender_screen_name'    => $sender['screen_name'],
1997                                 'recipient_screen_name' => $recipient['screen_name'],
1998                                 'sender'                => $sender,
1999                                 'recipient'             => $recipient,
2000                 );
2001
2002                 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2003                 unset($ret["sender"]["uid"]);
2004                 unset($ret["sender"]["self"]);
2005                 unset($ret["recipient"]["uid"]);
2006                 unset($ret["recipient"]["self"]);
2007
2008                 //don't send title to regular StatusNET requests to avoid confusing these apps
2009                 if (x($_GET, 'getText')) {
2010                         $ret['title'] = $item['title'] ;
2011                         if ($_GET["getText"] == "html") {
2012                                 $ret['text'] = bbcode($item['body'], false, false);
2013                         }
2014                         elseif ($_GET["getText"] == "plain") {
2015                                 //$ret['text'] = html2plain(bbcode($item['body'], false, false, true), 0);
2016                                 $ret['text'] = trim(html2plain(bbcode(api_clean_plain_items($item['body']), false, false, 2, true), 0));
2017                         }
2018                 }
2019                 else {
2020                         $ret['text'] = $item['title']."\n".html2plain(bbcode(api_clean_plain_items($item['body']), false, false, 2, true), 0);
2021                 }
2022                 if (isset($_GET["getUserObjects"]) && $_GET["getUserObjects"] == "false") {
2023                         unset($ret['sender']);
2024                         unset($ret['recipient']);
2025                 }
2026
2027                 return $ret;
2028         }
2029
2030         function api_convert_item($item) {
2031                 $body = $item['body'];
2032                 $attachments = api_get_attachments($body);
2033
2034                 // Workaround for ostatus messages where the title is identically to the body
2035                 $html = bbcode(api_clean_plain_items($body), false, false, 2, true);
2036                 $statusbody = trim(html2plain($html, 0));
2037
2038                 // handle data: images
2039                 $statusbody = api_format_items_embeded_images($item,$statusbody);
2040
2041                 $statustitle = trim($item['title']);
2042
2043                 if (($statustitle != '') and (strpos($statusbody, $statustitle) !== false))
2044                         $statustext = trim($statusbody);
2045                 else
2046                         $statustext = trim($statustitle."\n\n".$statusbody);
2047
2048                 if (($item["network"] == NETWORK_FEED) and (strlen($statustext)> 1000))
2049                         $statustext = substr($statustext, 0, 1000)."... \n".$item["plink"];
2050
2051                 $statushtml = trim(bbcode($body, false, false));
2052
2053                 $search = array("<br>", "<blockquote>", "</blockquote>",
2054                                 "<h1>", "</h1>", "<h2>", "</h2>",
2055                                 "<h3>", "</h3>", "<h4>", "</h4>",
2056                                 "<h5>", "</h5>", "<h6>", "</h6>");
2057                 $replace = array("<br>\n", "\n<blockquote>", "</blockquote>\n",
2058                                 "\n<h1>", "</h1>\n", "\n<h2>", "</h2>\n",
2059                                 "\n<h3>", "</h3>\n", "\n<h4>", "</h4>\n",
2060                                 "\n<h5>", "</h5>\n", "\n<h6>", "</h6>\n");
2061                 $statushtml = str_replace($search, $replace, $statushtml);
2062
2063                 if ($item['title'] != "")
2064                         $statushtml = "<h4>".bbcode($item['title'])."</h4>\n".$statushtml;
2065
2066                 $entities = api_get_entitities($statustext, $body);
2067
2068                 return array(
2069                         "text" => $statustext,
2070                         "html" => $statushtml,
2071                         "attachments" => $attachments,
2072                         "entities" => $entities
2073                 );
2074         }
2075
2076         function api_get_attachments(&$body) {
2077
2078                 $text = $body;
2079                 $text = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $text);
2080
2081                 $URLSearchString = "^\[\]";
2082                 $ret = preg_match_all("/\[img\]([$URLSearchString]*)\[\/img\]/ism", $text, $images);
2083
2084                 if (!$ret)
2085                         return false;
2086
2087                 $attachments = array();
2088
2089                 foreach ($images[1] AS $image) {
2090                         $imagedata = get_photo_info($image);
2091
2092                         if ($imagedata)
2093                                 $attachments[] = array("url" => $image, "mimetype" => $imagedata["mime"], "size" => $imagedata["size"]);
2094                 }
2095
2096                 if (strstr($_SERVER['HTTP_USER_AGENT'], "AndStatus"))
2097                         foreach ($images[0] AS $orig)
2098                                 $body = str_replace($orig, "", $body);
2099
2100                 return $attachments;
2101         }
2102
2103         function api_get_entitities(&$text, $bbcode) {
2104                 /*
2105                 To-Do:
2106                 * Links at the first character of the post
2107                 */
2108
2109                 $a = get_app();
2110
2111                 $include_entities = strtolower(x($_REQUEST,'include_entities')?$_REQUEST['include_entities']:"false");
2112
2113                 if ($include_entities != "true") {
2114
2115                         preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2116
2117                         foreach ($images[1] AS $image) {
2118                                 $replace = proxy_url($image);
2119                                 $text = str_replace($image, $replace, $text);
2120                         }
2121                         return array();
2122                 }
2123
2124                 $bbcode = bb_CleanPictureLinks($bbcode);
2125
2126                 // Change pure links in text to bbcode uris
2127                 $bbcode = preg_replace("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", '$1[url=$2]$2[/url]', $bbcode);
2128
2129                 $entities = array();
2130                 $entities["hashtags"] = array();
2131                 $entities["symbols"] = array();
2132                 $entities["urls"] = array();
2133                 $entities["user_mentions"] = array();
2134
2135                 $URLSearchString = "^\[\]";
2136
2137                 $bbcode = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'#$2',$bbcode);
2138
2139                 $bbcode = preg_replace("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism",'[url=$1]$2[/url]',$bbcode);
2140                 //$bbcode = preg_replace("/\[url\](.*?)\[\/url\]/ism",'[url=$1]$1[/url]',$bbcode);
2141                 $bbcode = preg_replace("/\[video\](.*?)\[\/video\]/ism",'[url=$1]$1[/url]',$bbcode);
2142
2143                 $bbcode = preg_replace("/\[youtube\]([A-Za-z0-9\-_=]+)(.*?)\[\/youtube\]/ism",
2144                                         '[url=https://www.youtube.com/watch?v=$1]https://www.youtube.com/watch?v=$1[/url]', $bbcode);
2145                 $bbcode = preg_replace("/\[youtube\](.*?)\[\/youtube\]/ism",'[url=$1]$1[/url]',$bbcode);
2146
2147                 $bbcode = preg_replace("/\[vimeo\]([0-9]+)(.*?)\[\/vimeo\]/ism",
2148                                         '[url=https://vimeo.com/$1]https://vimeo.com/$1[/url]', $bbcode);
2149                 $bbcode = preg_replace("/\[vimeo\](.*?)\[\/vimeo\]/ism",'[url=$1]$1[/url]',$bbcode);
2150
2151                 $bbcode = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $bbcode);
2152
2153                 //preg_match_all("/\[url\]([$URLSearchString]*)\[\/url\]/ism", $bbcode, $urls1);
2154                 preg_match_all("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $bbcode, $urls);
2155
2156                 $ordered_urls = array();
2157                 foreach ($urls[1] AS $id=>$url) {
2158                         //$start = strpos($text, $url, $offset);
2159                         $start = iconv_strpos($text, $url, 0, "UTF-8");
2160                         if (!($start === false))
2161                                 $ordered_urls[$start] = array("url" => $url, "title" => $urls[2][$id]);
2162                 }
2163
2164                 ksort($ordered_urls);
2165
2166                 $offset = 0;
2167                 //foreach ($urls[1] AS $id=>$url) {
2168                 foreach ($ordered_urls AS $url) {
2169                         if ((substr($url["title"], 0, 7) != "http://") AND (substr($url["title"], 0, 8) != "https://") AND
2170                                 !strpos($url["title"], "http://") AND !strpos($url["title"], "https://"))
2171                                 $display_url = $url["title"];
2172                         else {
2173                                 $display_url = str_replace(array("http://www.", "https://www."), array("", ""), $url["url"]);
2174                                 $display_url = str_replace(array("http://", "https://"), array("", ""), $display_url);
2175
2176                                 if (strlen($display_url) > 26)
2177                                         $display_url = substr($display_url, 0, 25)."…";
2178                         }
2179
2180                         //$start = strpos($text, $url, $offset);
2181                         $start = iconv_strpos($text, $url["url"], $offset, "UTF-8");
2182                         if (!($start === false)) {
2183                                 $entities["urls"][] = array("url" => $url["url"],
2184                                                                 "expanded_url" => $url["url"],
2185                                                                 "display_url" => $display_url,
2186                                                                 "indices" => array($start, $start+strlen($url["url"])));
2187                                 $offset = $start + 1;
2188                         }
2189                 }
2190
2191                 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2192                 $ordered_images = array();
2193                 foreach ($images[1] AS $image) {
2194                         //$start = strpos($text, $url, $offset);
2195                         $start = iconv_strpos($text, $image, 0, "UTF-8");
2196                         if (!($start === false))
2197                                 $ordered_images[$start] = $image;
2198                 }
2199                 //$entities["media"] = array();
2200                 $offset = 0;
2201
2202                 foreach ($ordered_images AS $url) {
2203                         $display_url = str_replace(array("http://www.", "https://www."), array("", ""), $url);
2204                         $display_url = str_replace(array("http://", "https://"), array("", ""), $display_url);
2205
2206                         if (strlen($display_url) > 26)
2207                                 $display_url = substr($display_url, 0, 25)."…";
2208
2209                         $start = iconv_strpos($text, $url, $offset, "UTF-8");
2210                         if (!($start === false)) {
2211                                 $image = get_photo_info($url);
2212                                 if ($image) {
2213                                         // If image cache is activated, then use the following sizes:
2214                                         // thumb  (150), small (340), medium (600) and large (1024)
2215                                         if (!get_config("system", "proxy_disabled")) {
2216                                                 $media_url = proxy_url($url);
2217
2218                                                 $sizes = array();
2219                                                 $scale = scale_image($image[0], $image[1], 150);
2220                                                 $sizes["thumb"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2221
2222                                                 if (($image[0] > 150) OR ($image[1] > 150)) {
2223                                                         $scale = scale_image($image[0], $image[1], 340);
2224                                                         $sizes["small"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2225                                                 }
2226
2227                                                 $scale = scale_image($image[0], $image[1], 600);
2228                                                 $sizes["medium"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2229
2230                                                 if (($image[0] > 600) OR ($image[1] > 600)) {
2231                                                         $scale = scale_image($image[0], $image[1], 1024);
2232                                                         $sizes["large"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2233                                                 }
2234                                         } else {
2235                                                 $media_url = $url;
2236                                                 $sizes["medium"] = array("w" => $image[0], "h" => $image[1], "resize" => "fit");
2237                                         }
2238
2239                                         $entities["media"][] = array(
2240                                                                 "id" => $start+1,
2241                                                                 "id_str" => (string)$start+1,
2242                                                                 "indices" => array($start, $start+strlen($url)),
2243                                                                 "media_url" => normalise_link($media_url),
2244                                                                 "media_url_https" => $media_url,
2245                                                                 "url" => $url,
2246                                                                 "display_url" => $display_url,
2247                                                                 "expanded_url" => $url,
2248                                                                 "type" => "photo",
2249                                                                 "sizes" => $sizes);
2250                                 }
2251                                 $offset = $start + 1;
2252                         }
2253                 }
2254
2255                 return($entities);
2256         }
2257         function api_format_items_embeded_images(&$item, $text){
2258                 $a = get_app();
2259                 $text = preg_replace_callback(
2260                                 "|data:image/([^;]+)[^=]+=*|m",
2261                                 function($match) use ($a, $item) {
2262                                         return $a->get_baseurl()."/display/".$item['guid'];
2263                                 },
2264                                 $text);
2265                 return $text;
2266         }
2267
2268
2269         /**
2270          * @brief return <a href='url'>name</a> as array
2271          *
2272          * @param string $txt
2273          * @return array
2274          *                      name => 'name'
2275          *                      'url => 'url'
2276          */
2277         function api_contactlink_to_array($txt) {
2278                 $match = array();
2279                 $r = preg_match_all('|<a href="([^"]*)">([^<]*)</a>|', $txt, $match);
2280                 if ($r && count($match)==3) {
2281                         $res = array(
2282                                 'name' => $match[2],
2283                                 'url' => $match[1]
2284                         );
2285                 } else {
2286                         $res = array(
2287                                 'name' => $text,
2288                                 'url' => ""
2289                         );
2290                 }
2291                 return $res;
2292         }
2293
2294
2295         /**
2296          * @brief return likes, dislikes and attend status for item
2297          *
2298          * @param array $item
2299          * @return array
2300          *                      likes => int count
2301          *                      dislikes => int count
2302          */
2303         function api_format_items_activities(&$item, $type = "json") {
2304                 $activities = array(
2305                         'like' => array(),
2306                         'dislike' => array(),
2307                         'attendyes' => array(),
2308                         'attendno' => array(),
2309                         'attendmaybe' => array()
2310                 );
2311                 $items = q('SELECT * FROM item
2312                                         WHERE uid=%d AND `thr-parent`="%s" AND visible AND NOT deleted',
2313                                         intval($item['uid']),
2314                                         dbesc($item['uri']));
2315                 foreach ($items as $i){
2316                         builtin_activity_puller($i, $activities);
2317                 }
2318
2319                 if ($type == "xml") {
2320                         $xml_activities = array();
2321                         foreach ($activities as $k => $v)
2322                                 $xml_activities["friendica:".$k] = $v;
2323
2324                         $activities = $xml_activities;
2325                 }
2326
2327                 $res = array();
2328                 $uri = $item['uri']."-l";
2329                 foreach($activities as $k => $v) {
2330                         $res[$k] = ( x($v,$uri) ? array_map("api_contactlink_to_array", $v[$uri]) : array() );
2331                 }
2332
2333                 return $res;
2334         }
2335
2336         /**
2337          * @brief format items to be returned by api
2338          *
2339          * @param array $r array of items
2340          * @param array $user_info
2341          * @param bool $filter_user filter items by $user_info
2342          */
2343         function api_format_items($r,$user_info, $filter_user = false, $type = "json") {
2344
2345                 $a = get_app();
2346                 $ret = Array();
2347
2348                 foreach($r as $item) {
2349
2350                         localize_item($item);
2351                         list($status_user, $owner_user) = api_item_get_user($a,$item);
2352
2353                         // Look if the posts are matching if they should be filtered by user id
2354                         if ($filter_user AND ($status_user["id"] != $user_info["id"]))
2355                                 continue;
2356
2357                         if ($item['thr-parent'] != $item['uri']) {
2358                                 $r = q("SELECT id FROM item WHERE uid=%d AND uri='%s' LIMIT 1",
2359                                         intval(api_user()),
2360                                         dbesc($item['thr-parent']));
2361                                 if ($r)
2362                                         $in_reply_to_status_id = intval($r[0]['id']);
2363                                 else
2364                                         $in_reply_to_status_id = intval($item['parent']);
2365
2366                                 $in_reply_to_status_id_str = (string) intval($item['parent']);
2367
2368                                 $in_reply_to_screen_name = NULL;
2369                                 $in_reply_to_user_id = NULL;
2370                                 $in_reply_to_user_id_str = NULL;
2371
2372                                 $r = q("SELECT `author-link` FROM item WHERE uid=%d AND id=%d LIMIT 1",
2373                                         intval(api_user()),
2374                                         intval($in_reply_to_status_id));
2375                                 if ($r) {
2376                                         $r = q("SELECT * FROM `gcontact` WHERE `url` = '%s'", dbesc(normalise_link($r[0]['author-link'])));
2377
2378                                         if ($r) {
2379                                                 if ($r[0]['nick'] == "")
2380                                                         $r[0]['nick'] = api_get_nick($r[0]["url"]);
2381
2382                                                 $in_reply_to_screen_name = (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']);
2383                                                 $in_reply_to_user_id = intval($r[0]['id']);
2384                                                 $in_reply_to_user_id_str = (string) intval($r[0]['id']);
2385                                         }
2386                                 }
2387                         } else {
2388                                 $in_reply_to_screen_name = NULL;
2389                                 $in_reply_to_user_id = NULL;
2390                                 $in_reply_to_status_id = NULL;
2391                                 $in_reply_to_user_id_str = NULL;
2392                                 $in_reply_to_status_id_str = NULL;
2393                         }
2394
2395                         $converted = api_convert_item($item);
2396
2397                         if ($type == "xml")
2398                                 $geo = "georss:point";
2399                         else
2400                                 $geo = "geo";
2401
2402                         $status = array(
2403                                 'text'          => $converted["text"],
2404                                 'truncated' => False,
2405                                 'created_at'=> api_date($item['created']),
2406                                 'in_reply_to_status_id' => $in_reply_to_status_id,
2407                                 'in_reply_to_status_id_str' => $in_reply_to_status_id_str,
2408                                 'source'    => (($item['app']) ? $item['app'] : 'web'),
2409                                 'id'            => intval($item['id']),
2410                                 'id_str'        => (string) intval($item['id']),
2411                                 'in_reply_to_user_id' => $in_reply_to_user_id,
2412                                 'in_reply_to_user_id_str' => $in_reply_to_user_id_str,
2413                                 'in_reply_to_screen_name' => $in_reply_to_screen_name,
2414                                 $geo => NULL,
2415                                 'favorited' => $item['starred'] ? true : false,
2416                                 'user' =>  $status_user ,
2417                                 'friendica_owner' => $owner_user,
2418                                 //'entities' => NULL,
2419                                 'statusnet_html'                => $converted["html"],
2420                                 'statusnet_conversation_id'     => $item['parent'],
2421                                 'friendica_activities' => api_format_items_activities($item, $type),
2422                         );
2423
2424                         if (count($converted["attachments"]) > 0)
2425                                 $status["attachments"] = $converted["attachments"];
2426
2427                         if (count($converted["entities"]) > 0)
2428                                 $status["entities"] = $converted["entities"];
2429
2430                         if (($item['item_network'] != "") AND ($status["source"] == 'web'))
2431                                 $status["source"] = network_to_name($item['item_network'], $user_info['url']);
2432                         else if (($item['item_network'] != "") AND (network_to_name($item['item_network'], $user_info['url']) != $status["source"]))
2433                                 $status["source"] = trim($status["source"].' ('.network_to_name($item['item_network'], $user_info['url']).')');
2434
2435
2436                         // Retweets are only valid for top postings
2437                         // It doesn't work reliable with the link if its a feed
2438                         #$IsRetweet = ($item['owner-link'] != $item['author-link']);
2439                         #if ($IsRetweet)
2440                         #       $IsRetweet = (($item['owner-name'] != $item['author-name']) OR ($item['owner-avatar'] != $item['author-avatar']));
2441
2442
2443                         if ($item["id"] == $item["parent"]) {
2444                                 $retweeted_item = api_share_as_retweet($item);
2445                                 if ($retweeted_item !== false) {
2446                                         $retweeted_status = $status;
2447                                         try {
2448                                                 $retweeted_status["user"] = api_get_user($a,$retweeted_item["author-link"]);
2449                                         } catch( BadRequestException $e ) {
2450                                                 // user not found. should be found?
2451                                                 /// @todo check if the user should be always found
2452                                                 $retweeted_status["user"] = array();
2453                                         }
2454
2455                                         $rt_converted = api_convert_item($retweeted_item);
2456
2457                                         $retweeted_status['text'] = $rt_converted["text"];
2458                                         $retweeted_status['statusnet_html'] = $rt_converted["html"];
2459                                         $retweeted_status['friendica_activities'] = api_format_items_activities($retweeted_item, $type);
2460                                         $retweeted_status['created_at'] =  api_date($retweeted_item['created']);
2461                                         $status['retweeted_status'] = $retweeted_status;
2462                                 }
2463                         }
2464
2465                         // "uid" and "self" are only needed for some internal stuff, so remove it from here
2466                         unset($status["user"]["uid"]);
2467                         unset($status["user"]["self"]);
2468
2469                         if ($item["coord"] != "") {
2470                                 $coords = explode(' ',$item["coord"]);
2471                                 if (count($coords) == 2) {
2472                                         if ($type == "json")
2473                                                 $status["geo"] = array('type' => 'Point',
2474                                                                 'coordinates' => array((float) $coords[0],
2475                                                                                         (float) $coords[1]));
2476                                         else // Not sure if this is the official format - if someone founds a documentation we can check
2477                                                 $status["georss:point"] = $item["coord"];
2478                                 }
2479                         }
2480                         $ret[] = $status;
2481                 };
2482                 return $ret;
2483         }
2484
2485
2486         function api_account_rate_limit_status(&$a,$type) {
2487
2488                 if ($type == "xml")
2489                         $hash = array(
2490                                         'remaining-hits' => (string) 150,
2491                                         '@attributes' => array("type" => "integer"),
2492                                         'hourly-limit' => (string) 150,
2493                                         '@attributes2' => array("type" => "integer"),
2494                                         'reset-time' => datetime_convert('UTC','UTC','now + 1 hour',ATOM_TIME),
2495                                         '@attributes3' => array("type" => "datetime"),
2496                                         'reset_time_in_seconds' => strtotime('now + 1 hour'),
2497                                         '@attributes4' => array("type" => "integer"),
2498                                 );
2499                 else
2500                         $hash = array(
2501                                         'reset_time_in_seconds' => strtotime('now + 1 hour'),
2502                                         'remaining_hits' => (string) 150,
2503                                         'hourly_limit' => (string) 150,
2504                                         'reset_time' => api_date(datetime_convert('UTC','UTC','now + 1 hour',ATOM_TIME)),
2505                                 );
2506
2507                 return api_format_data('hash', $type, array('hash' => $hash));
2508         }
2509         api_register_func('api/account/rate_limit_status','api_account_rate_limit_status',true);
2510
2511         function api_help_test(&$a,$type) {
2512                 if ($type == 'xml')
2513                         $ok = "true";
2514                 else
2515                         $ok = "ok";
2516
2517                 return api_format_data('ok', $type, array("ok" => $ok));
2518         }
2519         api_register_func('api/help/test','api_help_test',false);
2520
2521         function api_lists(&$a,$type) {
2522                 $ret = array();
2523                 return api_format_data('lists', $type, array("lists_list" => $ret));
2524         }
2525         api_register_func('api/lists','api_lists',true);
2526
2527         function api_lists_list(&$a,$type) {
2528                 $ret = array();
2529                 return api_format_data('lists', $type, array("lists_list" => $ret));
2530         }
2531         api_register_func('api/lists/list','api_lists_list',true);
2532
2533         /**
2534          *  https://dev.twitter.com/docs/api/1/get/statuses/friends
2535          *  This function is deprecated by Twitter
2536          *  returns: json, xml
2537          **/
2538         function api_statuses_f(&$a, $type, $qtype) {
2539                 if (api_user()===false) throw new ForbiddenException();
2540                 $user_info = api_get_user($a);
2541
2542                 if (x($_GET,'cursor') && $_GET['cursor']=='undefined'){
2543                         /* this is to stop Hotot to load friends multiple times
2544                         *  I'm not sure if I'm missing return something or
2545                         *  is a bug in hotot. Workaround, meantime
2546                         */
2547
2548                         /*$ret=Array();
2549                         return array('$users' => $ret);*/
2550                         return false;
2551                 }
2552
2553                 if($qtype == 'friends')
2554                         $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
2555                 if($qtype == 'followers')
2556                         $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
2557
2558                 // friends and followers only for self
2559                 if ($user_info['self'] == 0)
2560                         $sql_extra = " AND false ";
2561
2562                 $r = q("SELECT `nurl` FROM `contact` WHERE `uid` = %d AND `self` = 0 AND `blocked` = 0 AND `pending` = 0 $sql_extra",
2563                         intval(api_user())
2564                 );
2565
2566                 $ret = array();
2567                 foreach($r as $cid){
2568                         $user = api_get_user($a, $cid['nurl']);
2569                         // "uid" and "self" are only needed for some internal stuff, so remove it from here
2570                         unset($user["uid"]);
2571                         unset($user["self"]);
2572
2573                         if ($user)
2574                                 $ret[] = $user;
2575                 }
2576
2577                 return array('user' => $ret);
2578
2579         }
2580         function api_statuses_friends(&$a, $type){
2581                 $data =  api_statuses_f($a,$type,"friends");
2582                 if ($data===false) return false;
2583                 return  api_format_data("users", $type, $data);
2584         }
2585         function api_statuses_followers(&$a, $type){
2586                 $data = api_statuses_f($a,$type,"followers");
2587                 if ($data===false) return false;
2588                 return  api_format_data("users", $type, $data);
2589         }
2590         api_register_func('api/statuses/friends','api_statuses_friends',true);
2591         api_register_func('api/statuses/followers','api_statuses_followers',true);
2592
2593
2594
2595
2596
2597
2598         function api_statusnet_config(&$a,$type) {
2599                 $name = $a->config['sitename'];
2600                 $server = $a->get_hostname();
2601                 $logo = $a->get_baseurl() . '/images/friendica-64.png';
2602                 $email = $a->config['admin_email'];
2603                 $closed = (($a->config['register_policy'] == REGISTER_CLOSED) ? 'true' : 'false');
2604                 $private = (($a->config['system']['block_public']) ? 'true' : 'false');
2605                 $textlimit = (string) (($a->config['max_import_size']) ? $a->config['max_import_size'] : 200000);
2606                 if($a->config['api_import_size'])
2607                         $texlimit = string($a->config['api_import_size']);
2608                 $ssl = (($a->config['system']['have_ssl']) ? 'true' : 'false');
2609                 $sslserver = (($ssl === 'true') ? str_replace('http:','https:',$a->get_baseurl()) : '');
2610
2611                 $config = array(
2612                         'site' => array('name' => $name,'server' => $server, 'theme' => 'default', 'path' => '',
2613                                 'logo' => $logo, 'fancy' => true, 'language' => 'en', 'email' => $email, 'broughtby' => '',
2614                                 'broughtbyurl' => '', 'timezone' => 'UTC', 'closed' => $closed, 'inviteonly' => false,
2615                                 'private' => $private, 'textlimit' => $textlimit, 'sslserver' => $sslserver, 'ssl' => $ssl,
2616                                 'shorturllength' => '30',
2617                                 'friendica' => array(
2618                                                 'FRIENDICA_PLATFORM' => FRIENDICA_PLATFORM,
2619                                                 'FRIENDICA_VERSION' => FRIENDICA_VERSION,
2620                                                 'DFRN_PROTOCOL_VERSION' => DFRN_PROTOCOL_VERSION,
2621                                                 'DB_UPDATE_VERSION' => DB_UPDATE_VERSION
2622                                                 )
2623                         ),
2624                 );
2625
2626                 return api_format_data('config', $type, array('config' => $config));
2627
2628         }
2629         api_register_func('api/statusnet/config','api_statusnet_config',false);
2630
2631         function api_statusnet_version(&$a,$type) {
2632                 // liar
2633                 $fake_statusnet_version = "0.9.7";
2634
2635                 return api_format_data('version', $type, array('version' => $fake_statusnet_version));
2636         }
2637         api_register_func('api/statusnet/version','api_statusnet_version',false);
2638
2639         /**
2640          * @todo use api_format_data() to return data
2641          */
2642         function api_ff_ids(&$a,$type,$qtype) {
2643                 if(! api_user()) throw new ForbiddenException();
2644
2645                 $user_info = api_get_user($a);
2646
2647                 if($qtype == 'friends')
2648                         $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
2649                 if($qtype == 'followers')
2650                         $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
2651
2652                 if (!$user_info["self"])
2653                         $sql_extra = " AND false ";
2654
2655                 $stringify_ids = (x($_REQUEST,'stringify_ids')?$_REQUEST['stringify_ids']:false);
2656
2657                 $r = q("SELECT `gcontact`.`id` FROM `contact`, `gcontact` WHERE `contact`.`nurl` = `gcontact`.`nurl` AND `uid` = %d AND NOT `self` AND NOT `blocked` AND NOT `pending` $sql_extra",
2658                         intval(api_user())
2659                 );
2660
2661                 if(!dbm::is_result($r))
2662                         return;
2663
2664                 $ids = array();
2665                 foreach($r as $rr)
2666                         if ($stringify_ids)
2667                                 $ids[] = $rr['id'];
2668                         else
2669                                 $ids[] = intval($rr['id']);
2670
2671                 return api_format_data("ids", $type, array('id' => $ids));
2672         }
2673
2674         function api_friends_ids(&$a,$type) {
2675                 return api_ff_ids($a,$type,'friends');
2676         }
2677         function api_followers_ids(&$a,$type) {
2678                 return api_ff_ids($a,$type,'followers');
2679         }
2680         api_register_func('api/friends/ids','api_friends_ids',true);
2681         api_register_func('api/followers/ids','api_followers_ids',true);
2682
2683
2684         function api_direct_messages_new(&$a, $type) {
2685                 if (api_user()===false) throw new ForbiddenException();
2686
2687                 if (!x($_POST, "text") OR (!x($_POST,"screen_name") AND !x($_POST,"user_id"))) return;
2688
2689                 $sender = api_get_user($a);
2690
2691                 if ($_POST['screen_name']) {
2692                         $r = q("SELECT `id`, `nurl`, `network` FROM `contact` WHERE `uid`=%d AND `nick`='%s'",
2693                                         intval(api_user()),
2694                                         dbesc($_POST['screen_name']));
2695
2696                         // Selecting the id by priority, friendica first
2697                         api_best_nickname($r);
2698
2699                         $recipient = api_get_user($a, $r[0]['nurl']);
2700                 } else
2701                         $recipient = api_get_user($a, $_POST['user_id']);
2702
2703                 $replyto = '';
2704                 $sub     = '';
2705                 if (x($_REQUEST,'replyto')) {
2706                         $r = q('SELECT `parent-uri`, `title` FROM `mail` WHERE `uid`=%d AND `id`=%d',
2707                                         intval(api_user()),
2708                                         intval($_REQUEST['replyto']));
2709                         $replyto = $r[0]['parent-uri'];
2710                         $sub     = $r[0]['title'];
2711                 }
2712                 else {
2713                         if (x($_REQUEST,'title')) {
2714                                 $sub = $_REQUEST['title'];
2715                         }
2716                         else {
2717                                 $sub = ((strlen($_POST['text'])>10)?substr($_POST['text'],0,10)."...":$_POST['text']);
2718                         }
2719                 }
2720
2721                 $id = send_message($recipient['cid'], $_POST['text'], $sub, $replyto);
2722
2723                 if ($id>-1) {
2724                         $r = q("SELECT * FROM `mail` WHERE id=%d", intval($id));
2725                         $ret = api_format_messages($r[0], $recipient, $sender);
2726
2727                 } else {
2728                         $ret = array("error"=>$id);
2729                 }
2730
2731                 $data = Array('direct_message'=>$ret);
2732
2733                 switch($type){
2734                         case "atom":
2735                         case "rss":
2736                                 $data = api_rss_extra($a, $data, $user_info);
2737                 }
2738
2739                 return  api_format_data("direct-messages", $type, $data);
2740
2741         }
2742         api_register_func('api/direct_messages/new','api_direct_messages_new',true, API_METHOD_POST);
2743
2744         function api_direct_messages_box(&$a, $type, $box) {
2745                 if (api_user()===false) throw new ForbiddenException();
2746
2747                 // params
2748                 $count = (x($_GET,'count')?$_GET['count']:20);
2749                 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
2750                 if ($page<0) $page=0;
2751
2752                 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
2753                 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
2754
2755                 $user_id = (x($_REQUEST,'user_id')?$_REQUEST['user_id']:"");
2756                 $screen_name = (x($_REQUEST,'screen_name')?$_REQUEST['screen_name']:"");
2757
2758                 //  caller user info
2759                 unset($_REQUEST["user_id"]);
2760                 unset($_GET["user_id"]);
2761
2762                 unset($_REQUEST["screen_name"]);
2763                 unset($_GET["screen_name"]);
2764
2765                 $user_info = api_get_user($a);
2766                 //$profile_url = $a->get_baseurl() . '/profile/' . $a->user['nickname'];
2767                 $profile_url = $user_info["url"];
2768
2769
2770                 // pagination
2771                 $start = $page*$count;
2772
2773                 // filters
2774                 if ($box=="sentbox") {
2775                         $sql_extra = "`mail`.`from-url`='".dbesc( $profile_url )."'";
2776                 }
2777                 elseif ($box=="conversation") {
2778                         $sql_extra = "`mail`.`parent-uri`='".dbesc( $_GET["uri"] )  ."'";
2779                 }
2780                 elseif ($box=="all") {
2781                         $sql_extra = "true";
2782                 }
2783                 elseif ($box=="inbox") {
2784                         $sql_extra = "`mail`.`from-url`!='".dbesc( $profile_url )."'";
2785                 }
2786
2787                 if ($max_id > 0)
2788                         $sql_extra .= ' AND `mail`.`id` <= '.intval($max_id);
2789
2790                 if ($user_id !="") {
2791                         $sql_extra .= ' AND `mail`.`contact-id` = ' . intval($user_id);
2792                 }
2793                 elseif($screen_name !=""){
2794                         $sql_extra .= " AND `contact`.`nick` = '" . dbesc($screen_name). "'";
2795                 }
2796
2797                 $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`.`id` DESC LIMIT %d,%d",
2798                                 intval(api_user()),
2799                                 intval($since_id),
2800                                 intval($start), intval($count)
2801                 );
2802
2803
2804                 $ret = Array();
2805                 foreach($r as $item) {
2806                         if ($box == "inbox" || $item['from-url'] != $profile_url){
2807                                 $recipient = $user_info;
2808                                 $sender = api_get_user($a,normalise_link($item['contact-url']));
2809                         }
2810                         elseif ($box == "sentbox" || $item['from-url'] == $profile_url){
2811                                 $recipient = api_get_user($a,normalise_link($item['contact-url']));
2812                                 $sender = $user_info;
2813
2814                         }
2815                         $ret[]=api_format_messages($item, $recipient, $sender);
2816                 }
2817
2818
2819                 $data = array('direct_message' => $ret);
2820                 switch($type){
2821                         case "atom":
2822                         case "rss":
2823                                 $data = api_rss_extra($a, $data, $user_info);
2824                 }
2825
2826                 return  api_format_data("direct-messages", $type, $data);
2827
2828         }
2829
2830         function api_direct_messages_sentbox(&$a, $type){
2831                 return api_direct_messages_box($a, $type, "sentbox");
2832         }
2833         function api_direct_messages_inbox(&$a, $type){
2834                 return api_direct_messages_box($a, $type, "inbox");
2835         }
2836         function api_direct_messages_all(&$a, $type){
2837                 return api_direct_messages_box($a, $type, "all");
2838         }
2839         function api_direct_messages_conversation(&$a, $type){
2840                 return api_direct_messages_box($a, $type, "conversation");
2841         }
2842         api_register_func('api/direct_messages/conversation','api_direct_messages_conversation',true);
2843         api_register_func('api/direct_messages/all','api_direct_messages_all',true);
2844         api_register_func('api/direct_messages/sent','api_direct_messages_sentbox',true);
2845         api_register_func('api/direct_messages','api_direct_messages_inbox',true);
2846
2847
2848
2849         function api_oauth_request_token(&$a, $type){
2850                 try{
2851                         $oauth = new FKOAuth1();
2852                         $r = $oauth->fetch_request_token(OAuthRequest::from_request());
2853                 }catch(Exception $e){
2854                         echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage()); killme();
2855                 }
2856                 echo $r;
2857                 killme();
2858         }
2859         function api_oauth_access_token(&$a, $type){
2860                 try{
2861                         $oauth = new FKOAuth1();
2862                         $r = $oauth->fetch_access_token(OAuthRequest::from_request());
2863                 }catch(Exception $e){
2864                         echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage()); killme();
2865                 }
2866                 echo $r;
2867                 killme();
2868         }
2869
2870         api_register_func('api/oauth/request_token', 'api_oauth_request_token', false);
2871         api_register_func('api/oauth/access_token', 'api_oauth_access_token', false);
2872
2873
2874         function api_fr_photos_list(&$a,$type) {
2875                 if (api_user()===false) throw new ForbiddenException();
2876                 $r = q("select `resource-id`, max(scale) as scale, album, filename, type from photo
2877                                 where uid = %d and album != 'Contact Photos' group by `resource-id`",
2878                         intval(local_user())
2879                 );
2880                 $typetoext = array(
2881                 'image/jpeg' => 'jpg',
2882                 'image/png' => 'png',
2883                 'image/gif' => 'gif'
2884                 );
2885                 $data = array('photo'=>array());
2886                 if($r) {
2887                         foreach($r as $rr) {
2888                                 $photo = array();
2889                                 $photo['id'] = $rr['resource-id'];
2890                                 $photo['album'] = $rr['album'];
2891                                 $photo['filename'] = $rr['filename'];
2892                                 $photo['type'] = $rr['type'];
2893                                 $thumb = $a->get_baseurl()."/photo/".$rr['resource-id']."-".$rr['scale'].".".$typetoext[$rr['type']];
2894
2895                                 if ($type == "xml")
2896                                         $data['photo'][] = array("@attributes" => $photo, "1" => $thumb);
2897                                 else {
2898                                         $photo['thumb'] = $thumb;
2899                                         $data['photo'][] = $photo;
2900                                 }
2901                         }
2902                 }
2903                 return  api_format_data("photos", $type, $data);
2904         }
2905
2906         function api_fr_photo_detail(&$a,$type) {
2907                 if (api_user()===false) throw new ForbiddenException();
2908                 if(!x($_REQUEST,'photo_id')) throw new BadRequestException("No photo id.");
2909
2910                 $scale = (x($_REQUEST, 'scale') ? intval($_REQUEST['scale']) : false);
2911                 $scale_sql = ($scale === false ? "" : sprintf("and scale=%d",intval($scale)));
2912                 $data_sql = ($scale === false ? "" : "data, ");
2913
2914                 $r = q("select %s `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
2915                                                 `type`, `height`, `width`, `datasize`, `profile`, min(`scale`) as minscale, max(`scale`) as maxscale
2916                                 from photo where `uid` = %d and `resource-id` = '%s' %s group by `resource-id`",
2917                         $data_sql,
2918                         intval(local_user()),
2919                         dbesc($_REQUEST['photo_id']),
2920                         $scale_sql
2921                 );
2922
2923                 $typetoext = array(
2924                 'image/jpeg' => 'jpg',
2925                 'image/png' => 'png',
2926                 'image/gif' => 'gif'
2927                 );
2928
2929                 if ($r) {
2930                         $data = array('photo' => $r[0]);
2931                         $data['photo']['id'] = $data['photo']['resource-id'];
2932                         if ($scale !== false) {
2933                                 $data['photo']['data'] = base64_encode($data['photo']['data']);
2934                         } else {
2935                                 unset($data['photo']['datasize']); //needed only with scale param
2936                         }
2937                         if ($type == "xml") {
2938                                 $data['photo']['links'] = array();
2939                                 for ($k=intval($data['photo']['minscale']); $k<=intval($data['photo']['maxscale']); $k++)
2940                                         $data['photo']['links'][$k.":link"]["@attributes"] = array("type" => $data['photo']['type'],
2941                                                                                         "scale" => $k,
2942                                                                                         "href" => $a->get_baseurl()."/photo/".$data['photo']['resource-id']."-".$k.".".$typetoext[$data['photo']['type']]);
2943                         } else {
2944                                 $data['photo']['link'] = array();
2945                                 for ($k=intval($data['photo']['minscale']); $k<=intval($data['photo']['maxscale']); $k++) {
2946                                         $data['photo']['link'][$k] = $a->get_baseurl()."/photo/".$data['photo']['resource-id']."-".$k.".".$typetoext[$data['photo']['type']];
2947                                 }
2948                         }
2949                         unset($data['photo']['resource-id']);
2950                         unset($data['photo']['minscale']);
2951                         unset($data['photo']['maxscale']);
2952
2953                 } else {
2954                         throw new NotFoundException();
2955                 }
2956
2957                 return api_format_data("photo_detail", $type, $data);
2958         }
2959
2960         api_register_func('api/friendica/photos/list', 'api_fr_photos_list', true);
2961         api_register_func('api/friendica/photo', 'api_fr_photo_detail', true);
2962
2963
2964
2965         /**
2966          * similar as /mod/redir.php
2967          * redirect to 'url' after dfrn auth
2968          *
2969          * why this when there is mod/redir.php already?
2970          * This use api_user() and api_login()
2971          *
2972          * params
2973          *              c_url: url of remote contact to auth to
2974          *              url: string, url to redirect after auth
2975          */
2976         function api_friendica_remoteauth(&$a) {
2977                 $url = ((x($_GET,'url')) ? $_GET['url'] : '');
2978                 $c_url = ((x($_GET,'c_url')) ? $_GET['c_url'] : '');
2979
2980                 if ($url === '' || $c_url === '')
2981                         throw new BadRequestException("Wrong parameters.");
2982
2983                 $c_url = normalise_link($c_url);
2984
2985                 // traditional DFRN
2986
2987                 $r = q("SELECT * FROM `contact` WHERE `id` = %d AND `nurl` = '%s' LIMIT 1",
2988                         dbesc($c_url),
2989                         intval(api_user())
2990                 );
2991
2992                 if ((! count($r)) || ($r[0]['network'] !== NETWORK_DFRN))
2993                         throw new BadRequestException("Unknown contact");
2994
2995                 $cid = $r[0]['id'];
2996
2997                 $dfrn_id = $orig_id = (($r[0]['issued-id']) ? $r[0]['issued-id'] : $r[0]['dfrn-id']);
2998
2999                 if($r[0]['duplex'] && $r[0]['issued-id']) {
3000                         $orig_id = $r[0]['issued-id'];
3001                         $dfrn_id = '1:' . $orig_id;
3002                 }
3003                 if($r[0]['duplex'] && $r[0]['dfrn-id']) {
3004                         $orig_id = $r[0]['dfrn-id'];
3005                         $dfrn_id = '0:' . $orig_id;
3006                 }
3007
3008                 $sec = random_string();
3009
3010                 q("INSERT INTO `profile_check` ( `uid`, `cid`, `dfrn_id`, `sec`, `expire`)
3011                         VALUES( %d, %s, '%s', '%s', %d )",
3012                         intval(api_user()),
3013                         intval($cid),
3014                         dbesc($dfrn_id),
3015                         dbesc($sec),
3016                         intval(time() + 45)
3017                 );
3018
3019                 logger($r[0]['name'] . ' ' . $sec, LOGGER_DEBUG);
3020                 $dest = (($url) ? '&destination_url=' . $url : '');
3021                 goaway ($r[0]['poll'] . '?dfrn_id=' . $dfrn_id
3022                                 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
3023                                 . '&type=profile&sec=' . $sec . $dest . $quiet );
3024         }
3025         api_register_func('api/friendica/remoteauth', 'api_friendica_remoteauth', true);
3026
3027         /**
3028          * @brief Return the item shared, if the item contains only the [share] tag
3029          *
3030          * @param array $item Sharer item
3031          * @return array Shared item or false if not a reshare
3032          */
3033         function api_share_as_retweet(&$item) {
3034                 $body = trim($item["body"]);
3035
3036                 if (diaspora::is_reshare($body, false)===false) {
3037                         return false;
3038                 }
3039
3040                 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$1",$body);
3041                 // Skip if there is no shared message in there
3042                 // we already checked this in diaspora::is_reshare()
3043                 // but better one more than one less...
3044                 if ($body == $attributes)
3045                         return false;
3046
3047
3048                 // build the fake reshared item
3049                 $reshared_item = $item;
3050
3051                 $author = "";
3052                 preg_match("/author='(.*?)'/ism", $attributes, $matches);
3053                 if ($matches[1] != "")
3054                         $author = html_entity_decode($matches[1],ENT_QUOTES,'UTF-8');
3055
3056                 preg_match('/author="(.*?)"/ism', $attributes, $matches);
3057                 if ($matches[1] != "")
3058                         $author = $matches[1];
3059
3060                 $profile = "";
3061                 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
3062                 if ($matches[1] != "")
3063                         $profile = $matches[1];
3064
3065                 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
3066                 if ($matches[1] != "")
3067                         $profile = $matches[1];
3068
3069                 $avatar = "";
3070                 preg_match("/avatar='(.*?)'/ism", $attributes, $matches);
3071                 if ($matches[1] != "")
3072                         $avatar = $matches[1];
3073
3074                 preg_match('/avatar="(.*?)"/ism', $attributes, $matches);
3075                 if ($matches[1] != "")
3076                         $avatar = $matches[1];
3077
3078                 $link = "";
3079                 preg_match("/link='(.*?)'/ism", $attributes, $matches);
3080                 if ($matches[1] != "")
3081                         $link = $matches[1];
3082
3083                 preg_match('/link="(.*?)"/ism', $attributes, $matches);
3084                 if ($matches[1] != "")
3085                         $link = $matches[1];
3086
3087                 $posted = "";
3088                 preg_match("/posted='(.*?)'/ism", $attributes, $matches);
3089                 if ($matches[1] != "")
3090                         $posted= $matches[1];
3091
3092                 preg_match('/posted="(.*?)"/ism', $attributes, $matches);
3093                 if ($matches[1] != "")
3094                         $posted = $matches[1];
3095
3096                 $shared_body = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$2",$body);
3097
3098                 if (($shared_body == "") || ($profile == "") || ($author == "") || ($avatar == "") || ($posted == ""))
3099                         return false;
3100
3101
3102
3103                 $reshared_item["body"] = $shared_body;
3104                 $reshared_item["author-name"] = $author;
3105                 $reshared_item["author-link"] = $profile;
3106                 $reshared_item["author-avatar"] = $avatar;
3107                 $reshared_item["plink"] = $link;
3108                 $reshared_item["created"] = $posted;
3109                 $reshared_item["edited"] = $posted;
3110
3111                 return $reshared_item;
3112
3113         }
3114
3115         function api_get_nick($profile) {
3116                 /* To-Do:
3117                  - remove trailing junk from profile url
3118                  - pump.io check has to check the website
3119                 */
3120
3121                 $nick = "";
3122
3123                 $r = q("SELECT `nick` FROM `gcontact` WHERE `nurl` = '%s'",
3124                         dbesc(normalise_link($profile)));
3125                 if ($r)
3126                         $nick = $r[0]["nick"];
3127
3128                 if (!$nick == "") {
3129                         $r = q("SELECT `nick` FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s'",
3130                                 dbesc(normalise_link($profile)));
3131                         if ($r)
3132                                 $nick = $r[0]["nick"];
3133                 }
3134
3135                 if (!$nick == "") {
3136                         $friendica = preg_replace("=https?://(.*)/profile/(.*)=ism", "$2", $profile);
3137                         if ($friendica != $profile)
3138                                 $nick = $friendica;
3139                 }
3140
3141                 if (!$nick == "") {
3142                         $diaspora = preg_replace("=https?://(.*)/u/(.*)=ism", "$2", $profile);
3143                         if ($diaspora != $profile)
3144                                 $nick = $diaspora;
3145                 }
3146
3147                 if (!$nick == "") {
3148                         $twitter = preg_replace("=https?://twitter.com/(.*)=ism", "$1", $profile);
3149                         if ($twitter != $profile)
3150                                 $nick = $twitter;
3151                 }
3152
3153
3154                 if (!$nick == "") {
3155                         $StatusnetHost = preg_replace("=https?://(.*)/user/(.*)=ism", "$1", $profile);
3156                         if ($StatusnetHost != $profile) {
3157                                 $StatusnetUser = preg_replace("=https?://(.*)/user/(.*)=ism", "$2", $profile);
3158                                 if ($StatusnetUser != $profile) {
3159                                         $UserData = fetch_url("http://".$StatusnetHost."/api/users/show.json?user_id=".$StatusnetUser);
3160                                         $user = json_decode($UserData);
3161                                         if ($user)
3162                                                 $nick = $user->screen_name;
3163                                 }
3164                         }
3165                 }
3166
3167                 // To-Do: look at the page if its really a pumpio site
3168                 //if (!$nick == "") {
3169                 //      $pumpio = preg_replace("=https?://(.*)/(.*)/=ism", "$2", $profile."/");
3170                 //      if ($pumpio != $profile)
3171                 //              $nick = $pumpio;
3172                         //      <div class="media" id="profile-block" data-profile-id="acct:kabniel@microca.st">
3173
3174                 //}
3175
3176                 if ($nick != "")
3177                         return($nick);
3178
3179                 return(false);
3180         }
3181
3182         function api_clean_plain_items($Text) {
3183                 $include_entities = strtolower(x($_REQUEST,'include_entities')?$_REQUEST['include_entities']:"false");
3184
3185                 $Text = bb_CleanPictureLinks($Text);
3186                 $URLSearchString = "^\[\]";
3187
3188                 $Text = preg_replace("/([!#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'$1$3',$Text);
3189
3190                 if ($include_entities == "true") {
3191                         $Text = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'[url=$1]$1[/url]',$Text);
3192                 }
3193
3194                 // Simplify "attachment" element
3195                 $Text = api_clean_attachments($Text);
3196
3197                 return($Text);
3198         }
3199
3200         /**
3201          * @brief Removes most sharing information for API text export
3202          *
3203          * @param string $body The original body
3204          *
3205          * @return string Cleaned body
3206          */
3207         function api_clean_attachments($body) {
3208                 $data = get_attachment_data($body);
3209
3210                 if (!$data)
3211                         return $body;
3212
3213                 $body = "";
3214
3215                 if (isset($data["text"]))
3216                         $body = $data["text"];
3217
3218                 if (($body == "") AND (isset($data["title"])))
3219                         $body = $data["title"];
3220
3221                 if (isset($data["url"]))
3222                         $body .= "\n".$data["url"];
3223
3224                 $body .= $data["after"];
3225
3226                 return $body;
3227         }
3228
3229         function api_best_nickname(&$contacts) {
3230                 $best_contact = array();
3231
3232                 if (count($contact) == 0)
3233                         return;
3234
3235                 foreach ($contacts AS $contact)
3236                         if ($contact["network"] == "") {
3237                                 $contact["network"] = "dfrn";
3238                                 $best_contact = array($contact);
3239                         }
3240
3241                 if (sizeof($best_contact) == 0)
3242                         foreach ($contacts AS $contact)
3243                                 if ($contact["network"] == "dfrn")
3244                                         $best_contact = array($contact);
3245
3246                 if (sizeof($best_contact) == 0)
3247                         foreach ($contacts AS $contact)
3248                                 if ($contact["network"] == "dspr")
3249                                         $best_contact = array($contact);
3250
3251                 if (sizeof($best_contact) == 0)
3252                         foreach ($contacts AS $contact)
3253                                 if ($contact["network"] == "stat")
3254                                         $best_contact = array($contact);
3255
3256                 if (sizeof($best_contact) == 0)
3257                         foreach ($contacts AS $contact)
3258                                 if ($contact["network"] == "pump")
3259                                         $best_contact = array($contact);
3260
3261                 if (sizeof($best_contact) == 0)
3262                         foreach ($contacts AS $contact)
3263                                 if ($contact["network"] == "twit")
3264                                         $best_contact = array($contact);
3265
3266                 if (sizeof($best_contact) == 1)
3267                         $contacts = $best_contact;
3268                 else
3269                         $contacts = array($contacts[0]);
3270         }
3271
3272         // return all or a specified group of the user with the containing contacts
3273         function api_friendica_group_show(&$a, $type) {
3274                 if (api_user()===false) throw new ForbiddenException();
3275
3276                 // params
3277                 $user_info = api_get_user($a);
3278                 $gid = (x($_REQUEST,'gid') ? $_REQUEST['gid'] : 0);
3279                 $uid = $user_info['uid'];
3280
3281                 // get data of the specified group id or all groups if not specified
3282                 if ($gid != 0) {
3283                         $r = q("SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d AND `id` = %d",
3284                                 intval($uid),
3285                                 intval($gid));
3286                         // error message if specified gid is not in database
3287                         if (count($r) == 0)
3288                                 throw new BadRequestException("gid not available");
3289                 }
3290                 else
3291                         $r = q("SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d",
3292                                 intval($uid));
3293
3294                 // loop through all groups and retrieve all members for adding data in the user array
3295                 foreach ($r as $rr) {
3296                         $members = group_get_members($rr['id']);
3297                         $users = array();
3298
3299                         if ($type == "xml") {
3300                                 $user_element = "users";
3301                                 $k = 0;
3302                                 foreach ($members as $member) {
3303                                         $user = api_get_user($a, $member['nurl']);
3304                                         $users[$k++.":user"] = $user;
3305                                 }
3306                         } else {
3307                                 $user_element = "user";
3308                                 foreach ($members as $member) {
3309                                         $user = api_get_user($a, $member['nurl']);
3310                                         $users[] = $user;
3311                                 }
3312                         }
3313                         $grps[] = array('name' => $rr['name'], 'gid' => $rr['id'], $user_element => $users);
3314                 }
3315                 return api_format_data("groups", $type, array('group' => $grps));
3316         }
3317         api_register_func('api/friendica/group_show', 'api_friendica_group_show', true);
3318
3319
3320         // delete the specified group of the user
3321         function api_friendica_group_delete(&$a, $type) {
3322                 if (api_user()===false) throw new ForbiddenException();
3323
3324                 // params
3325                 $user_info = api_get_user($a);
3326                 $gid = (x($_REQUEST,'gid') ? $_REQUEST['gid'] : 0);
3327                 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
3328                 $uid = $user_info['uid'];
3329
3330                 // error if no gid specified
3331                 if ($gid == 0 || $name == "")
3332                         throw new BadRequestException('gid or name not specified');
3333
3334                 // get data of the specified group id
3335                 $r = q("SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d",
3336                         intval($uid),
3337                         intval($gid));
3338                 // error message if specified gid is not in database
3339                 if (count($r) == 0)
3340                         throw new BadRequestException('gid not available');
3341
3342                 // get data of the specified group id and group name
3343                 $rname = q("SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d AND `name` = '%s'",
3344                         intval($uid),
3345                         intval($gid),
3346                         dbesc($name));
3347                 // error message if specified gid is not in database
3348                 if (count($rname) == 0)
3349                         throw new BadRequestException('wrong group name');
3350
3351                 // delete group
3352                 $ret = group_rmv($uid, $name);
3353                 if ($ret) {
3354                         // return success
3355                         $success = array('success' => $ret, 'gid' => $gid, 'name' => $name, 'status' => 'deleted', 'wrong users' => array());
3356                         return api_format_data("group_delete", $type, array('result' => $success));
3357                 }
3358                 else
3359                         throw new BadRequestException('other API error');
3360         }
3361         api_register_func('api/friendica/group_delete', 'api_friendica_group_delete', true, API_METHOD_DELETE);
3362
3363
3364         // create the specified group with the posted array of contacts
3365         function api_friendica_group_create(&$a, $type) {
3366                 if (api_user()===false) throw new ForbiddenException();
3367
3368                 // params
3369                 $user_info = api_get_user($a);
3370                 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
3371                 $uid = $user_info['uid'];
3372                 $json = json_decode($_POST['json'], true);
3373                 $users = $json['user'];
3374
3375                 // error if no name specified
3376                 if ($name == "")
3377                         throw new BadRequestException('group name not specified');
3378
3379                 // get data of the specified group name
3380                 $rname = q("SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 0",
3381                         intval($uid),
3382                         dbesc($name));
3383                 // error message if specified group name already exists
3384                 if (count($rname) != 0)
3385                         throw new BadRequestException('group name already exists');
3386
3387                 // check if specified group name is a deleted group
3388                 $rname = q("SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 1",
3389                         intval($uid),
3390                         dbesc($name));
3391                 // error message if specified group name already exists
3392                 if (count($rname) != 0)
3393                         $reactivate_group = true;
3394
3395                 // create group
3396                 $ret = group_add($uid, $name);
3397                 if ($ret)
3398                         $gid = group_byname($uid, $name);
3399                 else
3400                         throw new BadRequestException('other API error');
3401
3402                 // add members
3403                 $erroraddinguser = false;
3404                 $errorusers = array();
3405                 foreach ($users as $user) {
3406                         $cid = $user['cid'];
3407                         // check if user really exists as contact
3408                         $contact = q("SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
3409                                 intval($cid),
3410                                 intval($uid));
3411                         if (count($contact))
3412                                 $result = group_add_member($uid, $name, $cid, $gid);
3413                         else {
3414                                 $erroraddinguser = true;
3415                                 $errorusers[] = $cid;
3416                         }
3417                 }
3418
3419                 // return success message incl. missing users in array
3420                 $status = ($erroraddinguser ? "missing user" : ($reactivate_group ? "reactivated" : "ok"));
3421                 $success = array('success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers);
3422                 return api_format_data("group_create", $type, array('result' => $success));
3423         }
3424         api_register_func('api/friendica/group_create', 'api_friendica_group_create', true, API_METHOD_POST);
3425
3426
3427         // update the specified group with the posted array of contacts
3428         function api_friendica_group_update(&$a, $type) {
3429                 if (api_user()===false) throw new ForbiddenException();
3430
3431                 // params
3432                 $user_info = api_get_user($a);
3433                 $uid = $user_info['uid'];
3434                 $gid = (x($_REQUEST, 'gid') ? $_REQUEST['gid'] : 0);
3435                 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
3436                 $json = json_decode($_POST['json'], true);
3437                 $users = $json['user'];
3438
3439                 // error if no name specified
3440                 if ($name == "")
3441                         throw new BadRequestException('group name not specified');
3442
3443                 // error if no gid specified
3444                 if ($gid == "")
3445                         throw new BadRequestException('gid not specified');
3446
3447                 // remove members
3448                 $members = group_get_members($gid);
3449                 foreach ($members as $member) {
3450                         $cid = $member['id'];
3451                         foreach ($users as $user) {
3452                                 $found = ($user['cid'] == $cid ? true : false);
3453                         }
3454                         if (!$found) {
3455                                 $ret = group_rmv_member($uid, $name, $cid);
3456                         }
3457                 }
3458
3459                 // add members
3460                 $erroraddinguser = false;
3461                 $errorusers = array();
3462                 foreach ($users as $user) {
3463                         $cid = $user['cid'];
3464                         // check if user really exists as contact
3465                         $contact = q("SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
3466                                 intval($cid),
3467                                 intval($uid));
3468                         if (count($contact))
3469                                 $result = group_add_member($uid, $name, $cid, $gid);
3470                         else {
3471                                 $erroraddinguser = true;
3472                                 $errorusers[] = $cid;
3473                         }
3474                 }
3475
3476                 // return success message incl. missing users in array
3477                 $status = ($erroraddinguser ? "missing user" : "ok");
3478                 $success = array('success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers);
3479                 return api_format_data("group_update", $type, array('result' => $success));
3480         }
3481         api_register_func('api/friendica/group_update', 'api_friendica_group_update', true, API_METHOD_POST);
3482
3483
3484         function api_friendica_activity(&$a, $type) {
3485                 if (api_user()===false) throw new ForbiddenException();
3486                 $verb = strtolower($a->argv[3]);
3487                 $verb = preg_replace("|\..*$|", "", $verb);
3488
3489                 $id = (x($_REQUEST, 'id') ? $_REQUEST['id'] : 0);
3490
3491                 $res = do_like($id, $verb);
3492
3493                 if ($res) {
3494                         if ($type == "xml")
3495                                 $ok = "true";
3496                         else
3497                                 $ok = "ok";
3498                         return api_format_data('ok', $type, array('ok' => $ok));
3499                 } else {
3500                         throw new BadRequestException('Error adding activity');
3501                 }
3502
3503         }
3504         api_register_func('api/friendica/activity/like', 'api_friendica_activity', true, API_METHOD_POST);
3505         api_register_func('api/friendica/activity/dislike', 'api_friendica_activity', true, API_METHOD_POST);
3506         api_register_func('api/friendica/activity/attendyes', 'api_friendica_activity', true, API_METHOD_POST);
3507         api_register_func('api/friendica/activity/attendno', 'api_friendica_activity', true, API_METHOD_POST);
3508         api_register_func('api/friendica/activity/attendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
3509         api_register_func('api/friendica/activity/unlike', 'api_friendica_activity', true, API_METHOD_POST);
3510         api_register_func('api/friendica/activity/undislike', 'api_friendica_activity', true, API_METHOD_POST);
3511         api_register_func('api/friendica/activity/unattendyes', 'api_friendica_activity', true, API_METHOD_POST);
3512         api_register_func('api/friendica/activity/unattendno', 'api_friendica_activity', true, API_METHOD_POST);
3513         api_register_func('api/friendica/activity/unattendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
3514
3515         /**
3516          * @brief Returns notifications
3517          *
3518          * @param App $a
3519          * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3520          * @return string
3521         */
3522         function api_friendica_notification(&$a, $type) {
3523                 if (api_user()===false) throw new ForbiddenException();
3524                 if ($a->argc!==3) throw new BadRequestException("Invalid argument count");
3525                 $nm = new NotificationsManager();
3526
3527                 $notes = $nm->getAll(array(), "+seen -date", 50);
3528
3529                 if ($type == "xml") {
3530                         $xmlnotes = array();
3531                         foreach ($notes AS $note)
3532                                 $xmlnotes[] = array("@attributes" => $note);
3533
3534                         $notes = $xmlnotes;
3535                 }
3536
3537                 return api_format_data("notes", $type, array('note' => $notes));
3538         }
3539
3540         /**
3541          * @brief Set notification as seen and returns associated item (if possible)
3542          *
3543          * POST request with 'id' param as notification id
3544          *
3545          * @param App $a
3546          * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3547          * @return string
3548          */
3549         function api_friendica_notification_seen(&$a, $type){
3550                 if (api_user()===false) throw new ForbiddenException();
3551                 if ($a->argc!==4) throw new BadRequestException("Invalid argument count");
3552
3553                 $id = (x($_REQUEST, 'id') ? intval($_REQUEST['id']) : 0);
3554
3555                 $nm = new NotificationsManager();
3556                 $note = $nm->getByID($id);
3557                 if (is_null($note)) throw new BadRequestException("Invalid argument");
3558
3559                 $nm->setSeen($note);
3560                 if ($note['otype']=='item') {
3561                         // would be really better with an ItemsManager and $im->getByID() :-P
3562                         $r = q("SELECT * FROM `item` WHERE `id`=%d AND `uid`=%d",
3563                                 intval($note['iid']),
3564                                 intval(local_user())
3565                         );
3566                         if ($r!==false) {
3567                                 // we found the item, return it to the user
3568                                 $user_info = api_get_user($a);
3569                                 $ret = api_format_items($r,$user_info, false, $type);
3570                                 $data = array('status' => $ret);
3571                                 return api_format_data("status", $type, $data);
3572                         }
3573                         // the item can't be found, but we set the note as seen, so we count this as a success
3574                 }
3575                 return api_format_data('result', $type, array('result' => "success"));
3576         }
3577
3578         api_register_func('api/friendica/notification/seen', 'api_friendica_notification_seen', true, API_METHOD_POST);
3579         api_register_func('api/friendica/notification', 'api_friendica_notification', true, API_METHOD_GET);
3580
3581
3582 /*
3583 To.Do:
3584     [pagename] => api/1.1/statuses/lookup.json
3585     [id] => 605138389168451584
3586     [include_cards] => true
3587     [cards_platform] => Android-12
3588     [include_entities] => true
3589     [include_my_retweet] => 1
3590     [include_rts] => 1
3591     [include_reply_count] => true
3592     [include_descendent_reply_count] => true
3593 (?)
3594
3595
3596 Not implemented by now:
3597 statuses/retweets_of_me
3598 friendships/create
3599 friendships/destroy
3600 friendships/exists
3601 friendships/show
3602 account/update_location
3603 account/update_profile_background_image
3604 account/update_profile_image
3605 blocks/create
3606 blocks/destroy
3607
3608 Not implemented in status.net:
3609 statuses/retweeted_to_me
3610 statuses/retweeted_by_me
3611 direct_messages/destroy
3612 account/end_session
3613 account/update_delivery_device
3614 notifications/follow
3615 notifications/leave
3616 blocks/exists
3617 blocks/blocking
3618 lists
3619 */