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