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