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