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