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