]> git.mxchange.org Git - friendica.git/blob - include/api.php
Optimized queries
[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' => get_contact($r[0]["url"], api_user()),
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`
1212                                 INNER JOIN `contact` ON `contact`.`id`=`item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1213                                 WHERE `item`.`uid` = %d AND `verb` = '%s' AND `item`.`contact-id` = %d
1214                                         AND ((`item`.`author-link` IN ('%s', '%s')) OR (`item`.`owner-link` IN ('%s', '%s')))
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
1228                 if (count($lastwall)>0){
1229                         $lastwall = $lastwall[0];
1230
1231                         $in_reply_to_status_id = NULL;
1232                         $in_reply_to_user_id = NULL;
1233                         $in_reply_to_status_id_str = NULL;
1234                         $in_reply_to_user_id_str = NULL;
1235                         $in_reply_to_screen_name = NULL;
1236                         if ($lastwall['parent']!=$lastwall['id']) {
1237                                 $reply = q("SELECT `item`.`id`, `item`.`contact-id` as `reply_uid`, `contact`.`nick` as `reply_author`, `item`.`author-link` AS `item-author`
1238                                                 FROM `item`,`contact` WHERE `contact`.`id`=`item`.`contact-id` AND `item`.`id` = %d", intval($lastwall['parent']));
1239                                 if (count($reply)>0) {
1240                                         $in_reply_to_status_id = intval($lastwall['parent']);
1241                                         $in_reply_to_status_id_str = (string) intval($lastwall['parent']);
1242
1243                                         $r = q("SELECT * FROM `gcontact` WHERE `nurl` = '%s'", dbesc(normalise_link($reply[0]['item-author'])));
1244                                         if ($r) {
1245                                                 if ($r[0]['nick'] == "")
1246                                                         $r[0]['nick'] = api_get_nick($r[0]["url"]);
1247
1248                                                 $in_reply_to_screen_name = (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']);
1249                                                 $in_reply_to_user_id = intval($r[0]['id']);
1250                                                 $in_reply_to_user_id_str = (string) intval($r[0]['id']);
1251                                         }
1252                                 }
1253                         }
1254
1255                         $converted = api_convert_item($lastwall);
1256
1257                         if ($type == "xml")
1258                                 $geo = "georss:point";
1259                         else
1260                                 $geo = "geo";
1261
1262                         $user_info['status'] = array(
1263                                 'text' => $converted["text"],
1264                                 'truncated' => false,
1265                                 'created_at' => api_date($lastwall['created']),
1266                                 'in_reply_to_status_id' => $in_reply_to_status_id,
1267                                 'in_reply_to_status_id_str' => $in_reply_to_status_id_str,
1268                                 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
1269                                 'id' => intval($lastwall['contact-id']),
1270                                 'id_str' => (string) $lastwall['contact-id'],
1271                                 'in_reply_to_user_id' => $in_reply_to_user_id,
1272                                 'in_reply_to_user_id_str' => $in_reply_to_user_id_str,
1273                                 'in_reply_to_screen_name' => $in_reply_to_screen_name,
1274                                 $geo => NULL,
1275                                 'favorited' => $lastwall['starred'] ? true : false,
1276                                 'statusnet_html'                => $converted["html"],
1277                                 'statusnet_conversation_id'     => $lastwall['parent'],
1278                         );
1279
1280                         if (count($converted["attachments"]) > 0)
1281                                 $user_info["status"]["attachments"] = $converted["attachments"];
1282
1283                         if (count($converted["entities"]) > 0)
1284                                 $user_info["status"]["entities"] = $converted["entities"];
1285
1286                         if (($lastwall['item_network'] != "") AND ($user_info["status"]["source"] == 'web'))
1287                                 $user_info["status"]["source"] = network_to_name($lastwall['item_network'], $user_info['url']);
1288                         if (($lastwall['item_network'] != "") AND (network_to_name($lastwall['item_network'], $user_info['url']) != $user_info["status"]["source"]))
1289                                 $user_info["status"]["source"] = trim($user_info["status"]["source"].' ('.network_to_name($lastwall['item_network'], $user_info['url']).')');
1290
1291                 }
1292
1293                 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1294                 unset($user_info["uid"]);
1295                 unset($user_info["self"]);
1296
1297                 return  api_format_data("user", $type, array('user' => $user_info));
1298
1299         }
1300         api_register_func('api/users/show','api_users_show');
1301
1302
1303         function api_users_search(&$a, $type) {
1304                 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1305
1306                 $userlist = array();
1307
1308                 if (isset($_GET["q"])) {
1309                         $r = q("SELECT id FROM `gcontact` WHERE `name`='%s'", dbesc($_GET["q"]));
1310                         if (!count($r))
1311                                 $r = q("SELECT `id` FROM `gcontact` WHERE `nick`='%s'", dbesc($_GET["q"]));
1312
1313                         if (count($r)) {
1314                                 $k = 0;
1315                                 foreach ($r AS $user) {
1316                                         $user_info = api_get_user($a, $user["id"], "json");
1317
1318                                         if ($type == "xml")
1319                                                 $userlist[$k++.":user"] = $user_info;
1320                                         else
1321                                                 $userlist[] = $user_info;
1322                                 }
1323                                 $userlist = array("users" => $userlist);
1324                         } else {
1325                                 throw new BadRequestException("User not found.");
1326                         }
1327                 } else {
1328                         throw new BadRequestException("User not found.");
1329                 }
1330                 return api_format_data("users", $type, $userlist);
1331         }
1332
1333         api_register_func('api/users/search','api_users_search');
1334
1335         /**
1336          *
1337          * http://developer.twitter.com/doc/get/statuses/home_timeline
1338          *
1339          * TODO: Optional parameters
1340          * TODO: Add reply info
1341          */
1342         function api_statuses_home_timeline(&$a, $type){
1343                 if (api_user()===false) throw new ForbiddenException();
1344
1345                 unset($_REQUEST["user_id"]);
1346                 unset($_GET["user_id"]);
1347
1348                 unset($_REQUEST["screen_name"]);
1349                 unset($_GET["screen_name"]);
1350
1351                 $user_info = api_get_user($a);
1352                 // get last newtork messages
1353
1354
1355                 // params
1356                 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1357                 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1358                 if ($page<0) $page=0;
1359                 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1360                 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1361                 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1362                 $exclude_replies = (x($_REQUEST,'exclude_replies')?1:0);
1363                 $conversation_id = (x($_REQUEST,'conversation_id')?$_REQUEST['conversation_id']:0);
1364
1365                 $start = $page*$count;
1366
1367                 $sql_extra = '';
1368                 if ($max_id > 0)
1369                         $sql_extra .= ' AND `item`.`id` <= '.intval($max_id);
1370                 if ($exclude_replies > 0)
1371                         $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
1372                 if ($conversation_id > 0)
1373                         $sql_extra .= ' AND `item`.`parent` = '.intval($conversation_id);
1374
1375                 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1376                         `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1377                         `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1378                         `contact`.`id` AS `cid`
1379                         FROM `item`
1380                         STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1381                                 AND NOT `contact`.`blocked` AND NOT `contact`.`pending`
1382                         WHERE `item`.`uid` = %d AND `verb` = '%s'
1383                         AND `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
1384                         $sql_extra
1385                         AND `item`.`id`>%d
1386                         ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1387                         intval(api_user()),
1388                         dbesc(ACTIVITY_POST),
1389                         intval($since_id),
1390                         intval($start), intval($count)
1391                 );
1392
1393                 $ret = api_format_items($r,$user_info, false, $type);
1394
1395                 // Set all posts from the query above to seen
1396                 $idarray = array();
1397                 foreach ($r AS $item)
1398                         $idarray[] = intval($item["id"]);
1399
1400                 $idlist = implode(",", $idarray);
1401
1402                 if ($idlist != "") {
1403                         $unseen = q("SELECT `id` FROM `item` WHERE `unseen` AND `id` IN (%s)", $idlist);
1404
1405                         if ($unseen)
1406                                 $r = q("UPDATE `item` SET `unseen` = 0 WHERE `unseen` AND `id` IN (%s)", $idlist);
1407                 }
1408
1409                 $data = array('status' => $ret);
1410                 switch($type){
1411                         case "atom":
1412                         case "rss":
1413                                 $data = api_rss_extra($a, $data, $user_info);
1414                                 break;
1415                 }
1416
1417                 return  api_format_data("statuses", $type, $data);
1418         }
1419         api_register_func('api/statuses/home_timeline','api_statuses_home_timeline', true);
1420         api_register_func('api/statuses/friends_timeline','api_statuses_home_timeline', true);
1421
1422         function api_statuses_public_timeline(&$a, $type){
1423                 if (api_user()===false) throw new ForbiddenException();
1424
1425                 $user_info = api_get_user($a);
1426                 // get last newtork messages
1427
1428
1429                 // params
1430                 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1431                 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1432                 if ($page<0) $page=0;
1433                 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1434                 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1435                 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1436                 $exclude_replies = (x($_REQUEST,'exclude_replies')?1:0);
1437                 $conversation_id = (x($_REQUEST,'conversation_id')?$_REQUEST['conversation_id']:0);
1438
1439                 $start = $page*$count;
1440
1441                 if ($max_id > 0)
1442                         $sql_extra = 'AND `item`.`id` <= '.intval($max_id);
1443                 if ($exclude_replies > 0)
1444                         $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
1445                 if ($conversation_id > 0)
1446                         $sql_extra .= ' AND `item`.`parent` = '.intval($conversation_id);
1447
1448                 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1449                         `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1450                         `contact`.`network`, `contact`.`thumb`, `contact`.`self`, `contact`.`writable`,
1451                         `contact`.`id` AS `cid`,
1452                         `user`.`nickname`, `user`.`hidewall`
1453                         FROM `item`
1454                         STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1455                                 AND NOT `contact`.`blocked` AND NOT `contact`.`pending`
1456                         STRAIGHT_JOIN `user` ON `user`.`uid` = `item`.`uid`
1457                                 AND NOT `user`.`hidewall`
1458                         WHERE `verb` = '%s' AND `item`.`visible` AND NOT `item`.`deleted` AND NOT `item`.`moderated`
1459                         AND `item`.`allow_cid` = ''  AND `item`.`allow_gid` = ''
1460                         AND `item`.`deny_cid`  = '' AND `item`.`deny_gid`  = ''
1461                         AND NOT `item`.`private` AND `item`.`wall`
1462                         $sql_extra
1463                         AND `item`.`id`>%d
1464                         ORDER BY `item`.`id` DESC LIMIT %d, %d ",
1465                         dbesc(ACTIVITY_POST),
1466                         intval($since_id),
1467                         intval($start),
1468                         intval($count));
1469
1470                 $ret = api_format_items($r,$user_info, false, $type);
1471
1472
1473                 $data = array('status' => $ret);
1474                 switch($type){
1475                         case "atom":
1476                         case "rss":
1477                                 $data = api_rss_extra($a, $data, $user_info);
1478                                 break;
1479                 }
1480
1481                 return  api_format_data("statuses", $type, $data);
1482         }
1483         api_register_func('api/statuses/public_timeline','api_statuses_public_timeline', true);
1484
1485         /**
1486          *
1487          */
1488         function api_statuses_show(&$a, $type){
1489                 if (api_user()===false) throw new ForbiddenException();
1490
1491                 $user_info = api_get_user($a);
1492
1493                 // params
1494                 $id = intval($a->argv[3]);
1495
1496                 if ($id == 0)
1497                         $id = intval($_REQUEST["id"]);
1498
1499                 // Hotot workaround
1500                 if ($id == 0)
1501                         $id = intval($a->argv[4]);
1502
1503                 logger('API: api_statuses_show: '.$id);
1504
1505                 $conversation = (x($_REQUEST,'conversation')?1:0);
1506
1507                 $sql_extra = '';
1508                 if ($conversation)
1509                         $sql_extra .= " AND `item`.`parent` = %d ORDER BY `received` ASC ";
1510                 else
1511                         $sql_extra .= " AND `item`.`id` = %d";
1512
1513                 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1514                         `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1515                         `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1516                         `contact`.`id` AS `cid`
1517                         FROM `item`
1518                         INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1519                                 AND NOT `contact`.`blocked` AND NOT `contact`.`pending`
1520                         WHERE `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
1521                         AND `item`.`uid` = %d AND `item`.`verb` = '%s'
1522                         $sql_extra",
1523                         intval(api_user()),
1524                         dbesc(ACTIVITY_POST),
1525                         intval($id)
1526                 );
1527
1528                 if (!$r) {
1529                         throw new BadRequestException("There is no status with this id.");
1530                 }
1531
1532                 $ret = api_format_items($r,$user_info, false, $type);
1533
1534                 if ($conversation) {
1535                         $data = array('status' => $ret);
1536                         return api_format_data("statuses", $type, $data);
1537                 } else {
1538                         $data = array('status' => $ret[0]);
1539                         return  api_format_data("status", $type, $data);
1540                 }
1541         }
1542         api_register_func('api/statuses/show','api_statuses_show', true);
1543
1544
1545         /**
1546          *
1547          */
1548         function api_conversation_show(&$a, $type){
1549                 if (api_user()===false) throw new ForbiddenException();
1550
1551                 $user_info = api_get_user($a);
1552
1553                 // params
1554                 $id = intval($a->argv[3]);
1555                 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1556                 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1557                 if ($page<0) $page=0;
1558                 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1559                 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1560
1561                 $start = $page*$count;
1562
1563                 if ($id == 0)
1564                         $id = intval($_REQUEST["id"]);
1565
1566                 // Hotot workaround
1567                 if ($id == 0)
1568                         $id = intval($a->argv[4]);
1569
1570                 logger('API: api_conversation_show: '.$id);
1571
1572                 $r = q("SELECT `parent` FROM `item` WHERE `id` = %d", intval($id));
1573                 if ($r)
1574                         $id = $r[0]["parent"];
1575
1576                 $sql_extra = '';
1577
1578                 if ($max_id > 0)
1579                         $sql_extra = ' AND `item`.`id` <= '.intval($max_id);
1580
1581                 // Not sure why this query was so complicated. We should keep it here for a while,
1582                 // just to make sure that we really don't need it.
1583                 //      FROM `item` INNER JOIN (SELECT `uri`,`parent` FROM `item` WHERE `id` = %d) AS `temp1`
1584                 //      ON (`item`.`thr-parent` = `temp1`.`uri` AND `item`.`parent` = `temp1`.`parent`)
1585
1586                 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1587                         `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1588                         `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1589                         `contact`.`id` AS `cid`
1590                         FROM `item`
1591                         STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1592                                 AND NOT `contact`.`blocked` AND NOT `contact`.`pending`
1593                         WHERE `item`.`parent` = %d AND `item`.`visible`
1594                         AND NOT `item`.`moderated` AND NOT `item`.`deleted`
1595                         AND `item`.`uid` = %d AND `item`.`verb` = '%s'
1596                         AND `item`.`id`>%d $sql_extra
1597                         ORDER BY `item`.`id` DESC LIMIT %d ,%d",
1598                         intval($id), intval(api_user()),
1599                         dbesc(ACTIVITY_POST),
1600                         intval($since_id),
1601                         intval($start), intval($count)
1602                 );
1603
1604                 if (!$r)
1605                         throw new BadRequestException("There is no conversation with this id.");
1606
1607                 $ret = api_format_items($r,$user_info, false, $type);
1608
1609                 $data = array('status' => $ret);
1610                 return api_format_data("statuses", $type, $data);
1611         }
1612         api_register_func('api/conversation/show','api_conversation_show', true);
1613         api_register_func('api/statusnet/conversation','api_conversation_show', true);
1614
1615
1616         /**
1617          *
1618          */
1619         function api_statuses_repeat(&$a, $type){
1620                 global $called_api;
1621
1622                 if (api_user()===false) throw new ForbiddenException();
1623
1624                 $user_info = api_get_user($a);
1625
1626                 // params
1627                 $id = intval($a->argv[3]);
1628
1629                 if ($id == 0)
1630                         $id = intval($_REQUEST["id"]);
1631
1632                 // Hotot workaround
1633                 if ($id == 0)
1634                         $id = intval($a->argv[4]);
1635
1636                 logger('API: api_statuses_repeat: '.$id);
1637
1638                 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`, `contact`.`nick` as `reply_author`,
1639                         `contact`.`name`, `contact`.`photo` as `reply_photo`, `contact`.`url` as `reply_url`, `contact`.`rel`,
1640                         `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1641                         `contact`.`id` AS `cid`
1642                         FROM `item`
1643                         INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1644                                 AND NOT `contact`.`blocked` AND NOT `contact`.`pending`
1645                         WHERE `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
1646                         AND NOT `item`.`private` AND `item`.`allow_cid` = '' AND `item`.`allow`.`gid` = ''
1647                         AND `item`.`deny_cid` = '' AND `item`.`deny_gid` = ''
1648                         $sql_extra
1649                         AND `item`.`id`=%d",
1650                         intval($id)
1651                 );
1652
1653                 if ($r[0]['body'] != "") {
1654                         if (!intval(get_config('system','old_share'))) {
1655                                 if (strpos($r[0]['body'], "[/share]") !== false) {
1656                                         $pos = strpos($r[0]['body'], "[share");
1657                                         $post = substr($r[0]['body'], $pos);
1658                                 } else {
1659                                         $post = share_header($r[0]['author-name'], $r[0]['author-link'], $r[0]['author-avatar'], $r[0]['guid'], $r[0]['created'], $r[0]['plink']);
1660
1661                                         $post .= $r[0]['body'];
1662                                         $post .= "[/share]";
1663                                 }
1664                                 $_REQUEST['body'] = $post;
1665                         } else
1666                                 $_REQUEST['body'] = html_entity_decode("&#x2672; ", ENT_QUOTES, 'UTF-8')."[url=".$r[0]['reply_url']."]".$r[0]['reply_author']."[/url] \n".$r[0]['body'];
1667
1668                         $_REQUEST['profile_uid'] = api_user();
1669                         $_REQUEST['type'] = 'wall';
1670                         $_REQUEST['api_source'] = true;
1671
1672                         if (!x($_REQUEST, "source"))
1673                                 $_REQUEST["source"] = api_source();
1674
1675                         item_post($a);
1676                 } else
1677                         throw new ForbiddenException();
1678
1679                 // this should output the last post (the one we just posted).
1680                 $called_api = null;
1681                 return(api_status_show($a,$type));
1682         }
1683         api_register_func('api/statuses/retweet','api_statuses_repeat', true, API_METHOD_POST);
1684
1685         /**
1686          *
1687          */
1688         function api_statuses_destroy(&$a, $type){
1689                 if (api_user()===false) throw new ForbiddenException();
1690
1691                 $user_info = api_get_user($a);
1692
1693                 // params
1694                 $id = intval($a->argv[3]);
1695
1696                 if ($id == 0)
1697                         $id = intval($_REQUEST["id"]);
1698
1699                 // Hotot workaround
1700                 if ($id == 0)
1701                         $id = intval($a->argv[4]);
1702
1703                 logger('API: api_statuses_destroy: '.$id);
1704
1705                 $ret = api_statuses_show($a, $type);
1706
1707                 drop_item($id, false);
1708
1709                 return($ret);
1710         }
1711         api_register_func('api/statuses/destroy','api_statuses_destroy', true, API_METHOD_DELETE);
1712
1713         /**
1714          *
1715          * http://developer.twitter.com/doc/get/statuses/mentions
1716          *
1717          */
1718         function api_statuses_mentions(&$a, $type){
1719                 if (api_user()===false) throw new ForbiddenException();
1720
1721                 unset($_REQUEST["user_id"]);
1722                 unset($_GET["user_id"]);
1723
1724                 unset($_REQUEST["screen_name"]);
1725                 unset($_GET["screen_name"]);
1726
1727                 $user_info = api_get_user($a);
1728                 // get last newtork messages
1729
1730
1731                 // params
1732                 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1733                 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1734                 if ($page<0) $page=0;
1735                 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1736                 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1737                 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1738
1739                 $start = $page*$count;
1740
1741                 // Ugly code - should be changed
1742                 $myurl = $a->get_baseurl() . '/profile/'. $a->user['nickname'];
1743                 $myurl = substr($myurl,strpos($myurl,'://')+3);
1744                 //$myurl = str_replace(array('www.','.'),array('','\\.'),$myurl);
1745                 $myurl = str_replace('www.','',$myurl);
1746                 $diasp_url = str_replace('/profile/','/u/',$myurl);
1747
1748                 if ($max_id > 0)
1749                         $sql_extra = ' AND `item`.`id` <= '.intval($max_id);
1750
1751                 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1752                         `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1753                         `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1754                         `contact`.`id` AS `cid`
1755                         FROM `item` FORCE INDEX (`uid_id`)
1756                         STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1757                                 AND NOT `contact`.`blocked` AND NOT `contact`.`pending`
1758                         WHERE `item`.`uid` = %d AND `verb` = '%s'
1759                         AND NOT (`item`.`author-link` IN ('https://%s', 'http://%s'))
1760                         AND `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
1761                         AND `item`.`parent` IN (SELECT `iid` FROM `thread` WHERE `uid` = %d AND `mention` AND !`ignored`)
1762                         $sql_extra
1763                         AND `item`.`id`>%d
1764                         ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1765                         intval(api_user()),
1766                         dbesc(ACTIVITY_POST),
1767                         dbesc(protect_sprintf($myurl)),
1768                         dbesc(protect_sprintf($myurl)),
1769                         intval(api_user()),
1770                         intval($since_id),
1771                         intval($start), intval($count)
1772                 );
1773
1774                 $ret = api_format_items($r,$user_info, false, $type);
1775
1776
1777                 $data = array('status' => $ret);
1778                 switch($type){
1779                         case "atom":
1780                         case "rss":
1781                                 $data = api_rss_extra($a, $data, $user_info);
1782                                 break;
1783                 }
1784
1785                 return  api_format_data("statuses", $type, $data);
1786         }
1787         api_register_func('api/statuses/mentions','api_statuses_mentions', true);
1788         api_register_func('api/statuses/replies','api_statuses_mentions', true);
1789
1790
1791         function api_statuses_user_timeline(&$a, $type){
1792                 if (api_user()===false) throw new ForbiddenException();
1793
1794                 $user_info = api_get_user($a);
1795                 // get last network messages
1796
1797                 logger("api_statuses_user_timeline: api_user: ". api_user() .
1798                            "\nuser_info: ".print_r($user_info, true) .
1799                            "\n_REQUEST:  ".print_r($_REQUEST, true),
1800                            LOGGER_DEBUG);
1801
1802                 // params
1803                 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1804                 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1805                 if ($page<0) $page=0;
1806                 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1807                 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1808                 $exclude_replies = (x($_REQUEST,'exclude_replies')?1:0);
1809                 $conversation_id = (x($_REQUEST,'conversation_id')?$_REQUEST['conversation_id']:0);
1810
1811                 $start = $page*$count;
1812
1813                 $sql_extra = '';
1814                 if ($user_info['self']==1)
1815                         $sql_extra .= " AND `item`.`wall` = 1 ";
1816
1817                 if ($exclude_replies > 0)
1818                         $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
1819                 if ($conversation_id > 0)
1820                         $sql_extra .= ' AND `item`.`parent` = '.intval($conversation_id);
1821
1822                 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1823                         `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1824                         `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1825                         `contact`.`id` AS `cid`
1826                         FROM `item` FORCE INDEX (`uid_contactid_id`)
1827                         STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1828                                 AND NOT `contact`.`blocked` AND NOT `contact`.`pending`
1829                         WHERE `item`.`uid` = %d AND `verb` = '%s'
1830                         AND `item`.`contact-id` = %d
1831                         AND `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
1832                         $sql_extra
1833                         AND `item`.`id`>%d
1834                         ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1835                         intval(api_user()),
1836                         dbesc(ACTIVITY_POST),
1837                         intval($user_info['cid']),
1838                         intval($since_id),
1839                         intval($start), intval($count)
1840                 );
1841
1842                 $ret = api_format_items($r,$user_info, true, $type);
1843
1844                 $data = array('status' => $ret);
1845                 switch($type){
1846                         case "atom":
1847                         case "rss":
1848                                 $data = api_rss_extra($a, $data, $user_info);
1849                 }
1850
1851                 return  api_format_data("statuses", $type, $data);
1852         }
1853         api_register_func('api/statuses/user_timeline','api_statuses_user_timeline', true);
1854
1855
1856         /**
1857          * Star/unstar an item
1858          * param: id : id of the item
1859          *
1860          * api v1 : https://web.archive.org/web/20131019055350/https://dev.twitter.com/docs/api/1/post/favorites/create/%3Aid
1861          */
1862         function api_favorites_create_destroy(&$a, $type){
1863                 if (api_user()===false) throw new ForbiddenException();
1864
1865                 // for versioned api.
1866                 /// @TODO We need a better global soluton
1867                 $action_argv_id=2;
1868                 if ($a->argv[1]=="1.1") $action_argv_id=3;
1869
1870                 if ($a->argc<=$action_argv_id) throw new BadRequestException("Invalid request.");
1871                 $action = str_replace(".".$type,"",$a->argv[$action_argv_id]);
1872                 if ($a->argc==$action_argv_id+2) {
1873                         $itemid = intval($a->argv[$action_argv_id+1]);
1874                 } else {
1875                         $itemid = intval($_REQUEST['id']);
1876                 }
1877
1878                 $item = q("SELECT * FROM item WHERE id=%d AND uid=%d",
1879                                 $itemid, api_user());
1880
1881                 if ($item===false || count($item)==0)
1882                         throw new BadRequestException("Invalid item.");
1883
1884                 switch($action){
1885                         case "create":
1886                                 $item[0]['starred']=1;
1887                                 break;
1888                         case "destroy":
1889                                 $item[0]['starred']=0;
1890                                 break;
1891                         default:
1892                                 throw new BadRequestException("Invalid action ".$action);
1893                 }
1894                 $r = q("UPDATE item SET starred=%d WHERE id=%d AND uid=%d",
1895                                 $item[0]['starred'], $itemid, api_user());
1896
1897                 q("UPDATE thread SET starred=%d WHERE iid=%d AND uid=%d",
1898                         $item[0]['starred'], $itemid, api_user());
1899
1900                 if ($r===false)
1901                         throw InternalServerErrorException("DB error");
1902
1903
1904                 $user_info = api_get_user($a);
1905                 $rets = api_format_items($item,$user_info, false, $type);
1906                 $ret = $rets[0];
1907
1908                 $data = array('status' => $ret);
1909                 switch($type){
1910                         case "atom":
1911                         case "rss":
1912                                 $data = api_rss_extra($a, $data, $user_info);
1913                 }
1914
1915                 return api_format_data("status", $type, $data);
1916         }
1917         api_register_func('api/favorites/create', 'api_favorites_create_destroy', true, API_METHOD_POST);
1918         api_register_func('api/favorites/destroy', 'api_favorites_create_destroy', true, API_METHOD_DELETE);
1919
1920         function api_favorites(&$a, $type){
1921                 global $called_api;
1922
1923                 if (api_user()===false) throw new ForbiddenException();
1924
1925                 $called_api= array();
1926
1927                 $user_info = api_get_user($a);
1928
1929                 // in friendica starred item are private
1930                 // return favorites only for self
1931                 logger('api_favorites: self:' . $user_info['self']);
1932
1933                 if ($user_info['self']==0) {
1934                         $ret = array();
1935                 } else {
1936                         $sql_extra = "";
1937
1938                         // params
1939                         $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1940                         $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1941                         $count = (x($_GET,'count')?$_GET['count']:20);
1942                         $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1943                         if ($page<0) $page=0;
1944
1945                         $start = $page*$count;
1946
1947                         if ($max_id > 0)
1948                                 $sql_extra .= ' AND `item`.`id` <= '.intval($max_id);
1949
1950                         $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1951                                 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1952                                 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1953                                 `contact`.`id` AS `cid`
1954                                 FROM `item`, `contact`
1955                                 WHERE `item`.`uid` = %d
1956                                 AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1957                                 AND `item`.`starred` = 1
1958                                 AND `contact`.`id` = `item`.`contact-id`
1959                                 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1960                                 $sql_extra
1961                                 AND `item`.`id`>%d
1962                                 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1963                                 intval(api_user()),
1964                                 intval($since_id),
1965                                 intval($start), intval($count)
1966                         );
1967
1968                         $ret = api_format_items($r,$user_info, false, $type);
1969
1970                 }
1971
1972                 $data = array('status' => $ret);
1973                 switch($type){
1974                         case "atom":
1975                         case "rss":
1976                                 $data = api_rss_extra($a, $data, $user_info);
1977                 }
1978
1979                 return  api_format_data("statuses", $type, $data);
1980         }
1981         api_register_func('api/favorites','api_favorites', true);
1982
1983         function api_format_messages($item, $recipient, $sender) {
1984                 // standard meta information
1985                 $ret=Array(
1986                                 'id'                    => $item['id'],
1987                                 'sender_id'             => $sender['id'] ,
1988                                 'text'                  => "",
1989                                 'recipient_id'          => $recipient['id'],
1990                                 'created_at'            => api_date($item['created']),
1991                                 'sender_screen_name'    => $sender['screen_name'],
1992                                 'recipient_screen_name' => $recipient['screen_name'],
1993                                 'sender'                => $sender,
1994                                 'recipient'             => $recipient,
1995                 );
1996
1997                 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1998                 unset($ret["sender"]["uid"]);
1999                 unset($ret["sender"]["self"]);
2000                 unset($ret["recipient"]["uid"]);
2001                 unset($ret["recipient"]["self"]);
2002
2003                 //don't send title to regular StatusNET requests to avoid confusing these apps
2004                 if (x($_GET, 'getText')) {
2005                         $ret['title'] = $item['title'] ;
2006                         if ($_GET["getText"] == "html") {
2007                                 $ret['text'] = bbcode($item['body'], false, false);
2008                         }
2009                         elseif ($_GET["getText"] == "plain") {
2010                                 //$ret['text'] = html2plain(bbcode($item['body'], false, false, true), 0);
2011                                 $ret['text'] = trim(html2plain(bbcode(api_clean_plain_items($item['body']), false, false, 2, true), 0));
2012                         }
2013                 }
2014                 else {
2015                         $ret['text'] = $item['title']."\n".html2plain(bbcode(api_clean_plain_items($item['body']), false, false, 2, true), 0);
2016                 }
2017                 if (isset($_GET["getUserObjects"]) && $_GET["getUserObjects"] == "false") {
2018                         unset($ret['sender']);
2019                         unset($ret['recipient']);
2020                 }
2021
2022                 return $ret;
2023         }
2024
2025         function api_convert_item($item) {
2026                 $body = $item['body'];
2027                 $attachments = api_get_attachments($body);
2028
2029                 // Workaround for ostatus messages where the title is identically to the body
2030                 $html = bbcode(api_clean_plain_items($body), false, false, 2, true);
2031                 $statusbody = trim(html2plain($html, 0));
2032
2033                 // handle data: images
2034                 $statusbody = api_format_items_embeded_images($item,$statusbody);
2035
2036                 $statustitle = trim($item['title']);
2037
2038                 if (($statustitle != '') and (strpos($statusbody, $statustitle) !== false))
2039                         $statustext = trim($statusbody);
2040                 else
2041                         $statustext = trim($statustitle."\n\n".$statusbody);
2042
2043                 if (($item["network"] == NETWORK_FEED) and (strlen($statustext)> 1000))
2044                         $statustext = substr($statustext, 0, 1000)."... \n".$item["plink"];
2045
2046                 $statushtml = trim(bbcode($body, false, false));
2047
2048                 $search = array("<br>", "<blockquote>", "</blockquote>",
2049                                 "<h1>", "</h1>", "<h2>", "</h2>",
2050                                 "<h3>", "</h3>", "<h4>", "</h4>",
2051                                 "<h5>", "</h5>", "<h6>", "</h6>");
2052                 $replace = array("<br>\n", "\n<blockquote>", "</blockquote>\n",
2053                                 "\n<h1>", "</h1>\n", "\n<h2>", "</h2>\n",
2054                                 "\n<h3>", "</h3>\n", "\n<h4>", "</h4>\n",
2055                                 "\n<h5>", "</h5>\n", "\n<h6>", "</h6>\n");
2056                 $statushtml = str_replace($search, $replace, $statushtml);
2057
2058                 if ($item['title'] != "")
2059                         $statushtml = "<h4>".bbcode($item['title'])."</h4>\n".$statushtml;
2060
2061                 $entities = api_get_entitities($statustext, $body);
2062
2063                 return array(
2064                         "text" => $statustext,
2065                         "html" => $statushtml,
2066                         "attachments" => $attachments,
2067                         "entities" => $entities
2068                 );
2069         }
2070
2071         function api_get_attachments(&$body) {
2072
2073                 $text = $body;
2074                 $text = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $text);
2075
2076                 $URLSearchString = "^\[\]";
2077                 $ret = preg_match_all("/\[img\]([$URLSearchString]*)\[\/img\]/ism", $text, $images);
2078
2079                 if (!$ret)
2080                         return false;
2081
2082                 $attachments = array();
2083
2084                 foreach ($images[1] AS $image) {
2085                         $imagedata = get_photo_info($image);
2086
2087                         if ($imagedata)
2088                                 $attachments[] = array("url" => $image, "mimetype" => $imagedata["mime"], "size" => $imagedata["size"]);
2089                 }
2090
2091                 if (strstr($_SERVER['HTTP_USER_AGENT'], "AndStatus"))
2092                         foreach ($images[0] AS $orig)
2093                                 $body = str_replace($orig, "", $body);
2094
2095                 return $attachments;
2096         }
2097
2098         function api_get_entitities(&$text, $bbcode) {
2099                 /*
2100                 To-Do:
2101                 * Links at the first character of the post
2102                 */
2103
2104                 $a = get_app();
2105
2106                 $include_entities = strtolower(x($_REQUEST,'include_entities')?$_REQUEST['include_entities']:"false");
2107
2108                 if ($include_entities != "true") {
2109
2110                         preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2111
2112                         foreach ($images[1] AS $image) {
2113                                 $replace = proxy_url($image);
2114                                 $text = str_replace($image, $replace, $text);
2115                         }
2116                         return array();
2117                 }
2118
2119                 $bbcode = bb_CleanPictureLinks($bbcode);
2120
2121                 // Change pure links in text to bbcode uris
2122                 $bbcode = preg_replace("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", '$1[url=$2]$2[/url]', $bbcode);
2123
2124                 $entities = array();
2125                 $entities["hashtags"] = array();
2126                 $entities["symbols"] = array();
2127                 $entities["urls"] = array();
2128                 $entities["user_mentions"] = array();
2129
2130                 $URLSearchString = "^\[\]";
2131
2132                 $bbcode = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'#$2',$bbcode);
2133
2134                 $bbcode = preg_replace("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism",'[url=$1]$2[/url]',$bbcode);
2135                 //$bbcode = preg_replace("/\[url\](.*?)\[\/url\]/ism",'[url=$1]$1[/url]',$bbcode);
2136                 $bbcode = preg_replace("/\[video\](.*?)\[\/video\]/ism",'[url=$1]$1[/url]',$bbcode);
2137
2138                 $bbcode = preg_replace("/\[youtube\]([A-Za-z0-9\-_=]+)(.*?)\[\/youtube\]/ism",
2139                                         '[url=https://www.youtube.com/watch?v=$1]https://www.youtube.com/watch?v=$1[/url]', $bbcode);
2140                 $bbcode = preg_replace("/\[youtube\](.*?)\[\/youtube\]/ism",'[url=$1]$1[/url]',$bbcode);
2141
2142                 $bbcode = preg_replace("/\[vimeo\]([0-9]+)(.*?)\[\/vimeo\]/ism",
2143                                         '[url=https://vimeo.com/$1]https://vimeo.com/$1[/url]', $bbcode);
2144                 $bbcode = preg_replace("/\[vimeo\](.*?)\[\/vimeo\]/ism",'[url=$1]$1[/url]',$bbcode);
2145
2146                 $bbcode = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $bbcode);
2147
2148                 //preg_match_all("/\[url\]([$URLSearchString]*)\[\/url\]/ism", $bbcode, $urls1);
2149                 preg_match_all("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $bbcode, $urls);
2150
2151                 $ordered_urls = array();
2152                 foreach ($urls[1] AS $id=>$url) {
2153                         //$start = strpos($text, $url, $offset);
2154                         $start = iconv_strpos($text, $url, 0, "UTF-8");
2155                         if (!($start === false))
2156                                 $ordered_urls[$start] = array("url" => $url, "title" => $urls[2][$id]);
2157                 }
2158
2159                 ksort($ordered_urls);
2160
2161                 $offset = 0;
2162                 //foreach ($urls[1] AS $id=>$url) {
2163                 foreach ($ordered_urls AS $url) {
2164                         if ((substr($url["title"], 0, 7) != "http://") AND (substr($url["title"], 0, 8) != "https://") AND
2165                                 !strpos($url["title"], "http://") AND !strpos($url["title"], "https://"))
2166                                 $display_url = $url["title"];
2167                         else {
2168                                 $display_url = str_replace(array("http://www.", "https://www."), array("", ""), $url["url"]);
2169                                 $display_url = str_replace(array("http://", "https://"), array("", ""), $display_url);
2170
2171                                 if (strlen($display_url) > 26)
2172                                         $display_url = substr($display_url, 0, 25)."…";
2173                         }
2174
2175                         //$start = strpos($text, $url, $offset);
2176                         $start = iconv_strpos($text, $url["url"], $offset, "UTF-8");
2177                         if (!($start === false)) {
2178                                 $entities["urls"][] = array("url" => $url["url"],
2179                                                                 "expanded_url" => $url["url"],
2180                                                                 "display_url" => $display_url,
2181                                                                 "indices" => array($start, $start+strlen($url["url"])));
2182                                 $offset = $start + 1;
2183                         }
2184                 }
2185
2186                 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2187                 $ordered_images = array();
2188                 foreach ($images[1] AS $image) {
2189                         //$start = strpos($text, $url, $offset);
2190                         $start = iconv_strpos($text, $image, 0, "UTF-8");
2191                         if (!($start === false))
2192                                 $ordered_images[$start] = $image;
2193                 }
2194                 //$entities["media"] = array();
2195                 $offset = 0;
2196
2197                 foreach ($ordered_images AS $url) {
2198                         $display_url = str_replace(array("http://www.", "https://www."), array("", ""), $url);
2199                         $display_url = str_replace(array("http://", "https://"), array("", ""), $display_url);
2200
2201                         if (strlen($display_url) > 26)
2202                                 $display_url = substr($display_url, 0, 25)."…";
2203
2204                         $start = iconv_strpos($text, $url, $offset, "UTF-8");
2205                         if (!($start === false)) {
2206                                 $image = get_photo_info($url);
2207                                 if ($image) {
2208                                         // If image cache is activated, then use the following sizes:
2209                                         // thumb  (150), small (340), medium (600) and large (1024)
2210                                         if (!get_config("system", "proxy_disabled")) {
2211                                                 $media_url = proxy_url($url);
2212
2213                                                 $sizes = array();
2214                                                 $scale = scale_image($image[0], $image[1], 150);
2215                                                 $sizes["thumb"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2216
2217                                                 if (($image[0] > 150) OR ($image[1] > 150)) {
2218                                                         $scale = scale_image($image[0], $image[1], 340);
2219                                                         $sizes["small"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2220                                                 }
2221
2222                                                 $scale = scale_image($image[0], $image[1], 600);
2223                                                 $sizes["medium"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2224
2225                                                 if (($image[0] > 600) OR ($image[1] > 600)) {
2226                                                         $scale = scale_image($image[0], $image[1], 1024);
2227                                                         $sizes["large"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2228                                                 }
2229                                         } else {
2230                                                 $media_url = $url;
2231                                                 $sizes["medium"] = array("w" => $image[0], "h" => $image[1], "resize" => "fit");
2232                                         }
2233
2234                                         $entities["media"][] = array(
2235                                                                 "id" => $start+1,
2236                                                                 "id_str" => (string)$start+1,
2237                                                                 "indices" => array($start, $start+strlen($url)),
2238                                                                 "media_url" => normalise_link($media_url),
2239                                                                 "media_url_https" => $media_url,
2240                                                                 "url" => $url,
2241                                                                 "display_url" => $display_url,
2242                                                                 "expanded_url" => $url,
2243                                                                 "type" => "photo",
2244                                                                 "sizes" => $sizes);
2245                                 }
2246                                 $offset = $start + 1;
2247                         }
2248                 }
2249
2250                 return($entities);
2251         }
2252         function api_format_items_embeded_images(&$item, $text){
2253                 $a = get_app();
2254                 $text = preg_replace_callback(
2255                                 "|data:image/([^;]+)[^=]+=*|m",
2256                                 function($match) use ($a, $item) {
2257                                         return $a->get_baseurl()."/display/".$item['guid'];
2258                                 },
2259                                 $text);
2260                 return $text;
2261         }
2262
2263
2264         /**
2265          * @brief return <a href='url'>name</a> as array
2266          *
2267          * @param string $txt
2268          * @return array
2269          *                      name => 'name'
2270          *                      'url => 'url'
2271          */
2272         function api_contactlink_to_array($txt) {
2273                 $match = array();
2274                 $r = preg_match_all('|<a href="([^"]*)">([^<]*)</a>|', $txt, $match);
2275                 if ($r && count($match)==3) {
2276                         $res = array(
2277                                 'name' => $match[2],
2278                                 'url' => $match[1]
2279                         );
2280                 } else {
2281                         $res = array(
2282                                 'name' => $text,
2283                                 'url' => ""
2284                         );
2285                 }
2286                 return $res;
2287         }
2288
2289
2290         /**
2291          * @brief return likes, dislikes and attend status for item
2292          *
2293          * @param array $item
2294          * @return array
2295          *                      likes => int count
2296          *                      dislikes => int count
2297          */
2298         function api_format_items_activities(&$item, $type = "json") {
2299                 $activities = array(
2300                         'like' => array(),
2301                         'dislike' => array(),
2302                         'attendyes' => array(),
2303                         'attendno' => array(),
2304                         'attendmaybe' => array()
2305                 );
2306                 $items = q('SELECT * FROM item
2307                                         WHERE uid=%d AND `thr-parent`="%s" AND visible AND NOT deleted',
2308                                         intval($item['uid']),
2309                                         dbesc($item['uri']));
2310                 foreach ($items as $i){
2311                         builtin_activity_puller($i, $activities);
2312                 }
2313
2314                 if ($type == "xml") {
2315                         $xml_activities = array();
2316                         foreach ($activities as $k => $v)
2317                                 $xml_activities["friendica:".$k] = $v;
2318
2319                         $activities = $xml_activities;
2320                 }
2321
2322                 $res = array();
2323                 $uri = $item['uri']."-l";
2324                 foreach($activities as $k => $v) {
2325                         $res[$k] = ( x($v,$uri) ? array_map("api_contactlink_to_array", $v[$uri]) : array() );
2326                 }
2327
2328                 return $res;
2329         }
2330
2331         /**
2332          * @brief format items to be returned by api
2333          *
2334          * @param array $r array of items
2335          * @param array $user_info
2336          * @param bool $filter_user filter items by $user_info
2337          */
2338         function api_format_items($r,$user_info, $filter_user = false, $type = "json") {
2339
2340                 $a = get_app();
2341                 $ret = Array();
2342
2343                 foreach($r as $item) {
2344
2345                         localize_item($item);
2346                         list($status_user, $owner_user) = api_item_get_user($a,$item);
2347
2348                         // Look if the posts are matching if they should be filtered by user id
2349                         if ($filter_user AND ($status_user["id"] != $user_info["id"]))
2350                                 continue;
2351
2352                         if ($item['thr-parent'] != $item['uri']) {
2353                                 $r = q("SELECT id FROM item WHERE uid=%d AND uri='%s' LIMIT 1",
2354                                         intval(api_user()),
2355                                         dbesc($item['thr-parent']));
2356                                 if ($r)
2357                                         $in_reply_to_status_id = intval($r[0]['id']);
2358                                 else
2359                                         $in_reply_to_status_id = intval($item['parent']);
2360
2361                                 $in_reply_to_status_id_str = (string) intval($item['parent']);
2362
2363                                 $in_reply_to_screen_name = NULL;
2364                                 $in_reply_to_user_id = NULL;
2365                                 $in_reply_to_user_id_str = NULL;
2366
2367                                 $r = q("SELECT `author-link` FROM item WHERE uid=%d AND id=%d LIMIT 1",
2368                                         intval(api_user()),
2369                                         intval($in_reply_to_status_id));
2370                                 if ($r) {
2371                                         $r = q("SELECT * FROM `gcontact` WHERE `url` = '%s'", dbesc(normalise_link($r[0]['author-link'])));
2372
2373                                         if ($r) {
2374                                                 if ($r[0]['nick'] == "")
2375                                                         $r[0]['nick'] = api_get_nick($r[0]["url"]);
2376
2377                                                 $in_reply_to_screen_name = (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']);
2378                                                 $in_reply_to_user_id = intval($r[0]['id']);
2379                                                 $in_reply_to_user_id_str = (string) intval($r[0]['id']);
2380                                         }
2381                                 }
2382                         } else {
2383                                 $in_reply_to_screen_name = NULL;
2384                                 $in_reply_to_user_id = NULL;
2385                                 $in_reply_to_status_id = NULL;
2386                                 $in_reply_to_user_id_str = NULL;
2387                                 $in_reply_to_status_id_str = NULL;
2388                         }
2389
2390                         $converted = api_convert_item($item);
2391
2392                         if ($type == "xml")
2393                                 $geo = "georss:point";
2394                         else
2395                                 $geo = "geo";
2396
2397                         $status = array(
2398                                 'text'          => $converted["text"],
2399                                 'truncated' => False,
2400                                 'created_at'=> api_date($item['created']),
2401                                 'in_reply_to_status_id' => $in_reply_to_status_id,
2402                                 'in_reply_to_status_id_str' => $in_reply_to_status_id_str,
2403                                 'source'    => (($item['app']) ? $item['app'] : 'web'),
2404                                 'id'            => intval($item['id']),
2405                                 'id_str'        => (string) intval($item['id']),
2406                                 'in_reply_to_user_id' => $in_reply_to_user_id,
2407                                 'in_reply_to_user_id_str' => $in_reply_to_user_id_str,
2408                                 'in_reply_to_screen_name' => $in_reply_to_screen_name,
2409                                 $geo => NULL,
2410                                 'favorited' => $item['starred'] ? true : false,
2411                                 'user' =>  $status_user ,
2412                                 'friendica_owner' => $owner_user,
2413                                 //'entities' => NULL,
2414                                 'statusnet_html'                => $converted["html"],
2415                                 'statusnet_conversation_id'     => $item['parent'],
2416                                 'friendica_activities' => api_format_items_activities($item, $type),
2417                         );
2418
2419                         if (count($converted["attachments"]) > 0)
2420                                 $status["attachments"] = $converted["attachments"];
2421
2422                         if (count($converted["entities"]) > 0)
2423                                 $status["entities"] = $converted["entities"];
2424
2425                         if (($item['item_network'] != "") AND ($status["source"] == 'web'))
2426                                 $status["source"] = network_to_name($item['item_network'], $user_info['url']);
2427                         else if (($item['item_network'] != "") AND (network_to_name($item['item_network'], $user_info['url']) != $status["source"]))
2428                                 $status["source"] = trim($status["source"].' ('.network_to_name($item['item_network'], $user_info['url']).')');
2429
2430
2431                         // Retweets are only valid for top postings
2432                         // It doesn't work reliable with the link if its a feed
2433                         #$IsRetweet = ($item['owner-link'] != $item['author-link']);
2434                         #if ($IsRetweet)
2435                         #       $IsRetweet = (($item['owner-name'] != $item['author-name']) OR ($item['owner-avatar'] != $item['author-avatar']));
2436
2437
2438                         if ($item["id"] == $item["parent"]) {
2439                                 $retweeted_item = api_share_as_retweet($item);
2440                                 if ($retweeted_item !== false) {
2441                                         $retweeted_status = $status;
2442                                         try {
2443                                                 $retweeted_status["user"] = api_get_user($a,$retweeted_item["author-link"]);
2444                                         } catch( BadRequestException $e ) {
2445                                                 // user not found. should be found?
2446                                                 /// @todo check if the user should be always found
2447                                                 $retweeted_status["user"] = array();
2448                                         }
2449
2450                                         $rt_converted = api_convert_item($retweeted_item);
2451
2452                                         $retweeted_status['text'] = $rt_converted["text"];
2453                                         $retweeted_status['statusnet_html'] = $rt_converted["html"];
2454                                         $retweeted_status['friendica_activities'] = api_format_items_activities($retweeted_item, $type);
2455                                         $retweeted_status['created_at'] =  api_date($retweeted_item['created']);
2456                                         $status['retweeted_status'] = $retweeted_status;
2457                                 }
2458                         }
2459
2460                         // "uid" and "self" are only needed for some internal stuff, so remove it from here
2461                         unset($status["user"]["uid"]);
2462                         unset($status["user"]["self"]);
2463
2464                         if ($item["coord"] != "") {
2465                                 $coords = explode(' ',$item["coord"]);
2466                                 if (count($coords) == 2) {
2467                                         if ($type == "json")
2468                                                 $status["geo"] = array('type' => 'Point',
2469                                                                 'coordinates' => array((float) $coords[0],
2470                                                                                         (float) $coords[1]));
2471                                         else // Not sure if this is the official format - if someone founds a documentation we can check
2472                                                 $status["georss:point"] = $item["coord"];
2473                                 }
2474                         }
2475                         $ret[] = $status;
2476                 };
2477                 return $ret;
2478         }
2479
2480
2481         function api_account_rate_limit_status(&$a,$type) {
2482
2483                 if ($type == "xml")
2484                         $hash = array(
2485                                         'remaining-hits' => (string) 150,
2486                                         '@attributes' => array("type" => "integer"),
2487                                         'hourly-limit' => (string) 150,
2488                                         '@attributes2' => array("type" => "integer"),
2489                                         'reset-time' => datetime_convert('UTC','UTC','now + 1 hour',ATOM_TIME),
2490                                         '@attributes3' => array("type" => "datetime"),
2491                                         'reset_time_in_seconds' => strtotime('now + 1 hour'),
2492                                         '@attributes4' => array("type" => "integer"),
2493                                 );
2494                 else
2495                         $hash = array(
2496                                         'reset_time_in_seconds' => strtotime('now + 1 hour'),
2497                                         'remaining_hits' => (string) 150,
2498                                         'hourly_limit' => (string) 150,
2499                                         'reset_time' => api_date(datetime_convert('UTC','UTC','now + 1 hour',ATOM_TIME)),
2500                                 );
2501
2502                 return api_format_data('hash', $type, array('hash' => $hash));
2503         }
2504         api_register_func('api/account/rate_limit_status','api_account_rate_limit_status',true);
2505
2506         function api_help_test(&$a,$type) {
2507                 if ($type == 'xml')
2508                         $ok = "true";
2509                 else
2510                         $ok = "ok";
2511
2512                 return api_format_data('ok', $type, array("ok" => $ok));
2513         }
2514         api_register_func('api/help/test','api_help_test',false);
2515
2516         function api_lists(&$a,$type) {
2517                 $ret = array();
2518                 return api_format_data('lists', $type, array("lists_list" => $ret));
2519         }
2520         api_register_func('api/lists','api_lists',true);
2521
2522         function api_lists_list(&$a,$type) {
2523                 $ret = array();
2524                 return api_format_data('lists', $type, array("lists_list" => $ret));
2525         }
2526         api_register_func('api/lists/list','api_lists_list',true);
2527
2528         /**
2529          *  https://dev.twitter.com/docs/api/1/get/statuses/friends
2530          *  This function is deprecated by Twitter
2531          *  returns: json, xml
2532          **/
2533         function api_statuses_f(&$a, $type, $qtype) {
2534                 if (api_user()===false) throw new ForbiddenException();
2535                 $user_info = api_get_user($a);
2536
2537                 if (x($_GET,'cursor') && $_GET['cursor']=='undefined'){
2538                         /* this is to stop Hotot to load friends multiple times
2539                         *  I'm not sure if I'm missing return something or
2540                         *  is a bug in hotot. Workaround, meantime
2541                         */
2542
2543                         /*$ret=Array();
2544                         return array('$users' => $ret);*/
2545                         return false;
2546                 }
2547
2548                 if($qtype == 'friends')
2549                         $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
2550                 if($qtype == 'followers')
2551                         $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
2552
2553                 // friends and followers only for self
2554                 if ($user_info['self'] == 0)
2555                         $sql_extra = " AND false ";
2556
2557                 $r = q("SELECT `nurl` FROM `contact` WHERE `uid` = %d AND `self` = 0 AND `blocked` = 0 AND `pending` = 0 $sql_extra",
2558                         intval(api_user())
2559                 );
2560
2561                 $ret = array();
2562                 foreach($r as $cid){
2563                         $user = api_get_user($a, $cid['nurl']);
2564                         // "uid" and "self" are only needed for some internal stuff, so remove it from here
2565                         unset($user["uid"]);
2566                         unset($user["self"]);
2567
2568                         if ($user)
2569                                 $ret[] = $user;
2570                 }
2571
2572                 return array('user' => $ret);
2573
2574         }
2575         function api_statuses_friends(&$a, $type){
2576                 $data =  api_statuses_f($a,$type,"friends");
2577                 if ($data===false) return false;
2578                 return  api_format_data("users", $type, $data);
2579         }
2580         function api_statuses_followers(&$a, $type){
2581                 $data = api_statuses_f($a,$type,"followers");
2582                 if ($data===false) return false;
2583                 return  api_format_data("users", $type, $data);
2584         }
2585         api_register_func('api/statuses/friends','api_statuses_friends',true);
2586         api_register_func('api/statuses/followers','api_statuses_followers',true);
2587
2588
2589
2590
2591
2592
2593         function api_statusnet_config(&$a,$type) {
2594                 $name = $a->config['sitename'];
2595                 $server = $a->get_hostname();
2596                 $logo = $a->get_baseurl() . '/images/friendica-64.png';
2597                 $email = $a->config['admin_email'];
2598                 $closed = (($a->config['register_policy'] == REGISTER_CLOSED) ? 'true' : 'false');
2599                 $private = (($a->config['system']['block_public']) ? 'true' : 'false');
2600                 $textlimit = (string) (($a->config['max_import_size']) ? $a->config['max_import_size'] : 200000);
2601                 if($a->config['api_import_size'])
2602                         $texlimit = string($a->config['api_import_size']);
2603                 $ssl = (($a->config['system']['have_ssl']) ? 'true' : 'false');
2604                 $sslserver = (($ssl === 'true') ? str_replace('http:','https:',$a->get_baseurl()) : '');
2605
2606                 $config = array(
2607                         'site' => array('name' => $name,'server' => $server, 'theme' => 'default', 'path' => '',
2608                                 'logo' => $logo, 'fancy' => true, 'language' => 'en', 'email' => $email, 'broughtby' => '',
2609                                 'broughtbyurl' => '', 'timezone' => 'UTC', 'closed' => $closed, 'inviteonly' => false,
2610                                 'private' => $private, 'textlimit' => $textlimit, 'sslserver' => $sslserver, 'ssl' => $ssl,
2611                                 'shorturllength' => '30',
2612                                 'friendica' => array(
2613                                                 'FRIENDICA_PLATFORM' => FRIENDICA_PLATFORM,
2614                                                 'FRIENDICA_VERSION' => FRIENDICA_VERSION,
2615                                                 'DFRN_PROTOCOL_VERSION' => DFRN_PROTOCOL_VERSION,
2616                                                 'DB_UPDATE_VERSION' => DB_UPDATE_VERSION
2617                                                 )
2618                         ),
2619                 );
2620
2621                 return api_format_data('config', $type, array('config' => $config));
2622
2623         }
2624         api_register_func('api/statusnet/config','api_statusnet_config',false);
2625
2626         function api_statusnet_version(&$a,$type) {
2627                 // liar
2628                 $fake_statusnet_version = "0.9.7";
2629
2630                 return api_format_data('version', $type, array('version' => $fake_statusnet_version));
2631         }
2632         api_register_func('api/statusnet/version','api_statusnet_version',false);
2633
2634         /**
2635          * @todo use api_format_data() to return data
2636          */
2637         function api_ff_ids(&$a,$type,$qtype) {
2638                 if(! api_user()) throw new ForbiddenException();
2639
2640                 $user_info = api_get_user($a);
2641
2642                 if($qtype == 'friends')
2643                         $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
2644                 if($qtype == 'followers')
2645                         $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
2646
2647                 if (!$user_info["self"])
2648                         $sql_extra = " AND false ";
2649
2650                 $stringify_ids = (x($_REQUEST,'stringify_ids')?$_REQUEST['stringify_ids']:false);
2651
2652                 $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",
2653                         intval(api_user())
2654                 );
2655
2656                 if(!dbm::is_result($r))
2657                         return;
2658
2659                 $ids = array();
2660                 foreach($r as $rr)
2661                         if ($stringify_ids)
2662                                 $ids[] = $rr['id'];
2663                         else
2664                                 $ids[] = intval($rr['id']);
2665
2666                 return api_format_data("ids", $type, array('id' => $ids));
2667         }
2668
2669         function api_friends_ids(&$a,$type) {
2670                 return api_ff_ids($a,$type,'friends');
2671         }
2672         function api_followers_ids(&$a,$type) {
2673                 return api_ff_ids($a,$type,'followers');
2674         }
2675         api_register_func('api/friends/ids','api_friends_ids',true);
2676         api_register_func('api/followers/ids','api_followers_ids',true);
2677
2678
2679         function api_direct_messages_new(&$a, $type) {
2680                 if (api_user()===false) throw new ForbiddenException();
2681
2682                 if (!x($_POST, "text") OR (!x($_POST,"screen_name") AND !x($_POST,"user_id"))) return;
2683
2684                 $sender = api_get_user($a);
2685
2686                 if ($_POST['screen_name']) {
2687                         $r = q("SELECT `id`, `nurl`, `network` FROM `contact` WHERE `uid`=%d AND `nick`='%s'",
2688                                         intval(api_user()),
2689                                         dbesc($_POST['screen_name']));
2690
2691                         // Selecting the id by priority, friendica first
2692                         api_best_nickname($r);
2693
2694                         $recipient = api_get_user($a, $r[0]['nurl']);
2695                 } else
2696                         $recipient = api_get_user($a, $_POST['user_id']);
2697
2698                 $replyto = '';
2699                 $sub     = '';
2700                 if (x($_REQUEST,'replyto')) {
2701                         $r = q('SELECT `parent-uri`, `title` FROM `mail` WHERE `uid`=%d AND `id`=%d',
2702                                         intval(api_user()),
2703                                         intval($_REQUEST['replyto']));
2704                         $replyto = $r[0]['parent-uri'];
2705                         $sub     = $r[0]['title'];
2706                 }
2707                 else {
2708                         if (x($_REQUEST,'title')) {
2709                                 $sub = $_REQUEST['title'];
2710                         }
2711                         else {
2712                                 $sub = ((strlen($_POST['text'])>10)?substr($_POST['text'],0,10)."...":$_POST['text']);
2713                         }
2714                 }
2715
2716                 $id = send_message($recipient['cid'], $_POST['text'], $sub, $replyto);
2717
2718                 if ($id>-1) {
2719                         $r = q("SELECT * FROM `mail` WHERE id=%d", intval($id));
2720                         $ret = api_format_messages($r[0], $recipient, $sender);
2721
2722                 } else {
2723                         $ret = array("error"=>$id);
2724                 }
2725
2726                 $data = Array('direct_message'=>$ret);
2727
2728                 switch($type){
2729                         case "atom":
2730                         case "rss":
2731                                 $data = api_rss_extra($a, $data, $user_info);
2732                 }
2733
2734                 return  api_format_data("direct-messages", $type, $data);
2735
2736         }
2737         api_register_func('api/direct_messages/new','api_direct_messages_new',true, API_METHOD_POST);
2738
2739         function api_direct_messages_box(&$a, $type, $box) {
2740                 if (api_user()===false) throw new ForbiddenException();
2741
2742                 // params
2743                 $count = (x($_GET,'count')?$_GET['count']:20);
2744                 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
2745                 if ($page<0) $page=0;
2746
2747                 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
2748                 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
2749
2750                 $user_id = (x($_REQUEST,'user_id')?$_REQUEST['user_id']:"");
2751                 $screen_name = (x($_REQUEST,'screen_name')?$_REQUEST['screen_name']:"");
2752
2753                 //  caller user info
2754                 unset($_REQUEST["user_id"]);
2755                 unset($_GET["user_id"]);
2756
2757                 unset($_REQUEST["screen_name"]);
2758                 unset($_GET["screen_name"]);
2759
2760                 $user_info = api_get_user($a);
2761                 //$profile_url = $a->get_baseurl() . '/profile/' . $a->user['nickname'];
2762                 $profile_url = $user_info["url"];
2763
2764
2765                 // pagination
2766                 $start = $page*$count;
2767
2768                 // filters
2769                 if ($box=="sentbox") {
2770                         $sql_extra = "`mail`.`from-url`='".dbesc( $profile_url )."'";
2771                 }
2772                 elseif ($box=="conversation") {
2773                         $sql_extra = "`mail`.`parent-uri`='".dbesc( $_GET["uri"] )  ."'";
2774                 }
2775                 elseif ($box=="all") {
2776                         $sql_extra = "true";
2777                 }
2778                 elseif ($box=="inbox") {
2779                         $sql_extra = "`mail`.`from-url`!='".dbesc( $profile_url )."'";
2780                 }
2781
2782                 if ($max_id > 0)
2783                         $sql_extra .= ' AND `mail`.`id` <= '.intval($max_id);
2784
2785                 if ($user_id !="") {
2786                         $sql_extra .= ' AND `mail`.`contact-id` = ' . intval($user_id);
2787                 }
2788                 elseif($screen_name !=""){
2789                         $sql_extra .= " AND `contact`.`nick` = '" . dbesc($screen_name). "'";
2790                 }
2791
2792                 $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",
2793                                 intval(api_user()),
2794                                 intval($since_id),
2795                                 intval($start), intval($count)
2796                 );
2797
2798
2799                 $ret = Array();
2800                 foreach($r as $item) {
2801                         if ($box == "inbox" || $item['from-url'] != $profile_url){
2802                                 $recipient = $user_info;
2803                                 $sender = api_get_user($a,normalise_link($item['contact-url']));
2804                         }
2805                         elseif ($box == "sentbox" || $item['from-url'] == $profile_url){
2806                                 $recipient = api_get_user($a,normalise_link($item['contact-url']));
2807                                 $sender = $user_info;
2808
2809                         }
2810                         $ret[]=api_format_messages($item, $recipient, $sender);
2811                 }
2812
2813
2814                 $data = array('direct_message' => $ret);
2815                 switch($type){
2816                         case "atom":
2817                         case "rss":
2818                                 $data = api_rss_extra($a, $data, $user_info);
2819                 }
2820
2821                 return  api_format_data("direct-messages", $type, $data);
2822
2823         }
2824
2825         function api_direct_messages_sentbox(&$a, $type){
2826                 return api_direct_messages_box($a, $type, "sentbox");
2827         }
2828         function api_direct_messages_inbox(&$a, $type){
2829                 return api_direct_messages_box($a, $type, "inbox");
2830         }
2831         function api_direct_messages_all(&$a, $type){
2832                 return api_direct_messages_box($a, $type, "all");
2833         }
2834         function api_direct_messages_conversation(&$a, $type){
2835                 return api_direct_messages_box($a, $type, "conversation");
2836         }
2837         api_register_func('api/direct_messages/conversation','api_direct_messages_conversation',true);
2838         api_register_func('api/direct_messages/all','api_direct_messages_all',true);
2839         api_register_func('api/direct_messages/sent','api_direct_messages_sentbox',true);
2840         api_register_func('api/direct_messages','api_direct_messages_inbox',true);
2841
2842
2843
2844         function api_oauth_request_token(&$a, $type){
2845                 try{
2846                         $oauth = new FKOAuth1();
2847                         $r = $oauth->fetch_request_token(OAuthRequest::from_request());
2848                 }catch(Exception $e){
2849                         echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage()); killme();
2850                 }
2851                 echo $r;
2852                 killme();
2853         }
2854         function api_oauth_access_token(&$a, $type){
2855                 try{
2856                         $oauth = new FKOAuth1();
2857                         $r = $oauth->fetch_access_token(OAuthRequest::from_request());
2858                 }catch(Exception $e){
2859                         echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage()); killme();
2860                 }
2861                 echo $r;
2862                 killme();
2863         }
2864
2865         api_register_func('api/oauth/request_token', 'api_oauth_request_token', false);
2866         api_register_func('api/oauth/access_token', 'api_oauth_access_token', false);
2867
2868
2869         function api_fr_photos_list(&$a,$type) {
2870                 if (api_user()===false) throw new ForbiddenException();
2871                 $r = q("select `resource-id`, max(scale) as scale, album, filename, type from photo
2872                                 where uid = %d and album != 'Contact Photos' group by `resource-id`",
2873                         intval(local_user())
2874                 );
2875                 $typetoext = array(
2876                 'image/jpeg' => 'jpg',
2877                 'image/png' => 'png',
2878                 'image/gif' => 'gif'
2879                 );
2880                 $data = array('photo'=>array());
2881                 if($r) {
2882                         foreach($r as $rr) {
2883                                 $photo = array();
2884                                 $photo['id'] = $rr['resource-id'];
2885                                 $photo['album'] = $rr['album'];
2886                                 $photo['filename'] = $rr['filename'];
2887                                 $photo['type'] = $rr['type'];
2888                                 $thumb = $a->get_baseurl()."/photo/".$rr['resource-id']."-".$rr['scale'].".".$typetoext[$rr['type']];
2889
2890                                 if ($type == "xml")
2891                                         $data['photo'][] = array("@attributes" => $photo, "1" => $thumb);
2892                                 else {
2893                                         $photo['thumb'] = $thumb;
2894                                         $data['photo'][] = $photo;
2895                                 }
2896                         }
2897                 }
2898                 return  api_format_data("photos", $type, $data);
2899         }
2900
2901         function api_fr_photo_detail(&$a,$type) {
2902                 if (api_user()===false) throw new ForbiddenException();
2903                 if(!x($_REQUEST,'photo_id')) throw new BadRequestException("No photo id.");
2904
2905                 $scale = (x($_REQUEST, 'scale') ? intval($_REQUEST['scale']) : false);
2906                 $scale_sql = ($scale === false ? "" : sprintf("and scale=%d",intval($scale)));
2907                 $data_sql = ($scale === false ? "" : "data, ");
2908
2909                 $r = q("select %s `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
2910                                                 `type`, `height`, `width`, `datasize`, `profile`, min(`scale`) as minscale, max(`scale`) as maxscale
2911                                 from photo where `uid` = %d and `resource-id` = '%s' %s group by `resource-id`",
2912                         $data_sql,
2913                         intval(local_user()),
2914                         dbesc($_REQUEST['photo_id']),
2915                         $scale_sql
2916                 );
2917
2918                 $typetoext = array(
2919                 'image/jpeg' => 'jpg',
2920                 'image/png' => 'png',
2921                 'image/gif' => 'gif'
2922                 );
2923
2924                 if ($r) {
2925                         $data = array('photo' => $r[0]);
2926                         $data['photo']['id'] = $data['photo']['resource-id'];
2927                         if ($scale !== false) {
2928                                 $data['photo']['data'] = base64_encode($data['photo']['data']);
2929                         } else {
2930                                 unset($data['photo']['datasize']); //needed only with scale param
2931                         }
2932                         if ($type == "xml") {
2933                                 $data['photo']['links'] = array();
2934                                 for ($k=intval($data['photo']['minscale']); $k<=intval($data['photo']['maxscale']); $k++)
2935                                         $data['photo']['links'][$k.":link"]["@attributes"] = array("type" => $data['photo']['type'],
2936                                                                                         "scale" => $k,
2937                                                                                         "href" => $a->get_baseurl()."/photo/".$data['photo']['resource-id']."-".$k.".".$typetoext[$data['photo']['type']]);
2938                         } else {
2939                                 $data['photo']['link'] = array();
2940                                 for ($k=intval($data['photo']['minscale']); $k<=intval($data['photo']['maxscale']); $k++) {
2941                                         $data['photo']['link'][$k] = $a->get_baseurl()."/photo/".$data['photo']['resource-id']."-".$k.".".$typetoext[$data['photo']['type']];
2942                                 }
2943                         }
2944                         unset($data['photo']['resource-id']);
2945                         unset($data['photo']['minscale']);
2946                         unset($data['photo']['maxscale']);
2947
2948                 } else {
2949                         throw new NotFoundException();
2950                 }
2951
2952                 return api_format_data("photo_detail", $type, $data);
2953         }
2954
2955         api_register_func('api/friendica/photos/list', 'api_fr_photos_list', true);
2956         api_register_func('api/friendica/photo', 'api_fr_photo_detail', true);
2957
2958
2959
2960         /**
2961          * similar as /mod/redir.php
2962          * redirect to 'url' after dfrn auth
2963          *
2964          * why this when there is mod/redir.php already?
2965          * This use api_user() and api_login()
2966          *
2967          * params
2968          *              c_url: url of remote contact to auth to
2969          *              url: string, url to redirect after auth
2970          */
2971         function api_friendica_remoteauth(&$a) {
2972                 $url = ((x($_GET,'url')) ? $_GET['url'] : '');
2973                 $c_url = ((x($_GET,'c_url')) ? $_GET['c_url'] : '');
2974
2975                 if ($url === '' || $c_url === '')
2976                         throw new BadRequestException("Wrong parameters.");
2977
2978                 $c_url = normalise_link($c_url);
2979
2980                 // traditional DFRN
2981
2982                 $r = q("SELECT * FROM `contact` WHERE `id` = %d AND `nurl` = '%s' LIMIT 1",
2983                         dbesc($c_url),
2984                         intval(api_user())
2985                 );
2986
2987                 if ((! count($r)) || ($r[0]['network'] !== NETWORK_DFRN))
2988                         throw new BadRequestException("Unknown contact");
2989
2990                 $cid = $r[0]['id'];
2991
2992                 $dfrn_id = $orig_id = (($r[0]['issued-id']) ? $r[0]['issued-id'] : $r[0]['dfrn-id']);
2993
2994                 if($r[0]['duplex'] && $r[0]['issued-id']) {
2995                         $orig_id = $r[0]['issued-id'];
2996                         $dfrn_id = '1:' . $orig_id;
2997                 }
2998                 if($r[0]['duplex'] && $r[0]['dfrn-id']) {
2999                         $orig_id = $r[0]['dfrn-id'];
3000                         $dfrn_id = '0:' . $orig_id;
3001                 }
3002
3003                 $sec = random_string();
3004
3005                 q("INSERT INTO `profile_check` ( `uid`, `cid`, `dfrn_id`, `sec`, `expire`)
3006                         VALUES( %d, %s, '%s', '%s', %d )",
3007                         intval(api_user()),
3008                         intval($cid),
3009                         dbesc($dfrn_id),
3010                         dbesc($sec),
3011                         intval(time() + 45)
3012                 );
3013
3014                 logger($r[0]['name'] . ' ' . $sec, LOGGER_DEBUG);
3015                 $dest = (($url) ? '&destination_url=' . $url : '');
3016                 goaway ($r[0]['poll'] . '?dfrn_id=' . $dfrn_id
3017                                 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
3018                                 . '&type=profile&sec=' . $sec . $dest . $quiet );
3019         }
3020         api_register_func('api/friendica/remoteauth', 'api_friendica_remoteauth', true);
3021
3022         /**
3023          * @brief Return the item shared, if the item contains only the [share] tag
3024          *
3025          * @param array $item Sharer item
3026          * @return array Shared item or false if not a reshare
3027          */
3028         function api_share_as_retweet(&$item) {
3029                 $body = trim($item["body"]);
3030
3031                 if (diaspora::is_reshare($body, false)===false) {
3032                         return false;
3033                 }
3034
3035                 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$1",$body);
3036                 // Skip if there is no shared message in there
3037                 // we already checked this in diaspora::is_reshare()
3038                 // but better one more than one less...
3039                 if ($body == $attributes)
3040                         return false;
3041
3042
3043                 // build the fake reshared item
3044                 $reshared_item = $item;
3045
3046                 $author = "";
3047                 preg_match("/author='(.*?)'/ism", $attributes, $matches);
3048                 if ($matches[1] != "")
3049                         $author = html_entity_decode($matches[1],ENT_QUOTES,'UTF-8');
3050
3051                 preg_match('/author="(.*?)"/ism', $attributes, $matches);
3052                 if ($matches[1] != "")
3053                         $author = $matches[1];
3054
3055                 $profile = "";
3056                 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
3057                 if ($matches[1] != "")
3058                         $profile = $matches[1];
3059
3060                 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
3061                 if ($matches[1] != "")
3062                         $profile = $matches[1];
3063
3064                 $avatar = "";
3065                 preg_match("/avatar='(.*?)'/ism", $attributes, $matches);
3066                 if ($matches[1] != "")
3067                         $avatar = $matches[1];
3068
3069                 preg_match('/avatar="(.*?)"/ism', $attributes, $matches);
3070                 if ($matches[1] != "")
3071                         $avatar = $matches[1];
3072
3073                 $link = "";
3074                 preg_match("/link='(.*?)'/ism", $attributes, $matches);
3075                 if ($matches[1] != "")
3076                         $link = $matches[1];
3077
3078                 preg_match('/link="(.*?)"/ism', $attributes, $matches);
3079                 if ($matches[1] != "")
3080                         $link = $matches[1];
3081
3082                 $posted = "";
3083                 preg_match("/posted='(.*?)'/ism", $attributes, $matches);
3084                 if ($matches[1] != "")
3085                         $posted= $matches[1];
3086
3087                 preg_match('/posted="(.*?)"/ism', $attributes, $matches);
3088                 if ($matches[1] != "")
3089                         $posted = $matches[1];
3090
3091                 $shared_body = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$2",$body);
3092
3093                 if (($shared_body == "") || ($profile == "") || ($author == "") || ($avatar == "") || ($posted == ""))
3094                         return false;
3095
3096
3097
3098                 $reshared_item["body"] = $shared_body;
3099                 $reshared_item["author-name"] = $author;
3100                 $reshared_item["author-link"] = $profile;
3101                 $reshared_item["author-avatar"] = $avatar;
3102                 $reshared_item["plink"] = $link;
3103                 $reshared_item["created"] = $posted;
3104                 $reshared_item["edited"] = $posted;
3105
3106                 return $reshared_item;
3107
3108         }
3109
3110         function api_get_nick($profile) {
3111                 /* To-Do:
3112                  - remove trailing junk from profile url
3113                  - pump.io check has to check the website
3114                 */
3115
3116                 $nick = "";
3117
3118                 $r = q("SELECT `nick` FROM `gcontact` WHERE `nurl` = '%s'",
3119                         dbesc(normalise_link($profile)));
3120                 if ($r)
3121                         $nick = $r[0]["nick"];
3122
3123                 if (!$nick == "") {
3124                         $r = q("SELECT `nick` FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s'",
3125                                 dbesc(normalise_link($profile)));
3126                         if ($r)
3127                                 $nick = $r[0]["nick"];
3128                 }
3129
3130                 if (!$nick == "") {
3131                         $friendica = preg_replace("=https?://(.*)/profile/(.*)=ism", "$2", $profile);
3132                         if ($friendica != $profile)
3133                                 $nick = $friendica;
3134                 }
3135
3136                 if (!$nick == "") {
3137                         $diaspora = preg_replace("=https?://(.*)/u/(.*)=ism", "$2", $profile);
3138                         if ($diaspora != $profile)
3139                                 $nick = $diaspora;
3140                 }
3141
3142                 if (!$nick == "") {
3143                         $twitter = preg_replace("=https?://twitter.com/(.*)=ism", "$1", $profile);
3144                         if ($twitter != $profile)
3145                                 $nick = $twitter;
3146                 }
3147
3148
3149                 if (!$nick == "") {
3150                         $StatusnetHost = preg_replace("=https?://(.*)/user/(.*)=ism", "$1", $profile);
3151                         if ($StatusnetHost != $profile) {
3152                                 $StatusnetUser = preg_replace("=https?://(.*)/user/(.*)=ism", "$2", $profile);
3153                                 if ($StatusnetUser != $profile) {
3154                                         $UserData = fetch_url("http://".$StatusnetHost."/api/users/show.json?user_id=".$StatusnetUser);
3155                                         $user = json_decode($UserData);
3156                                         if ($user)
3157                                                 $nick = $user->screen_name;
3158                                 }
3159                         }
3160                 }
3161
3162                 // To-Do: look at the page if its really a pumpio site
3163                 //if (!$nick == "") {
3164                 //      $pumpio = preg_replace("=https?://(.*)/(.*)/=ism", "$2", $profile."/");
3165                 //      if ($pumpio != $profile)
3166                 //              $nick = $pumpio;
3167                         //      <div class="media" id="profile-block" data-profile-id="acct:kabniel@microca.st">
3168
3169                 //}
3170
3171                 if ($nick != "")
3172                         return($nick);
3173
3174                 return(false);
3175         }
3176
3177         function api_clean_plain_items($Text) {
3178                 $include_entities = strtolower(x($_REQUEST,'include_entities')?$_REQUEST['include_entities']:"false");
3179
3180                 $Text = bb_CleanPictureLinks($Text);
3181                 $URLSearchString = "^\[\]";
3182
3183                 $Text = preg_replace("/([!#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'$1$3',$Text);
3184
3185                 if ($include_entities == "true") {
3186                         $Text = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'[url=$1]$1[/url]',$Text);
3187                 }
3188
3189                 // Simplify "attachment" element
3190                 $Text = api_clean_attachments($Text);
3191
3192                 return($Text);
3193         }
3194
3195         /**
3196          * @brief Removes most sharing information for API text export
3197          *
3198          * @param string $body The original body
3199          *
3200          * @return string Cleaned body
3201          */
3202         function api_clean_attachments($body) {
3203                 $data = get_attachment_data($body);
3204
3205                 if (!$data)
3206                         return $body;
3207
3208                 $body = "";
3209
3210                 if (isset($data["text"]))
3211                         $body = $data["text"];
3212
3213                 if (($body == "") AND (isset($data["title"])))
3214                         $body = $data["title"];
3215
3216                 if (isset($data["url"]))
3217                         $body .= "\n".$data["url"];
3218
3219                 $body .= $data["after"];
3220
3221                 return $body;
3222         }
3223
3224         function api_best_nickname(&$contacts) {
3225                 $best_contact = array();
3226
3227                 if (count($contact) == 0)
3228                         return;
3229
3230                 foreach ($contacts AS $contact)
3231                         if ($contact["network"] == "") {
3232                                 $contact["network"] = "dfrn";
3233                                 $best_contact = array($contact);
3234                         }
3235
3236                 if (sizeof($best_contact) == 0)
3237                         foreach ($contacts AS $contact)
3238                                 if ($contact["network"] == "dfrn")
3239                                         $best_contact = array($contact);
3240
3241                 if (sizeof($best_contact) == 0)
3242                         foreach ($contacts AS $contact)
3243                                 if ($contact["network"] == "dspr")
3244                                         $best_contact = array($contact);
3245
3246                 if (sizeof($best_contact) == 0)
3247                         foreach ($contacts AS $contact)
3248                                 if ($contact["network"] == "stat")
3249                                         $best_contact = array($contact);
3250
3251                 if (sizeof($best_contact) == 0)
3252                         foreach ($contacts AS $contact)
3253                                 if ($contact["network"] == "pump")
3254                                         $best_contact = array($contact);
3255
3256                 if (sizeof($best_contact) == 0)
3257                         foreach ($contacts AS $contact)
3258                                 if ($contact["network"] == "twit")
3259                                         $best_contact = array($contact);
3260
3261                 if (sizeof($best_contact) == 1)
3262                         $contacts = $best_contact;
3263                 else
3264                         $contacts = array($contacts[0]);
3265         }
3266
3267         // return all or a specified group of the user with the containing contacts
3268         function api_friendica_group_show(&$a, $type) {
3269                 if (api_user()===false) throw new ForbiddenException();
3270
3271                 // params
3272                 $user_info = api_get_user($a);
3273                 $gid = (x($_REQUEST,'gid') ? $_REQUEST['gid'] : 0);
3274                 $uid = $user_info['uid'];
3275
3276                 // get data of the specified group id or all groups if not specified
3277                 if ($gid != 0) {
3278                         $r = q("SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d AND `id` = %d",
3279                                 intval($uid),
3280                                 intval($gid));
3281                         // error message if specified gid is not in database
3282                         if (count($r) == 0)
3283                                 throw new BadRequestException("gid not available");
3284                 }
3285                 else
3286                         $r = q("SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d",
3287                                 intval($uid));
3288
3289                 // loop through all groups and retrieve all members for adding data in the user array
3290                 foreach ($r as $rr) {
3291                         $members = group_get_members($rr['id']);
3292                         $users = array();
3293
3294                         if ($type == "xml") {
3295                                 $user_element = "users";
3296                                 $k = 0;
3297                                 foreach ($members as $member) {
3298                                         $user = api_get_user($a, $member['nurl']);
3299                                         $users[$k++.":user"] = $user;
3300                                 }
3301                         } else {
3302                                 $user_element = "user";
3303                                 foreach ($members as $member) {
3304                                         $user = api_get_user($a, $member['nurl']);
3305                                         $users[] = $user;
3306                                 }
3307                         }
3308                         $grps[] = array('name' => $rr['name'], 'gid' => $rr['id'], $user_element => $users);
3309                 }
3310                 return api_format_data("groups", $type, array('group' => $grps));
3311         }
3312         api_register_func('api/friendica/group_show', 'api_friendica_group_show', true);
3313
3314
3315         // delete the specified group of the user
3316         function api_friendica_group_delete(&$a, $type) {
3317                 if (api_user()===false) throw new ForbiddenException();
3318
3319                 // params
3320                 $user_info = api_get_user($a);
3321                 $gid = (x($_REQUEST,'gid') ? $_REQUEST['gid'] : 0);
3322                 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
3323                 $uid = $user_info['uid'];
3324
3325                 // error if no gid specified
3326                 if ($gid == 0 || $name == "")
3327                         throw new BadRequestException('gid or name not specified');
3328
3329                 // get data of the specified group id
3330                 $r = q("SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d",
3331                         intval($uid),
3332                         intval($gid));
3333                 // error message if specified gid is not in database
3334                 if (count($r) == 0)
3335                         throw new BadRequestException('gid not available');
3336
3337                 // get data of the specified group id and group name
3338                 $rname = q("SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d AND `name` = '%s'",
3339                         intval($uid),
3340                         intval($gid),
3341                         dbesc($name));
3342                 // error message if specified gid is not in database
3343                 if (count($rname) == 0)
3344                         throw new BadRequestException('wrong group name');
3345
3346                 // delete group
3347                 $ret = group_rmv($uid, $name);
3348                 if ($ret) {
3349                         // return success
3350                         $success = array('success' => $ret, 'gid' => $gid, 'name' => $name, 'status' => 'deleted', 'wrong users' => array());
3351                         return api_format_data("group_delete", $type, array('result' => $success));
3352                 }
3353                 else
3354                         throw new BadRequestException('other API error');
3355         }
3356         api_register_func('api/friendica/group_delete', 'api_friendica_group_delete', true, API_METHOD_DELETE);
3357
3358
3359         // create the specified group with the posted array of contacts
3360         function api_friendica_group_create(&$a, $type) {
3361                 if (api_user()===false) throw new ForbiddenException();
3362
3363                 // params
3364                 $user_info = api_get_user($a);
3365                 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
3366                 $uid = $user_info['uid'];
3367                 $json = json_decode($_POST['json'], true);
3368                 $users = $json['user'];
3369
3370                 // error if no name specified
3371                 if ($name == "")
3372                         throw new BadRequestException('group name not specified');
3373
3374                 // get data of the specified group name
3375                 $rname = q("SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 0",
3376                         intval($uid),
3377                         dbesc($name));
3378                 // error message if specified group name already exists
3379                 if (count($rname) != 0)
3380                         throw new BadRequestException('group name already exists');
3381
3382                 // check if specified group name is a deleted group
3383                 $rname = q("SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 1",
3384                         intval($uid),
3385                         dbesc($name));
3386                 // error message if specified group name already exists
3387                 if (count($rname) != 0)
3388                         $reactivate_group = true;
3389
3390                 // create group
3391                 $ret = group_add($uid, $name);
3392                 if ($ret)
3393                         $gid = group_byname($uid, $name);
3394                 else
3395                         throw new BadRequestException('other API error');
3396
3397                 // add members
3398                 $erroraddinguser = false;
3399                 $errorusers = array();
3400                 foreach ($users as $user) {
3401                         $cid = $user['cid'];
3402                         // check if user really exists as contact
3403                         $contact = q("SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
3404                                 intval($cid),
3405                                 intval($uid));
3406                         if (count($contact))
3407                                 $result = group_add_member($uid, $name, $cid, $gid);
3408                         else {
3409                                 $erroraddinguser = true;
3410                                 $errorusers[] = $cid;
3411                         }
3412                 }
3413
3414                 // return success message incl. missing users in array
3415                 $status = ($erroraddinguser ? "missing user" : ($reactivate_group ? "reactivated" : "ok"));
3416                 $success = array('success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers);
3417                 return api_format_data("group_create", $type, array('result' => $success));
3418         }
3419         api_register_func('api/friendica/group_create', 'api_friendica_group_create', true, API_METHOD_POST);
3420
3421
3422         // update the specified group with the posted array of contacts
3423         function api_friendica_group_update(&$a, $type) {
3424                 if (api_user()===false) throw new ForbiddenException();
3425
3426                 // params
3427                 $user_info = api_get_user($a);
3428                 $uid = $user_info['uid'];
3429                 $gid = (x($_REQUEST, 'gid') ? $_REQUEST['gid'] : 0);
3430                 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
3431                 $json = json_decode($_POST['json'], true);
3432                 $users = $json['user'];
3433
3434                 // error if no name specified
3435                 if ($name == "")
3436                         throw new BadRequestException('group name not specified');
3437
3438                 // error if no gid specified
3439                 if ($gid == "")
3440                         throw new BadRequestException('gid not specified');
3441
3442                 // remove members
3443                 $members = group_get_members($gid);
3444                 foreach ($members as $member) {
3445                         $cid = $member['id'];
3446                         foreach ($users as $user) {
3447                                 $found = ($user['cid'] == $cid ? true : false);
3448                         }
3449                         if (!$found) {
3450                                 $ret = group_rmv_member($uid, $name, $cid);
3451                         }
3452                 }
3453
3454                 // add members
3455                 $erroraddinguser = false;
3456                 $errorusers = array();
3457                 foreach ($users as $user) {
3458                         $cid = $user['cid'];
3459                         // check if user really exists as contact
3460                         $contact = q("SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
3461                                 intval($cid),
3462                                 intval($uid));
3463                         if (count($contact))
3464                                 $result = group_add_member($uid, $name, $cid, $gid);
3465                         else {
3466                                 $erroraddinguser = true;
3467                                 $errorusers[] = $cid;
3468                         }
3469                 }
3470
3471                 // return success message incl. missing users in array
3472                 $status = ($erroraddinguser ? "missing user" : "ok");
3473                 $success = array('success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers);
3474                 return api_format_data("group_update", $type, array('result' => $success));
3475         }
3476         api_register_func('api/friendica/group_update', 'api_friendica_group_update', true, API_METHOD_POST);
3477
3478
3479         function api_friendica_activity(&$a, $type) {
3480                 if (api_user()===false) throw new ForbiddenException();
3481                 $verb = strtolower($a->argv[3]);
3482                 $verb = preg_replace("|\..*$|", "", $verb);
3483
3484                 $id = (x($_REQUEST, 'id') ? $_REQUEST['id'] : 0);
3485
3486                 $res = do_like($id, $verb);
3487
3488                 if ($res) {
3489                         if ($type == "xml")
3490                                 $ok = "true";
3491                         else
3492                                 $ok = "ok";
3493                         return api_format_data('ok', $type, array('ok' => $ok));
3494                 } else {
3495                         throw new BadRequestException('Error adding activity');
3496                 }
3497
3498         }
3499         api_register_func('api/friendica/activity/like', 'api_friendica_activity', true, API_METHOD_POST);
3500         api_register_func('api/friendica/activity/dislike', 'api_friendica_activity', true, API_METHOD_POST);
3501         api_register_func('api/friendica/activity/attendyes', 'api_friendica_activity', true, API_METHOD_POST);
3502         api_register_func('api/friendica/activity/attendno', 'api_friendica_activity', true, API_METHOD_POST);
3503         api_register_func('api/friendica/activity/attendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
3504         api_register_func('api/friendica/activity/unlike', 'api_friendica_activity', true, API_METHOD_POST);
3505         api_register_func('api/friendica/activity/undislike', 'api_friendica_activity', true, API_METHOD_POST);
3506         api_register_func('api/friendica/activity/unattendyes', 'api_friendica_activity', true, API_METHOD_POST);
3507         api_register_func('api/friendica/activity/unattendno', 'api_friendica_activity', true, API_METHOD_POST);
3508         api_register_func('api/friendica/activity/unattendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
3509
3510         /**
3511          * @brief Returns notifications
3512          *
3513          * @param App $a
3514          * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3515          * @return string
3516         */
3517         function api_friendica_notification(&$a, $type) {
3518                 if (api_user()===false) throw new ForbiddenException();
3519                 if ($a->argc!==3) throw new BadRequestException("Invalid argument count");
3520                 $nm = new NotificationsManager();
3521
3522                 $notes = $nm->getAll(array(), "+seen -date", 50);
3523
3524                 if ($type == "xml") {
3525                         $xmlnotes = array();
3526                         foreach ($notes AS $note)
3527                                 $xmlnotes[] = array("@attributes" => $note);
3528
3529                         $notes = $xmlnotes;
3530                 }
3531
3532                 return api_format_data("notes", $type, array('note' => $notes));
3533         }
3534
3535         /**
3536          * @brief Set notification as seen and returns associated item (if possible)
3537          *
3538          * POST request with 'id' param as notification id
3539          *
3540          * @param App $a
3541          * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3542          * @return string
3543          */
3544         function api_friendica_notification_seen(&$a, $type){
3545                 if (api_user()===false) throw new ForbiddenException();
3546                 if ($a->argc!==4) throw new BadRequestException("Invalid argument count");
3547
3548                 $id = (x($_REQUEST, 'id') ? intval($_REQUEST['id']) : 0);
3549
3550                 $nm = new NotificationsManager();
3551                 $note = $nm->getByID($id);
3552                 if (is_null($note)) throw new BadRequestException("Invalid argument");
3553
3554                 $nm->setSeen($note);
3555                 if ($note['otype']=='item') {
3556                         // would be really better with an ItemsManager and $im->getByID() :-P
3557                         $r = q("SELECT * FROM `item` WHERE `id`=%d AND `uid`=%d",
3558                                 intval($note['iid']),
3559                                 intval(local_user())
3560                         );
3561                         if ($r!==false) {
3562                                 // we found the item, return it to the user
3563                                 $user_info = api_get_user($a);
3564                                 $ret = api_format_items($r,$user_info, false, $type);
3565                                 $data = array('status' => $ret);
3566                                 return api_format_data("status", $type, $data);
3567                         }
3568                         // the item can't be found, but we set the note as seen, so we count this as a success
3569                 }
3570                 return api_format_data('result', $type, array('result' => "success"));
3571         }
3572
3573         api_register_func('api/friendica/notification/seen', 'api_friendica_notification_seen', true, API_METHOD_POST);
3574         api_register_func('api/friendica/notification', 'api_friendica_notification', true, API_METHOD_GET);
3575
3576
3577 /*
3578 To.Do:
3579     [pagename] => api/1.1/statuses/lookup.json
3580     [id] => 605138389168451584
3581     [include_cards] => true
3582     [cards_platform] => Android-12
3583     [include_entities] => true
3584     [include_my_retweet] => 1
3585     [include_rts] => 1
3586     [include_reply_count] => true
3587     [include_descendent_reply_count] => true
3588 (?)
3589
3590
3591 Not implemented by now:
3592 statuses/retweets_of_me
3593 friendships/create
3594 friendships/destroy
3595 friendships/exists
3596 friendships/show
3597 account/update_location
3598 account/update_profile_background_image
3599 account/update_profile_image
3600 blocks/create
3601 blocks/destroy
3602
3603 Not implemented in status.net:
3604 statuses/retweeted_to_me
3605 statuses/retweeted_by_me
3606 direct_messages/destroy
3607 account/end_session
3608 account/update_delivery_device
3609 notifications/follow
3610 notifications/leave
3611 blocks/exists
3612 blocks/blocking
3613 lists
3614 */