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