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