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