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