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