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