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