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