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