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