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