]> git.mxchange.org Git - friendica.git/blob - include/api.php
Bugfix for failed events page and api
[friendica.git] / include / api.php
1 <?php
2 /**
3  * @file include/api.php
4  * Friendica implementation of statusnet/twitter API
5  *
6  * @todo Automatically detect if incoming data is HTML or BBCode
7  */
8         require_once('include/HTTPExceptions.php');
9
10         require_once('include/bbcode.php');
11         require_once('include/datetime.php');
12         require_once('include/conversation.php');
13         require_once('include/oauth.php');
14         require_once('include/html2plain.php');
15         require_once('mod/share.php');
16         require_once('include/Photo.php');
17         require_once('mod/item.php');
18         require_once('include/security.php');
19         require_once('include/contact_selectors.php');
20         require_once('include/html2bbcode.php');
21         require_once('mod/wall_upload.php');
22         require_once('mod/proxy.php');
23         require_once('include/message.php');
24         require_once('include/group.php');
25         require_once('include/like.php');
26         require_once('include/NotificationsManager.php');
27         require_once('include/plaintext.php');
28         require_once('include/xml.php');
29
30
31         define('API_METHOD_ANY','*');
32         define('API_METHOD_GET','GET');
33         define('API_METHOD_POST','POST,PUT');
34         define('API_METHOD_DELETE','POST,DELETE');
35
36
37
38         $API = Array();
39         $called_api = Null;
40
41         /**
42          * @brief Auth API user
43          *
44          * It is not sufficient to use local_user() to check whether someone is allowed to use the API,
45          * because this will open CSRF holes (just embed an image with src=friendicasite.com/api/statuses/update?status=CSRF
46          * into a page, and visitors will post something without noticing it).
47          */
48         function api_user() {
49                 if ($_SESSION['allow_api'])
50                         return local_user();
51
52                 return false;
53         }
54
55         /**
56          * @brief Get source name from API client
57          *
58          * Clients can send 'source' parameter to be show in post metadata
59          * as "sent via <source>".
60          * Some clients doesn't send a source param, we support ones we know
61          * (only Twidere, atm)
62          *
63          * @return string
64          *              Client source name, default to "api" if unset/unknown
65          */
66         function api_source() {
67                 if (requestdata('source'))
68                         return (requestdata('source'));
69
70                 // Support for known clients that doesn't send a source name
71                 if (strstr($_SERVER['HTTP_USER_AGENT'], "Twidere"))
72                         return ("Twidere");
73
74                 logger("Unrecognized user-agent ".$_SERVER['HTTP_USER_AGENT'], LOGGER_DEBUG);
75
76                 return ("api");
77         }
78
79         /**
80          * @brief Format date for API
81          *
82          * @param string $str Source date, as UTC
83          * @return string Date in UTC formatted as "D M d H:i:s +0000 Y"
84          */
85         function api_date($str){
86                 //Wed May 23 06:01:13 +0000 2007
87                 return datetime_convert('UTC', 'UTC', $str, "D M d H:i:s +0000 Y" );
88         }
89
90         /**
91          * @brief Register API endpoint
92          *
93          * Register a function to be the endpont for defined API path.
94          *
95          * @param string $path API URL path, relative to App::get_baseurl()
96          * @param string $func Function name to call on path request
97          * @param bool $auth API need logged user
98          * @param string $method
99          *      HTTP method reqiured to call this endpoint.
100          *      One of API_METHOD_ANY, API_METHOD_GET, API_METHOD_POST.
101          *  Default to API_METHOD_ANY
102          */
103         function api_register_func($path, $func, $auth=false, $method=API_METHOD_ANY){
104                 global $API;
105                 $API[$path] = array(
106                         'func'=>$func,
107                         'auth'=>$auth,
108                         'method'=> $method
109                 );
110
111                 // Workaround for hotot
112                 $path = str_replace("api/", "api/1.1/", $path);
113                 $API[$path] = array(
114                         'func'=>$func,
115                         'auth'=>$auth,
116                         'method'=> $method
117                 );
118         }
119
120         /**
121          * @brief Login API user
122          *
123          * Log in user via OAuth1 or Simple HTTP Auth.
124          * Simple Auth allow username in form of <pre>user@server</pre>, ignoring server part
125          *
126          * @param App $a
127          * @hook 'authenticate'
128          *              array $addon_auth
129          *                      'username' => username from login form
130          *                      'password' => password from login form
131          *                      'authenticated' => return status,
132          *                      'user_record' => return authenticated user record
133          * @hook 'logged_in'
134          *              array $user     logged user record
135          */
136         function api_login(App $a){
137                 // login with oauth
138                 try{
139                         $oauth = new FKOAuth1();
140                         list($consumer,$token) = $oauth->verify_request(OAuthRequest::from_request());
141                         if (!is_null($token)){
142                                 $oauth->loginUser($token->uid);
143                                 call_hooks('logged_in', $a->user);
144                                 return;
145                         }
146                         echo __file__.__line__.__function__."<pre>"; var_dump($consumer, $token); die();
147                 }catch(Exception $e){
148                         logger($e);
149                 }
150
151
152
153                 // workaround for HTTP-auth in CGI mode
154                 if(x($_SERVER,'REDIRECT_REMOTE_USER')) {
155                         $userpass = base64_decode(substr($_SERVER["REDIRECT_REMOTE_USER"],6)) ;
156                         if(strlen($userpass)) {
157                                 list($name, $password) = explode(':', $userpass);
158                                 $_SERVER['PHP_AUTH_USER'] = $name;
159                                 $_SERVER['PHP_AUTH_PW'] = $password;
160                         }
161                 }
162
163                 if (!isset($_SERVER['PHP_AUTH_USER'])) {
164                         logger('API_login: ' . print_r($_SERVER,true), LOGGER_DEBUG);
165                         header('WWW-Authenticate: Basic realm="Friendica"');
166                         throw new UnauthorizedException("This API requires login");
167                 }
168
169                 $user = $_SERVER['PHP_AUTH_USER'];
170                 $password = $_SERVER['PHP_AUTH_PW'];
171                 $encrypted = hash('whirlpool',trim($password));
172
173                 // allow "user@server" login (but ignore 'server' part)
174                 $at=strstr($user, "@", true);
175                 if ( $at ) $user=$at;
176
177                 /**
178                  *  next code from mod/auth.php. needs better solution
179                  */
180                 $record = null;
181
182                 $addon_auth = array(
183                         'username' => trim($user),
184                         'password' => trim($password),
185                         'authenticated' => 0,
186                         'user_record' => null
187                 );
188
189                 /**
190                  *
191                  * A plugin indicates successful login by setting 'authenticated' to non-zero value and returning a user record
192                  * Plugins should never set 'authenticated' except to indicate success - as hooks may be chained
193                  * and later plugins should not interfere with an earlier one that succeeded.
194                  *
195                  */
196
197                 call_hooks('authenticate', $addon_auth);
198
199                 if(($addon_auth['authenticated']) && (count($addon_auth['user_record']))) {
200                         $record = $addon_auth['user_record'];
201                 }
202                 else {
203                         // process normal login request
204
205                         $r = q("SELECT * FROM `user` WHERE (`email` = '%s' OR `nickname` = '%s')
206                                 AND `password` = '%s' AND NOT `blocked` AND NOT `account_expired` AND NOT `account_removed` AND `verified` LIMIT 1",
207                                 dbesc(trim($user)),
208                                 dbesc(trim($user)),
209                                 dbesc($encrypted)
210                         );
211                         if (dbm::is_result($r))
212                                 $record = $r[0];
213                 }
214
215                 if((! $record) || (! count($record))) {
216                         logger('API_login failure: ' . print_r($_SERVER,true), LOGGER_DEBUG);
217                         header('WWW-Authenticate: Basic realm="Friendica"');
218                         #header('HTTP/1.0 401 Unauthorized');
219                         #die('This api requires login');
220                         throw new UnauthorizedException("This API requires login");
221                 }
222
223                 authenticate_success($record);
224
225                 $_SESSION["allow_api"] = true;
226
227                 call_hooks('logged_in', $a->user);
228
229         }
230
231         /**
232          * @brief Check HTTP method of called API
233          *
234          * API endpoints can define which HTTP method to accept when called.
235          * This function check the current HTTP method agains endpoint
236          * registered method.
237          *
238          * @param string $method Required methods, uppercase, separated by comma
239          * @return bool
240          */
241          function api_check_method($method) {
242                 if ($method=="*") return True;
243                 return strpos($method, $_SERVER['REQUEST_METHOD']) !== false;
244          }
245
246         /**
247          * @brief Main API entry point
248          *
249          * Authenticate user, call registered API function, set HTTP headers
250          *
251          * @param App $a
252          * @return string API call result
253          */
254         function api_call(App $a){
255                 global $API, $called_api;
256
257                 $type="json";
258                 if (strpos($a->query_string, ".xml")>0) $type="xml";
259                 if (strpos($a->query_string, ".json")>0) $type="json";
260                 if (strpos($a->query_string, ".rss")>0) $type="rss";
261                 if (strpos($a->query_string, ".atom")>0) $type="atom";
262                 try {
263                         foreach ($API as $p=>$info){
264                                 if (strpos($a->query_string, $p)===0){
265                                         if (!api_check_method($info['method'])){
266                                                 throw new MethodNotAllowedException();
267                                         }
268
269                                         $called_api= explode("/",$p);
270                                         //unset($_SERVER['PHP_AUTH_USER']);
271                                         if ($info['auth']===true && api_user()===false) {
272                                                         api_login($a);
273                                         }
274
275                                         logger('API call for ' . $a->user['username'] . ': ' . $a->query_string);
276                                         logger('API parameters: ' . print_r($_REQUEST,true));
277
278                                         $stamp =  microtime(true);
279                                         $r = call_user_func($info['func'], $type);
280                                         $duration = (float)(microtime(true)-$stamp);
281                                         logger("API call duration: ".round($duration, 2)."\t".$a->query_string, LOGGER_DEBUG);
282
283                                         if (get_config("system", "profiler")) {
284                                                 $duration = microtime(true)-$a->performance["start"];
285
286                                                 logger(parse_url($a->query_string, PHP_URL_PATH).": ".sprintf("Database: %s/%s, Network: %s, I/O: %s, Other: %s, Total: %s",
287                                                         round($a->performance["database"] - $a->performance["database_write"], 3),
288                                                         round($a->performance["database_write"], 3),
289                                                         round($a->performance["network"], 2),
290                                                         round($a->performance["file"], 2),
291                                                         round($duration - ($a->performance["database"] + $a->performance["network"]
292                                                                 + $a->performance["file"]), 2),
293                                                         round($duration, 2)),
294                                                         LOGGER_DEBUG);
295
296                                                 if (get_config("rendertime", "callstack")) {
297                                                         $o = "Database Read:\n";
298                                                         foreach ($a->callstack["database"] AS $func => $time) {
299                                                                 $time = round($time, 3);
300                                                                 if ($time > 0)
301                                                                         $o .= $func.": ".$time."\n";
302                                                         }
303                                                         $o .= "\nDatabase Write:\n";
304                                                         foreach ($a->callstack["database_write"] AS $func => $time) {
305                                                                 $time = round($time, 3);
306                                                                 if ($time > 0)
307                                                                         $o .= $func.": ".$time."\n";
308                                                         }
309
310                                                         $o .= "\nNetwork:\n";
311                                                         foreach ($a->callstack["network"] AS $func => $time) {
312                                                                 $time = round($time, 3);
313                                                                 if ($time > 0)
314                                                                         $o .= $func.": ".$time."\n";
315                                                         }
316                                                         logger($o, LOGGER_DEBUG);
317                                                 }
318                                         }
319
320
321                                         if ($r===false) {
322                                                 // api function returned false withour throw an
323                                                 // exception. This should not happend, throw a 500
324                                                 throw new InternalServerErrorException();
325                                         }
326
327                                         switch($type){
328                                                 case "xml":
329                                                         header ("Content-Type: text/xml");
330                                                         return $r;
331                                                         break;
332                                                 case "json":
333                                                         header ("Content-Type: application/json");
334                                                         foreach($r as $rr)
335                                                                 $json = json_encode($rr);
336                                                                 if ($_GET['callback'])
337                                                                         $json = $_GET['callback']."(".$json.")";
338                                                                 return $json;
339                                                         break;
340                                                 case "rss":
341                                                         header ("Content-Type: application/rss+xml");
342                                                         return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
343                                                         break;
344                                                 case "atom":
345                                                         header ("Content-Type: application/atom+xml");
346                                                         return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
347                                                         break;
348
349                                         }
350                                 }
351                         }
352                         throw new NotImplementedException();
353                 } catch (HTTPException $e) {
354                         header("HTTP/1.1 {$e->httpcode} {$e->httpdesc}");
355                         return api_error($type, $e);
356                 }
357         }
358
359         /**
360          * @brief Format API error string
361          *
362          * @param string $type Return type (xml, json, rss, as)
363          * @param HTTPException $error Error object
364          * @return strin error message formatted as $type
365          */
366         function api_error($type, $e) {
367
368                 $a = get_app();
369
370                 $error = ($e->getMessage()!==""?$e->getMessage():$e->httpdesc);
371                 # TODO:  https://dev.twitter.com/overview/api/response-codes
372
373                 $error = array("error" => $error,
374                                 "code" => $e->httpcode." ".$e->httpdesc,
375                                 "request" => $a->query_string);
376
377                 $ret = api_format_data('status', $type, array('status' => $error));
378
379                 switch($type){
380                         case "xml":
381                                 header ("Content-Type: text/xml");
382                                 return $ret;
383                                 break;
384                         case "json":
385                                 header ("Content-Type: application/json");
386                                 return json_encode($ret);
387                                 break;
388                         case "rss":
389                                 header ("Content-Type: application/rss+xml");
390                                 return $ret;
391                                 break;
392                         case "atom":
393                                 header ("Content-Type: application/atom+xml");
394                                 return $ret;
395                                 break;
396                 }
397         }
398
399         /**
400          * @brief Set values for RSS template
401          *
402          * @param App $a
403          * @param array $arr Array to be passed to template
404          * @param array $user_info
405          * @return array
406          */
407         function api_rss_extra(App $a, $arr, $user_info){
408                 if (is_null($user_info)) $user_info = api_get_user($a);
409                 $arr['$user'] = $user_info;
410                 $arr['$rss'] = array(
411                         'alternate'    => $user_info['url'],
412                         'self'         => App::get_baseurl(). "/". $a->query_string,
413                         'base'         => App::get_baseurl(),
414                         'updated'      => api_date(null),
415                         'atom_updated' => datetime_convert('UTC','UTC','now',ATOM_TIME),
416                         'language'     => $user_info['language'],
417                         'logo'         => App::get_baseurl()."/images/friendica-32.png",
418                 );
419
420                 return $arr;
421         }
422
423
424         /**
425          * @brief Unique contact to contact url.
426          *
427          * @param int $id Contact id
428          * @return bool|string
429          *              Contact url or False if contact id is unknown
430          */
431         function api_unique_id_to_url($id){
432                 $r = q("SELECT `url` FROM `contact` WHERE `uid` = 0 AND `id` = %d LIMIT 1",
433                         intval($id));
434                 if ($r)
435                         return ($r[0]["url"]);
436                 else
437                         return false;
438         }
439
440         /**
441          * @brief Get user info array.
442          *
443          * @param Api $a
444          * @param int|string $contact_id Contact ID or URL
445          * @param string $type Return type (for errors)
446          */
447         function api_get_user(App $a, $contact_id = Null, $type = "json"){
448                 global $called_api;
449                 $user = null;
450                 $extra_query = "";
451                 $url = "";
452                 $nick = "";
453
454                 logger("api_get_user: Fetching user data for user ".$contact_id, LOGGER_DEBUG);
455
456                 // Searching for contact URL
457                 if(!is_null($contact_id) AND (intval($contact_id) == 0)){
458                         $user = dbesc(normalise_link($contact_id));
459                         $url = $user;
460                         $extra_query = "AND `contact`.`nurl` = '%s' ";
461                         if (api_user()!==false)  $extra_query .= "AND `contact`.`uid`=".intval(api_user());
462                 }
463
464                 // Searching for contact id with uid = 0
465                 if(!is_null($contact_id) AND (intval($contact_id) != 0)){
466                         $user = dbesc(api_unique_id_to_url($contact_id));
467
468                         if ($user == "")
469                                 throw new BadRequestException("User not found.");
470
471                         $url = $user;
472                         $extra_query = "AND `contact`.`nurl` = '%s' ";
473                         if (api_user()!==false)  $extra_query .= "AND `contact`.`uid`=".intval(api_user());
474                 }
475
476                 if(is_null($user) && x($_GET, 'user_id')) {
477                         $user = dbesc(api_unique_id_to_url($_GET['user_id']));
478
479                         if ($user == "")
480                                 throw new BadRequestException("User not found.");
481
482                         $url = $user;
483                         $extra_query = "AND `contact`.`nurl` = '%s' ";
484                         if (api_user()!==false)  $extra_query .= "AND `contact`.`uid`=".intval(api_user());
485                 }
486                 if(is_null($user) && x($_GET, 'screen_name')) {
487                         $user = dbesc($_GET['screen_name']);
488                         $nick = $user;
489                         $extra_query = "AND `contact`.`nick` = '%s' ";
490                         if (api_user()!==false)  $extra_query .= "AND `contact`.`uid`=".intval(api_user());
491                 }
492
493                 if (is_null($user) AND ($a->argc > (count($called_api)-1)) AND (count($called_api) > 0)){
494                         $argid = count($called_api);
495                         list($user, $null) = explode(".",$a->argv[$argid]);
496                         if(is_numeric($user)){
497                                 $user = dbesc(api_unique_id_to_url($user));
498
499                                 if ($user == "")
500                                         return false;
501
502                                 $url = $user;
503                                 $extra_query = "AND `contact`.`nurl` = '%s' ";
504                                 if (api_user()!==false)  $extra_query .= "AND `contact`.`uid`=".intval(api_user());
505                         } else {
506                                 $user = dbesc($user);
507                                 $nick = $user;
508                                 $extra_query = "AND `contact`.`nick` = '%s' ";
509                                 if (api_user()!==false)  $extra_query .= "AND `contact`.`uid`=".intval(api_user());
510                         }
511                 }
512
513                 logger("api_get_user: user ".$user, LOGGER_DEBUG);
514
515                 if (!$user) {
516                         if (api_user()===false) {
517                                 api_login($a);
518                                 return False;
519                         } else {
520                                 $user = $_SESSION['uid'];
521                                 $extra_query = "AND `contact`.`uid` = %d AND `contact`.`self` ";
522                         }
523
524                 }
525
526                 logger('api_user: ' . $extra_query . ', user: ' . $user);
527                 // user info
528                 $uinfo = q("SELECT *, `contact`.`id` as `cid` FROM `contact`
529                                 WHERE 1
530                                 $extra_query",
531                                 $user
532                 );
533
534                 // Selecting the id by priority, friendica first
535                 api_best_nickname($uinfo);
536
537                 // if the contact wasn't found, fetch it from the contacts with uid = 0
538                 if (count($uinfo)==0) {
539                         $r = array();
540
541                         if ($url != "")
542                                 $r = q("SELECT * FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s' LIMIT 1", dbesc(normalise_link($url)));
543
544                         if ($r) {
545                                 $network_name = network_to_name($r[0]['network'], $r[0]['url']);
546
547                                 // If no nick where given, extract it from the address
548                                 if (($r[0]['nick'] == "") OR ($r[0]['name'] == $r[0]['nick']))
549                                         $r[0]['nick'] = api_get_nick($r[0]["url"]);
550
551                                 $ret = array(
552                                         'id' => $r[0]["id"],
553                                         'id_str' => (string) $r[0]["id"],
554                                         'name' => $r[0]["name"],
555                                         'screen_name' => (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']),
556                                         'location' => ($r[0]["location"] != "") ? $r[0]["location"] : $network_name,
557                                         'description' => $r[0]["about"],
558                                         'profile_image_url' => $r[0]["micro"],
559                                         'profile_image_url_https' => $r[0]["micro"],
560                                         'url' => $r[0]["url"],
561                                         'protected' => false,
562                                         'followers_count' => 0,
563                                         'friends_count' => 0,
564                                         'listed_count' => 0,
565                                         'created_at' => api_date($r[0]["created"]),
566                                         'favourites_count' => 0,
567                                         'utc_offset' => 0,
568                                         'time_zone' => 'UTC',
569                                         'geo_enabled' => false,
570                                         'verified' => false,
571                                         'statuses_count' => 0,
572                                         'lang' => '',
573                                         'contributors_enabled' => false,
574                                         'is_translator' => false,
575                                         'is_translation_enabled' => false,
576                                         'following' => false,
577                                         'follow_request_sent' => false,
578                                         'statusnet_blocking' => false,
579                                         'notifications' => false,
580                                         'statusnet_profile_url' => $r[0]["url"],
581                                         'uid' => 0,
582                                         'cid' => get_contact($r[0]["url"], api_user(), true),
583                                         'self' => 0,
584                                         'network' => $r[0]["network"],
585                                 );
586
587                                 return $ret;
588                         } else {
589                                 throw new BadRequestException("User not found.");
590                         }
591                 }
592
593                 if($uinfo[0]['self']) {
594
595                         if ($uinfo[0]['network'] == "")
596                                 $uinfo[0]['network'] = NETWORK_DFRN;
597
598                         $usr = q("select * from user where uid = %d limit 1",
599                                 intval(api_user())
600                         );
601                         $profile = q("select * from profile where uid = %d and `is-default` = 1 limit 1",
602                                 intval(api_user())
603                         );
604
605                         // Counting is deactivated by now, due to performance issues
606                         // count public wall messages
607                         //$r = q("SELECT COUNT(*) as `count` FROM `item` WHERE `uid` = %d AND `wall`",
608                         //              intval($uinfo[0]['uid'])
609                         //);
610                         //$countitms = $r[0]['count'];
611                         $countitms = 0;
612                 } else {
613                         // Counting is deactivated by now, due to performance issues
614                         //$r = q("SELECT count(*) as `count` FROM `item`
615                         //              WHERE  `contact-id` = %d",
616                         //              intval($uinfo[0]['id'])
617                         //);
618                         //$countitms = $r[0]['count'];
619                         $countitms = 0;
620                 }
621 /*
622                 // Counting is deactivated by now, due to performance issues
623                 // count friends
624                 $r = q("SELECT count(*) as `count` FROM `contact`
625                                 WHERE  `uid` = %d AND `rel` IN ( %d, %d )
626                                 AND `self`=0 AND NOT `blocked` AND `hidden`=0",
627                                 intval($uinfo[0]['uid']),
628                                 intval(CONTACT_IS_SHARING),
629                                 intval(CONTACT_IS_FRIEND)
630                 );
631                 $countfriends = $r[0]['count'];
632
633                 $r = q("SELECT count(*) as `count` FROM `contact`
634                                 WHERE  `uid` = %d AND `rel` IN ( %d, %d )
635                                 AND `self`=0 AND NOT `blocked` AND `hidden`=0",
636                                 intval($uinfo[0]['uid']),
637                                 intval(CONTACT_IS_FOLLOWER),
638                                 intval(CONTACT_IS_FRIEND)
639                 );
640                 $countfollowers = $r[0]['count'];
641
642                 $r = q("SELECT count(*) as `count` FROM item where starred = 1 and uid = %d and deleted = 0",
643                         intval($uinfo[0]['uid'])
644                 );
645                 $starred = $r[0]['count'];
646
647
648                 if(! $uinfo[0]['self']) {
649                         $countfriends = 0;
650                         $countfollowers = 0;
651                         $starred = 0;
652                 }
653 */
654                 $countfriends = 0;
655                 $countfollowers = 0;
656                 $starred = 0;
657
658                 // Add a nick if it isn't present there
659                 if (($uinfo[0]['nick'] == "") OR ($uinfo[0]['name'] == $uinfo[0]['nick'])) {
660                         $uinfo[0]['nick'] = api_get_nick($uinfo[0]["url"]);
661                 }
662
663                 $network_name = network_to_name($uinfo[0]['network'], $uinfo[0]['url']);
664
665                 $pcontact_id  = get_contact($uinfo[0]['url'], 0, true);
666
667                 $ret = Array(
668                         'id' => intval($pcontact_id),
669                         'id_str' => (string) intval($pcontact_id),
670                         'name' => (($uinfo[0]['name']) ? $uinfo[0]['name'] : $uinfo[0]['nick']),
671                         'screen_name' => (($uinfo[0]['nick']) ? $uinfo[0]['nick'] : $uinfo[0]['name']),
672                         'location' => ($usr) ? $usr[0]['default-location'] : $network_name,
673                         'description' => (($profile) ? $profile[0]['pdesc'] : NULL),
674                         'profile_image_url' => $uinfo[0]['micro'],
675                         'profile_image_url_https' => $uinfo[0]['micro'],
676                         'url' => $uinfo[0]['url'],
677                         'protected' => false,
678                         'followers_count' => intval($countfollowers),
679                         'friends_count' => intval($countfriends),
680                         'listed_count' => 0,
681                         'created_at' => api_date($uinfo[0]['created']),
682                         'favourites_count' => intval($starred),
683                         'utc_offset' => "0",
684                         'time_zone' => 'UTC',
685                         'geo_enabled' => false,
686                         'verified' => true,
687                         'statuses_count' => intval($countitms),
688                         'lang' => '',
689                         'contributors_enabled' => false,
690                         'is_translator' => false,
691                         'is_translation_enabled' => false,
692                         'following' => (($uinfo[0]['rel'] == CONTACT_IS_FOLLOWER) OR ($uinfo[0]['rel'] == CONTACT_IS_FRIEND)),
693                         'follow_request_sent' => false,
694                         'statusnet_blocking' => false,
695                         'notifications' => false,
696                         //'statusnet_profile_url' => App::get_baseurl()."/contacts/".$uinfo[0]['cid'],
697                         'statusnet_profile_url' => $uinfo[0]['url'],
698                         'uid' => intval($uinfo[0]['uid']),
699                         'cid' => intval($uinfo[0]['cid']),
700                         'self' => $uinfo[0]['self'],
701                         'network' => $uinfo[0]['network'],
702                 );
703
704                 return $ret;
705
706         }
707
708         /**
709          * @brief return api-formatted array for item's author and owner
710          *
711          * @param App $a
712          * @param array $item : item from db
713          * @return array(array:author, array:owner)
714          */
715         function api_item_get_user(App $a, $item) {
716
717                 $status_user = api_get_user($a, $item["author-link"]);
718
719                 $status_user["protected"] = (($item["allow_cid"] != "") OR
720                                                 ($item["allow_gid"] != "") OR
721                                                 ($item["deny_cid"] != "") OR
722                                                 ($item["deny_gid"] != "") OR
723                                                 $item["private"]);
724
725                 $owner_user = api_get_user($a, $item["owner-link"]);
726
727                 return (array($status_user, $owner_user));
728         }
729
730         /**
731          * @brief walks recursively through an array with the possibility to change value and key
732          *
733          * @param array $array The array to walk through
734          * @param string $callback The callback function
735          *
736          * @return array the transformed array
737          */
738         function api_walk_recursive(array &$array, callable $callback) {
739
740                 $new_array = array();
741
742                 foreach ($array as $k => $v) {
743                         if (is_array($v)) {
744                                 if ($callback($v, $k))
745                                         $new_array[$k] = api_walk_recursive($v, $callback);
746                         } else {
747                                 if ($callback($v, $k))
748                                         $new_array[$k] = $v;
749                         }
750                 }
751                 $array = $new_array;
752
753                 return $array;
754         }
755
756         /**
757          * @brief Callback function to transform the array in an array that can be transformed in a XML file
758          *
759          * @param variant $item Array item value
760          * @param string $key Array key
761          *
762          * @return boolean Should the array item be deleted?
763          */
764         function api_reformat_xml(&$item, &$key) {
765                 if (is_bool($item))
766                         $item = ($item ? "true" : "false");
767
768                 if (substr($key, 0, 10) == "statusnet_")
769                         $key = "statusnet:".substr($key, 10);
770                 elseif (substr($key, 0, 10) == "friendica_")
771                         $key = "friendica:".substr($key, 10);
772                 //else
773                 //      $key = "default:".$key;
774
775                 return true;
776         }
777
778         /**
779          * @brief Creates the XML from a JSON style array
780          *
781          * @param array $data JSON style array
782          * @param string $root_element Name of the root element
783          *
784          * @return string The XML data
785          */
786         function api_create_xml($data, $root_element) {
787                 $childname = key($data);
788                 $data2 = array_pop($data);
789                 $key = key($data2);
790
791                 $namespaces = array("" => "http://api.twitter.com",
792                                         "statusnet" => "http://status.net/schema/api/1/",
793                                         "friendica" => "http://friendi.ca/schema/api/1/",
794                                         "georss" => "http://www.georss.org/georss");
795
796                 /// @todo Auto detection of needed namespaces
797                 if (in_array($root_element, array("ok", "hash", "config", "version", "ids", "notes", "photos")))
798                         $namespaces = array();
799
800                 if (is_array($data2))
801                         api_walk_recursive($data2, "api_reformat_xml");
802
803                 if ($key == "0") {
804                         $data4 = array();
805                         $i = 1;
806
807                         foreach ($data2 AS $item)
808                                 $data4[$i++.":".$childname] = $item;
809
810                         $data2 = $data4;
811                 }
812
813                 $data3 = array($root_element => $data2);
814
815                 $ret = xml::from_array($data3, $xml, false, $namespaces);
816                 return $ret;
817         }
818
819         /**
820          * @brief Formats the data according to the data type
821          *
822          * @param string $root_element Name of the root element
823          * @param string $type Return type (atom, rss, xml, json)
824          * @param array $data JSON style array
825          *
826          * @return (string|object) XML data or JSON data
827          */
828         function api_format_data($root_element, $type, $data){
829
830                 $a = get_app();
831
832                 switch($type){
833                         case "atom":
834                         case "rss":
835                         case "xml":
836                                 $ret = api_create_xml($data, $root_element);
837                                 break;
838                         case "json":
839                                 $ret = $data;
840                                 break;
841                 }
842
843                 return $ret;
844         }
845
846         /**
847          ** TWITTER API
848          */
849
850         /**
851          * Returns an HTTP 200 OK response code and a representation of the requesting user if authentication was successful;
852          * returns a 401 status code and an error message if not.
853          * http://developer.twitter.com/doc/get/account/verify_credentials
854          */
855         function api_account_verify_credentials($type){
856
857                 $a = get_app();
858
859                 if (api_user()===false) throw new ForbiddenException();
860
861                 unset($_REQUEST["user_id"]);
862                 unset($_GET["user_id"]);
863
864                 unset($_REQUEST["screen_name"]);
865                 unset($_GET["screen_name"]);
866
867                 $skip_status = (x($_REQUEST,'skip_status')?$_REQUEST['skip_status']:false);
868
869                 $user_info = api_get_user($a);
870
871                 // "verified" isn't used here in the standard
872                 unset($user_info["verified"]);
873
874                 // - Adding last status
875                 if (!$skip_status) {
876                         $user_info["status"] = api_status_show("raw");
877                         if (!count($user_info["status"]))
878                                 unset($user_info["status"]);
879                         else
880                                 unset($user_info["status"]["user"]);
881                 }
882
883                 // "uid" and "self" are only needed for some internal stuff, so remove it from here
884                 unset($user_info["uid"]);
885                 unset($user_info["self"]);
886
887                 return api_format_data("user", $type, array('user' => $user_info));
888
889         }
890         api_register_func('api/account/verify_credentials','api_account_verify_credentials', true);
891
892
893         /**
894          * get data from $_POST or $_GET
895          */
896         function requestdata($k){
897                 if (isset($_POST[$k])){
898                         return $_POST[$k];
899                 }
900                 if (isset($_GET[$k])){
901                         return $_GET[$k];
902                 }
903                 return null;
904         }
905
906 /*Waitman Gobble Mod*/
907         function api_statuses_mediap($type) {
908
909                 $a = get_app();
910
911                 if (api_user()===false) {
912                         logger('api_statuses_update: no user');
913                         throw new ForbiddenException();
914                 }
915                 $user_info = api_get_user($a);
916
917                 $_REQUEST['type'] = 'wall';
918                 $_REQUEST['profile_uid'] = api_user();
919                 $_REQUEST['api_source'] = true;
920                 $txt = requestdata('status');
921                 //$txt = urldecode(requestdata('status'));
922
923                 if((strpos($txt,'<') !== false) || (strpos($txt,'>') !== false)) {
924
925                         $txt = html2bb_video($txt);
926                         $config = HTMLPurifier_Config::createDefault();
927                         $config->set('Cache.DefinitionImpl', null);
928                         $purifier = new HTMLPurifier($config);
929                         $txt = $purifier->purify($txt);
930                 }
931                 $txt = html2bbcode($txt);
932
933                 $a->argv[1]=$user_info['screen_name']; //should be set to username?
934
935                 $_REQUEST['hush']='yeah'; //tell wall_upload function to return img info instead of echo
936                 $bebop = wall_upload_post($a);
937
938                 //now that we have the img url in bbcode we can add it to the status and insert the wall item.
939                 $_REQUEST['body']=$txt."\n\n".$bebop;
940                 item_post($a);
941
942                 // this should output the last post (the one we just posted).
943                 return api_status_show($type);
944         }
945         api_register_func('api/statuses/mediap','api_statuses_mediap', true, API_METHOD_POST);
946 /*Waitman Gobble Mod*/
947
948
949         function api_statuses_update($type) {
950
951                 $a = get_app();
952
953                 if (api_user()===false) {
954                         logger('api_statuses_update: no user');
955                         throw new ForbiddenException();
956                 }
957
958                 $user_info = api_get_user($a);
959
960                 // convert $_POST array items to the form we use for web posts.
961
962                 // logger('api_post: ' . print_r($_POST,true));
963
964                 if(requestdata('htmlstatus')) {
965                         $txt = requestdata('htmlstatus');
966                         if((strpos($txt,'<') !== false) || (strpos($txt,'>') !== false)) {
967                                 $txt = html2bb_video($txt);
968
969                                 $config = HTMLPurifier_Config::createDefault();
970                                 $config->set('Cache.DefinitionImpl', null);
971
972                                 $purifier = new HTMLPurifier($config);
973                                 $txt = $purifier->purify($txt);
974
975                                 $_REQUEST['body'] = html2bbcode($txt);
976                         }
977
978                 } else
979                         $_REQUEST['body'] = requestdata('status');
980
981                 $_REQUEST['title'] = requestdata('title');
982
983                 $parent = requestdata('in_reply_to_status_id');
984
985                 // Twidere sends "-1" if it is no reply ...
986                 if ($parent == -1)
987                         $parent = "";
988
989                 if(ctype_digit($parent))
990                         $_REQUEST['parent'] = $parent;
991                 else
992                         $_REQUEST['parent_uri'] = $parent;
993
994                 if(requestdata('lat') && requestdata('long'))
995                         $_REQUEST['coord'] = sprintf("%s %s",requestdata('lat'),requestdata('long'));
996                 $_REQUEST['profile_uid'] = api_user();
997
998                 if($parent)
999                         $_REQUEST['type'] = 'net-comment';
1000                 else {
1001                         // Check for throttling (maximum posts per day, week and month)
1002                         $throttle_day = get_config('system','throttle_limit_day');
1003                         if ($throttle_day > 0) {
1004                                 $datefrom = date("Y-m-d H:i:s", time() - 24*60*60);
1005
1006                                 $r = q("SELECT COUNT(*) AS `posts_day` FROM `item` WHERE `uid`=%d AND `wall`
1007                                         AND `created` > '%s' AND `id` = `parent`",
1008                                         intval(api_user()), dbesc($datefrom));
1009
1010                                 if ($r)
1011                                         $posts_day = $r[0]["posts_day"];
1012                                 else
1013                                         $posts_day = 0;
1014
1015                                 if ($posts_day > $throttle_day) {
1016                                         logger('Daily posting limit reached for user '.api_user(), LOGGER_DEBUG);
1017                                         #die(api_error($type, sprintf(t("Daily posting limit of %d posts reached. The post was rejected."), $throttle_day)));
1018                                         throw new TooManyRequestsException(sprintf(t("Daily posting limit of %d posts reached. The post was rejected."), $throttle_day));
1019                                 }
1020                         }
1021
1022                         $throttle_week = get_config('system','throttle_limit_week');
1023                         if ($throttle_week > 0) {
1024                                 $datefrom = date("Y-m-d H:i:s", time() - 24*60*60*7);
1025
1026                                 $r = q("SELECT COUNT(*) AS `posts_week` FROM `item` WHERE `uid`=%d AND `wall`
1027                                         AND `created` > '%s' AND `id` = `parent`",
1028                                         intval(api_user()), dbesc($datefrom));
1029
1030                                 if ($r)
1031                                         $posts_week = $r[0]["posts_week"];
1032                                 else
1033                                         $posts_week = 0;
1034
1035                                 if ($posts_week > $throttle_week) {
1036                                         logger('Weekly posting limit reached for user '.api_user(), LOGGER_DEBUG);
1037                                         #die(api_error($type, sprintf(t("Weekly posting limit of %d posts reached. The post was rejected."), $throttle_week)));
1038                                         throw new TooManyRequestsException(sprintf(t("Weekly posting limit of %d posts reached. The post was rejected."), $throttle_week));
1039
1040                                 }
1041                         }
1042
1043                         $throttle_month = get_config('system','throttle_limit_month');
1044                         if ($throttle_month > 0) {
1045                                 $datefrom = date("Y-m-d H:i:s", time() - 24*60*60*30);
1046
1047                                 $r = q("SELECT COUNT(*) AS `posts_month` FROM `item` WHERE `uid`=%d AND `wall`
1048                                         AND `created` > '%s' AND `id` = `parent`",
1049                                         intval(api_user()), dbesc($datefrom));
1050
1051                                 if ($r)
1052                                         $posts_month = $r[0]["posts_month"];
1053                                 else
1054                                         $posts_month = 0;
1055
1056                                 if ($posts_month > $throttle_month) {
1057                                         logger('Monthly posting limit reached for user '.api_user(), LOGGER_DEBUG);
1058                                         #die(api_error($type, sprintf(t("Monthly posting limit of %d posts reached. The post was rejected."), $throttle_month)));
1059                                         throw new TooManyRequestsException(sprintf(t("Monthly posting limit of %d posts reached. The post was rejected."), $throttle_month));
1060                                 }
1061                         }
1062
1063                         $_REQUEST['type'] = 'wall';
1064                 }
1065
1066                 if(x($_FILES,'media')) {
1067                         // upload the image if we have one
1068                         $_REQUEST['hush']='yeah'; //tell wall_upload function to return img info instead of echo
1069                         $media = wall_upload_post($a);
1070                         if(strlen($media)>0)
1071                                 $_REQUEST['body'] .= "\n\n".$media;
1072                 }
1073
1074                 // To-Do: Multiple IDs
1075                 if (requestdata('media_ids')) {
1076                         $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",
1077                                 intval(requestdata('media_ids')), api_user());
1078                         if ($r) {
1079                                 $phototypes = Photo::supportedTypes();
1080                                 $ext = $phototypes[$r[0]['type']];
1081                                 $_REQUEST['body'] .= "\n\n".'[url='.App::get_baseurl().'/photos/'.$r[0]['nickname'].'/image/'.$r[0]['resource-id'].']';
1082                                 $_REQUEST['body'] .= '[img]'.App::get_baseurl()."/photo/".$r[0]['resource-id']."-".$r[0]['scale'].".".$ext."[/img][/url]";
1083                         }
1084                 }
1085
1086                 // set this so that the item_post() function is quiet and doesn't redirect or emit json
1087
1088                 $_REQUEST['api_source'] = true;
1089
1090                 if (!x($_REQUEST, "source"))
1091                         $_REQUEST["source"] = api_source();
1092
1093                 // call out normal post function
1094
1095                 item_post($a);
1096
1097                 // this should output the last post (the one we just posted).
1098                 return api_status_show($type);
1099         }
1100         api_register_func('api/statuses/update','api_statuses_update', true, API_METHOD_POST);
1101         api_register_func('api/statuses/update_with_media','api_statuses_update', true, API_METHOD_POST);
1102
1103
1104         function api_media_upload($type) {
1105
1106                 $a = get_app();
1107
1108                 if (api_user()===false) {
1109                         logger('no user');
1110                         throw new ForbiddenException();
1111                 }
1112
1113                 $user_info = api_get_user($a);
1114
1115                 if(!x($_FILES,'media')) {
1116                         // Output error
1117                         throw new BadRequestException("No media.");
1118                 }
1119
1120                 $media = wall_upload_post($a, false);
1121                 if(!$media) {
1122                         // Output error
1123                         throw new InternalServerErrorException();
1124                 }
1125
1126                 $returndata = array();
1127                 $returndata["media_id"] = $media["id"];
1128                 $returndata["media_id_string"] = (string)$media["id"];
1129                 $returndata["size"] = $media["size"];
1130                 $returndata["image"] = array("w" => $media["width"],
1131                                                 "h" => $media["height"],
1132                                                 "image_type" => $media["type"]);
1133
1134                 logger("Media uploaded: ".print_r($returndata, true), LOGGER_DEBUG);
1135
1136                 return array("media" => $returndata);
1137         }
1138         api_register_func('api/media/upload','api_media_upload', true, API_METHOD_POST);
1139
1140         function api_status_show($type){
1141
1142                 $a = get_app();
1143
1144                 $user_info = api_get_user($a);
1145
1146                 logger('api_status_show: user_info: '.print_r($user_info, true), LOGGER_DEBUG);
1147
1148                 if ($type == "raw")
1149                         $privacy_sql = "AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''";
1150                 else
1151                         $privacy_sql = "";
1152
1153                 // get last public wall message
1154                 $lastwall = q("SELECT `item`.*
1155                                 FROM `item`
1156                                 WHERE `item`.`contact-id` = %d AND `item`.`uid` = %d
1157                                         AND ((`item`.`author-link` IN ('%s', '%s')) OR (`item`.`owner-link` IN ('%s', '%s')))
1158                                         AND `item`.`type` != 'activity' $privacy_sql
1159                                 ORDER BY `item`.`id` DESC
1160                                 LIMIT 1",
1161                                 intval($user_info['cid']),
1162                                 intval(api_user()),
1163                                 dbesc($user_info['url']),
1164                                 dbesc(normalise_link($user_info['url'])),
1165                                 dbesc($user_info['url']),
1166                                 dbesc(normalise_link($user_info['url']))
1167                 );
1168
1169                 if (count($lastwall)>0){
1170                         $lastwall = $lastwall[0];
1171
1172                         $in_reply_to = api_in_reply_to($lastwall);
1173
1174                         $converted = api_convert_item($lastwall);
1175
1176                         if ($type == "xml")
1177                                 $geo = "georss:point";
1178                         else
1179                                 $geo = "geo";
1180
1181                         $status_info = array(
1182                                 'created_at' => api_date($lastwall['created']),
1183                                 'id' => intval($lastwall['id']),
1184                                 'id_str' => (string) $lastwall['id'],
1185                                 'text' => $converted["text"],
1186                                 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
1187                                 'truncated' => false,
1188                                 'in_reply_to_status_id' => $in_reply_to['status_id'],
1189                                 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
1190                                 'in_reply_to_user_id' => $in_reply_to['user_id'],
1191                                 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
1192                                 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
1193                                 'user' => $user_info,
1194                                 $geo => NULL,
1195                                 'coordinates' => "",
1196                                 'place' => "",
1197                                 'contributors' => "",
1198                                 'is_quote_status' => false,
1199                                 'retweet_count' => 0,
1200                                 'favorite_count' => 0,
1201                                 'favorited' => $lastwall['starred'] ? true : false,
1202                                 'retweeted' => false,
1203                                 'possibly_sensitive' => false,
1204                                 'lang' => "",
1205                                 'statusnet_html'                => $converted["html"],
1206                                 'statusnet_conversation_id'     => $lastwall['parent'],
1207                         );
1208
1209                         if (count($converted["attachments"]) > 0)
1210                                 $status_info["attachments"] = $converted["attachments"];
1211
1212                         if (count($converted["entities"]) > 0)
1213                                 $status_info["entities"] = $converted["entities"];
1214
1215                         if (($lastwall['item_network'] != "") AND ($status["source"] == 'web'))
1216                                 $status_info["source"] = network_to_name($lastwall['item_network'], $user_info['url']);
1217                         elseif (($lastwall['item_network'] != "") AND (network_to_name($lastwall['item_network'], $user_info['url']) != $status_info["source"]))
1218                                 $status_info["source"] = trim($status_info["source"].' ('.network_to_name($lastwall['item_network'], $user_info['url']).')');
1219
1220                         // "uid" and "self" are only needed for some internal stuff, so remove it from here
1221                         unset($status_info["user"]["uid"]);
1222                         unset($status_info["user"]["self"]);
1223                 }
1224
1225                 logger('status_info: '.print_r($status_info, true), LOGGER_DEBUG);
1226
1227                 if ($type == "raw")
1228                         return($status_info);
1229
1230                 return  api_format_data("statuses", $type, array('status' => $status_info));
1231
1232         }
1233
1234
1235
1236
1237
1238         /**
1239          * Returns extended information of a given user, specified by ID or screen name as per the required id parameter.
1240          * The author's most recent status will be returned inline.
1241          * http://developer.twitter.com/doc/get/users/show
1242          */
1243         function api_users_show($type){
1244
1245                 $a = get_app();
1246
1247                 $user_info = api_get_user($a);
1248                 $lastwall = q("SELECT `item`.*
1249                                 FROM `item`
1250                                 INNER JOIN `contact` ON `contact`.`id`=`item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1251                                 WHERE `item`.`uid` = %d AND `verb` = '%s' AND `item`.`contact-id` = %d
1252                                         AND ((`item`.`author-link` IN ('%s', '%s')) OR (`item`.`owner-link` IN ('%s', '%s')))
1253                                         AND `type`!='activity'
1254                                         AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''
1255                                 ORDER BY `id` DESC
1256                                 LIMIT 1",
1257                                 intval(api_user()),
1258                                 dbesc(ACTIVITY_POST),
1259                                 intval($user_info['cid']),
1260                                 dbesc($user_info['url']),
1261                                 dbesc(normalise_link($user_info['url'])),
1262                                 dbesc($user_info['url']),
1263                                 dbesc(normalise_link($user_info['url']))
1264                 );
1265
1266                 if (count($lastwall)>0){
1267                         $lastwall = $lastwall[0];
1268
1269                         $in_reply_to = api_in_reply_to($lastwall);
1270
1271                         $converted = api_convert_item($lastwall);
1272
1273                         if ($type == "xml")
1274                                 $geo = "georss:point";
1275                         else
1276                                 $geo = "geo";
1277
1278                         $user_info['status'] = array(
1279                                 'text' => $converted["text"],
1280                                 'truncated' => false,
1281                                 'created_at' => api_date($lastwall['created']),
1282                                 'in_reply_to_status_id' => $in_reply_to['status_id'],
1283                                 'in_reply_to_status_id_str' => $in_reply_to['status_id_str'],
1284                                 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
1285                                 'id' => intval($lastwall['contact-id']),
1286                                 'id_str' => (string) $lastwall['contact-id'],
1287                                 'in_reply_to_user_id' => $in_reply_to['user_id'],
1288                                 'in_reply_to_user_id_str' => $in_reply_to['user_id_str'],
1289                                 'in_reply_to_screen_name' => $in_reply_to['screen_name'],
1290                                 $geo => NULL,
1291                                 'favorited' => $lastwall['starred'] ? true : false,
1292                                 'statusnet_html'                => $converted["html"],
1293                                 'statusnet_conversation_id'     => $lastwall['parent'],
1294                         );
1295
1296                         if (count($converted["attachments"]) > 0)
1297                                 $user_info["status"]["attachments"] = $converted["attachments"];
1298
1299                         if (count($converted["entities"]) > 0)
1300                                 $user_info["status"]["entities"] = $converted["entities"];
1301
1302                         if (($lastwall['item_network'] != "") AND ($user_info["status"]["source"] == 'web'))
1303                                 $user_info["status"]["source"] = network_to_name($lastwall['item_network'], $user_info['url']);
1304                         if (($lastwall['item_network'] != "") AND (network_to_name($lastwall['item_network'], $user_info['url']) != $user_info["status"]["source"]))
1305                                 $user_info["status"]["source"] = trim($user_info["status"]["source"].' ('.network_to_name($lastwall['item_network'], $user_info['url']).')');
1306
1307                 }
1308
1309                 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1310                 unset($user_info["uid"]);
1311                 unset($user_info["self"]);
1312
1313                 return  api_format_data("user", $type, array('user' => $user_info));
1314
1315         }
1316         api_register_func('api/users/show','api_users_show');
1317
1318
1319         function api_users_search($type) {
1320
1321                 $a = get_app();
1322
1323                 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1324
1325                 $userlist = array();
1326
1327                 if (isset($_GET["q"])) {
1328                         $r = q("SELECT id FROM `contact` WHERE `uid` = 0 AND `name` = '%s'", dbesc($_GET["q"]));
1329                         if (!dbm::is_result($r))
1330                                 $r = q("SELECT `id` FROM `contact` WHERE `uid` = 0 AND `nick` = '%s'", dbesc($_GET["q"]));
1331
1332                         if (dbm::is_result($r)) {
1333                                 $k = 0;
1334                                 foreach ($r AS $user) {
1335                                         $user_info = api_get_user($a, $user["id"], "json");
1336
1337                                         if ($type == "xml")
1338                                                 $userlist[$k++.":user"] = $user_info;
1339                                         else
1340                                                 $userlist[] = $user_info;
1341                                 }
1342                                 $userlist = array("users" => $userlist);
1343                         } else {
1344                                 throw new BadRequestException("User not found.");
1345                         }
1346                 } else {
1347                         throw new BadRequestException("User not found.");
1348                 }
1349                 return api_format_data("users", $type, $userlist);
1350         }
1351
1352         api_register_func('api/users/search','api_users_search');
1353
1354         /**
1355          *
1356          * http://developer.twitter.com/doc/get/statuses/home_timeline
1357          *
1358          * TODO: Optional parameters
1359          * TODO: Add reply info
1360          */
1361         function api_statuses_home_timeline($type){
1362
1363                 $a = get_app();
1364
1365                 if (api_user()===false) throw new ForbiddenException();
1366
1367                 unset($_REQUEST["user_id"]);
1368                 unset($_GET["user_id"]);
1369
1370                 unset($_REQUEST["screen_name"]);
1371                 unset($_GET["screen_name"]);
1372
1373                 $user_info = api_get_user($a);
1374                 // get last newtork messages
1375
1376                 // params
1377                 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1378                 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1379                 if ($page<0) $page=0;
1380                 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1381                 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1382                 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1383                 $exclude_replies = (x($_REQUEST,'exclude_replies')?1:0);
1384                 $conversation_id = (x($_REQUEST,'conversation_id')?$_REQUEST['conversation_id']:0);
1385
1386                 $start = $page*$count;
1387
1388                 $sql_extra = '';
1389                 if ($max_id > 0)
1390                         $sql_extra .= ' AND `item`.`id` <= '.intval($max_id);
1391                 if ($exclude_replies > 0)
1392                         $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
1393                 if ($conversation_id > 0)
1394                         $sql_extra .= ' AND `item`.`parent` = '.intval($conversation_id);
1395
1396                 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1397                         `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1398                         `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1399                         `contact`.`id` AS `cid`
1400                         FROM `item`
1401                         STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1402                                 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
1403                         WHERE `item`.`uid` = %d AND `verb` = '%s'
1404                         AND `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
1405                         $sql_extra
1406                         AND `item`.`id`>%d
1407                         ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1408                         intval(api_user()),
1409                         dbesc(ACTIVITY_POST),
1410                         intval($since_id),
1411                         intval($start), intval($count)
1412                 );
1413
1414                 $ret = api_format_items($r,$user_info, false, $type);
1415
1416                 // Set all posts from the query above to seen
1417                 $idarray = array();
1418                 foreach ($r AS $item)
1419                         $idarray[] = intval($item["id"]);
1420
1421                 $idlist = implode(",", $idarray);
1422
1423                 if ($idlist != "") {
1424                         $unseen = q("SELECT `id` FROM `item` WHERE `unseen` AND `id` IN (%s)", $idlist);
1425
1426                         if ($unseen)
1427                                 $r = q("UPDATE `item` SET `unseen` = 0 WHERE `unseen` AND `id` IN (%s)", $idlist);
1428                 }
1429
1430                 $data = array('status' => $ret);
1431                 switch($type){
1432                         case "atom":
1433                         case "rss":
1434                                 $data = api_rss_extra($a, $data, $user_info);
1435                                 break;
1436                 }
1437
1438                 return  api_format_data("statuses", $type, $data);
1439         }
1440         api_register_func('api/statuses/home_timeline','api_statuses_home_timeline', true);
1441         api_register_func('api/statuses/friends_timeline','api_statuses_home_timeline', true);
1442
1443         function api_statuses_public_timeline($type){
1444
1445                 $a = get_app();
1446
1447                 if (api_user()===false) throw new ForbiddenException();
1448
1449                 $user_info = api_get_user($a);
1450                 // get last newtork messages
1451
1452
1453                 // params
1454                 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1455                 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1456                 if ($page<0) $page=0;
1457                 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1458                 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1459                 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1460                 $exclude_replies = (x($_REQUEST,'exclude_replies')?1:0);
1461                 $conversation_id = (x($_REQUEST,'conversation_id')?$_REQUEST['conversation_id']:0);
1462
1463                 $start = $page*$count;
1464
1465                 if ($max_id > 0)
1466                         $sql_extra = 'AND `item`.`id` <= '.intval($max_id);
1467                 if ($exclude_replies > 0)
1468                         $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
1469                 if ($conversation_id > 0)
1470                         $sql_extra .= ' AND `item`.`parent` = '.intval($conversation_id);
1471
1472                 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1473                         `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1474                         `contact`.`network`, `contact`.`thumb`, `contact`.`self`, `contact`.`writable`,
1475                         `contact`.`id` AS `cid`,
1476                         `user`.`nickname`, `user`.`hidewall`
1477                         FROM `item`
1478                         STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1479                                 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
1480                         STRAIGHT_JOIN `user` ON `user`.`uid` = `item`.`uid`
1481                                 AND NOT `user`.`hidewall`
1482                         WHERE `verb` = '%s' AND `item`.`visible` AND NOT `item`.`deleted` AND NOT `item`.`moderated`
1483                         AND `item`.`allow_cid` = ''  AND `item`.`allow_gid` = ''
1484                         AND `item`.`deny_cid`  = '' AND `item`.`deny_gid`  = ''
1485                         AND NOT `item`.`private` AND `item`.`wall`
1486                         $sql_extra
1487                         AND `item`.`id`>%d
1488                         ORDER BY `item`.`id` DESC LIMIT %d, %d ",
1489                         dbesc(ACTIVITY_POST),
1490                         intval($since_id),
1491                         intval($start),
1492                         intval($count));
1493
1494                 $ret = api_format_items($r,$user_info, false, $type);
1495
1496
1497                 $data = array('status' => $ret);
1498                 switch($type){
1499                         case "atom":
1500                         case "rss":
1501                                 $data = api_rss_extra($a, $data, $user_info);
1502                                 break;
1503                 }
1504
1505                 return  api_format_data("statuses", $type, $data);
1506         }
1507         api_register_func('api/statuses/public_timeline','api_statuses_public_timeline', true);
1508
1509         /**
1510          *
1511          */
1512         function api_statuses_show($type){
1513
1514                 $a = get_app();
1515
1516                 if (api_user()===false) throw new ForbiddenException();
1517
1518                 $user_info = api_get_user($a);
1519
1520                 // params
1521                 $id = intval($a->argv[3]);
1522
1523                 if ($id == 0)
1524                         $id = intval($_REQUEST["id"]);
1525
1526                 // Hotot workaround
1527                 if ($id == 0)
1528                         $id = intval($a->argv[4]);
1529
1530                 logger('API: api_statuses_show: '.$id);
1531
1532                 $conversation = (x($_REQUEST,'conversation')?1:0);
1533
1534                 $sql_extra = '';
1535                 if ($conversation)
1536                         $sql_extra .= " AND `item`.`parent` = %d ORDER BY `id` ASC ";
1537                 else
1538                         $sql_extra .= " AND `item`.`id` = %d";
1539
1540                 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1541                         `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1542                         `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1543                         `contact`.`id` AS `cid`
1544                         FROM `item`
1545                         INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1546                                 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
1547                         WHERE `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
1548                         AND `item`.`uid` = %d AND `item`.`verb` = '%s'
1549                         $sql_extra",
1550                         intval(api_user()),
1551                         dbesc(ACTIVITY_POST),
1552                         intval($id)
1553                 );
1554
1555                 if (!$r) {
1556                         throw new BadRequestException("There is no status with this id.");
1557                 }
1558
1559                 $ret = api_format_items($r,$user_info, false, $type);
1560
1561                 if ($conversation) {
1562                         $data = array('status' => $ret);
1563                         return api_format_data("statuses", $type, $data);
1564                 } else {
1565                         $data = array('status' => $ret[0]);
1566                         return  api_format_data("status", $type, $data);
1567                 }
1568         }
1569         api_register_func('api/statuses/show','api_statuses_show', true);
1570
1571
1572         /**
1573          *
1574          */
1575         function api_conversation_show($type){
1576
1577                 $a = get_app();
1578
1579                 if (api_user()===false) throw new ForbiddenException();
1580
1581                 $user_info = api_get_user($a);
1582
1583                 // params
1584                 $id = intval($a->argv[3]);
1585                 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1586                 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1587                 if ($page<0) $page=0;
1588                 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1589                 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1590
1591                 $start = $page*$count;
1592
1593                 if ($id == 0)
1594                         $id = intval($_REQUEST["id"]);
1595
1596                 // Hotot workaround
1597                 if ($id == 0)
1598                         $id = intval($a->argv[4]);
1599
1600                 logger('API: api_conversation_show: '.$id);
1601
1602                 $r = q("SELECT `parent` FROM `item` WHERE `id` = %d", intval($id));
1603                 if ($r)
1604                         $id = $r[0]["parent"];
1605
1606                 $sql_extra = '';
1607
1608                 if ($max_id > 0)
1609                         $sql_extra = ' AND `item`.`id` <= '.intval($max_id);
1610
1611                 // Not sure why this query was so complicated. We should keep it here for a while,
1612                 // just to make sure that we really don't need it.
1613                 //      FROM `item` INNER JOIN (SELECT `uri`,`parent` FROM `item` WHERE `id` = %d) AS `temp1`
1614                 //      ON (`item`.`thr-parent` = `temp1`.`uri` AND `item`.`parent` = `temp1`.`parent`)
1615
1616                 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1617                         `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1618                         `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1619                         `contact`.`id` AS `cid`
1620                         FROM `item`
1621                         STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1622                                 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
1623                         WHERE `item`.`parent` = %d AND `item`.`visible`
1624                         AND NOT `item`.`moderated` AND NOT `item`.`deleted`
1625                         AND `item`.`uid` = %d AND `item`.`verb` = '%s'
1626                         AND `item`.`id`>%d $sql_extra
1627                         ORDER BY `item`.`id` DESC LIMIT %d ,%d",
1628                         intval($id), intval(api_user()),
1629                         dbesc(ACTIVITY_POST),
1630                         intval($since_id),
1631                         intval($start), intval($count)
1632                 );
1633
1634                 if (!$r)
1635                         throw new BadRequestException("There is no conversation with this id.");
1636
1637                 $ret = api_format_items($r,$user_info, false, $type);
1638
1639                 $data = array('status' => $ret);
1640                 return api_format_data("statuses", $type, $data);
1641         }
1642         api_register_func('api/conversation/show','api_conversation_show', true);
1643         api_register_func('api/statusnet/conversation','api_conversation_show', true);
1644
1645
1646         /**
1647          *
1648          */
1649         function api_statuses_repeat($type){
1650                 global $called_api;
1651
1652                 $a = get_app();
1653
1654                 if (api_user()===false) throw new ForbiddenException();
1655
1656                 $user_info = api_get_user($a);
1657
1658                 // params
1659                 $id = intval($a->argv[3]);
1660
1661                 if ($id == 0)
1662                         $id = intval($_REQUEST["id"]);
1663
1664                 // Hotot workaround
1665                 if ($id == 0)
1666                         $id = intval($a->argv[4]);
1667
1668                 logger('API: api_statuses_repeat: '.$id);
1669
1670                 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`, `contact`.`nick` as `reply_author`,
1671                         `contact`.`name`, `contact`.`photo` as `reply_photo`, `contact`.`url` as `reply_url`, `contact`.`rel`,
1672                         `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1673                         `contact`.`id` AS `cid`
1674                         FROM `item`
1675                         INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id` AND `contact`.`uid` = `item`.`uid`
1676                                 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
1677                         WHERE `item`.`visible` AND NOT `item`.`moderated` AND NOT `item`.`deleted`
1678                         AND NOT `item`.`private` AND `item`.`allow_cid` = '' AND `item`.`allow`.`gid` = ''
1679                         AND `item`.`deny_cid` = '' AND `item`.`deny_gid` = ''
1680                         $sql_extra
1681                         AND `item`.`id`=%d",
1682                         intval($id)
1683                 );
1684
1685                 if ($r[0]['body'] != "") {
1686                         if (!intval(get_config('system','old_share'))) {
1687                                 if (strpos($r[0]['body'], "[/share]") !== false) {
1688                                         $pos = strpos($r[0]['body'], "[share");
1689                                         $post = substr($r[0]['body'], $pos);
1690                                 } else {
1691                                         $post = share_header($r[0]['author-name'], $r[0]['author-link'], $r[0]['author-avatar'], $r[0]['guid'], $r[0]['created'], $r[0]['plink']);
1692
1693                                         $post .= $r[0]['body'];
1694                                         $post .= "[/share]";
1695                                 }
1696                                 $_REQUEST['body'] = $post;
1697                         } else
1698                                 $_REQUEST['body'] = html_entity_decode("&#x2672; ", ENT_QUOTES, 'UTF-8')."[url=".$r[0]['reply_url']."]".$r[0]['reply_author']."[/url] \n".$r[0]['body'];
1699
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 = (($a->config['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 = (($a->config['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/statusnet/config','api_statusnet_config',false);
2725
2726         function api_statusnet_version($type) {
2727                 // liar
2728                 $fake_statusnet_version = "0.9.7";
2729
2730                 return api_format_data('version', $type, array('version' => $fake_statusnet_version));
2731         }
2732         api_register_func('api/statusnet/version','api_statusnet_version',false);
2733
2734         /**
2735          * @todo use api_format_data() to return data
2736          */
2737         function api_ff_ids($type,$qtype) {
2738
2739                 $a = get_app();
2740
2741                 if(! api_user()) throw new ForbiddenException();
2742
2743                 $user_info = api_get_user($a);
2744
2745                 if($qtype == 'friends')
2746                         $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
2747                 if($qtype == 'followers')
2748                         $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
2749
2750                 if (!$user_info["self"])
2751                         $sql_extra = " AND false ";
2752
2753                 $stringify_ids = (x($_REQUEST,'stringify_ids')?$_REQUEST['stringify_ids']:false);
2754
2755                 $r = q("SELECT `pcontact`.`id` FROM `contact`
2756                                 INNER JOIN `contact` AS `pcontact` ON `contact`.`nurl` = `pcontact`.`nurl` AND `pcontact`.`uid` = 0
2757                                 WHERE `contact`.`uid` = %s AND NOT `contact`.`self`",
2758                         intval(api_user())
2759                 );
2760
2761                 if (!dbm::is_result($r))
2762                         return;
2763
2764                 $ids = array();
2765                 foreach($r as $rr)
2766                         if ($stringify_ids)
2767                                 $ids[] = $rr['id'];
2768                         else
2769                                 $ids[] = intval($rr['id']);
2770
2771                 return api_format_data("ids", $type, array('id' => $ids));
2772         }
2773
2774         function api_friends_ids($type) {
2775                 return api_ff_ids($type,'friends');
2776         }
2777         function api_followers_ids($type) {
2778                 return api_ff_ids($type,'followers');
2779         }
2780         api_register_func('api/friends/ids','api_friends_ids',true);
2781         api_register_func('api/followers/ids','api_followers_ids',true);
2782
2783
2784         function api_direct_messages_new($type) {
2785
2786                 $a = get_app();
2787
2788                 if (api_user()===false) throw new ForbiddenException();
2789
2790                 if (!x($_POST, "text") OR (!x($_POST,"screen_name") AND !x($_POST,"user_id"))) return;
2791
2792                 $sender = api_get_user($a);
2793
2794                 if ($_POST['screen_name']) {
2795                         $r = q("SELECT `id`, `nurl`, `network` FROM `contact` WHERE `uid`=%d AND `nick`='%s'",
2796                                         intval(api_user()),
2797                                         dbesc($_POST['screen_name']));
2798
2799                         // Selecting the id by priority, friendica first
2800                         api_best_nickname($r);
2801
2802                         $recipient = api_get_user($a, $r[0]['nurl']);
2803                 } else
2804                         $recipient = api_get_user($a, $_POST['user_id']);
2805
2806                 $replyto = '';
2807                 $sub     = '';
2808                 if (x($_REQUEST,'replyto')) {
2809                         $r = q('SELECT `parent-uri`, `title` FROM `mail` WHERE `uid`=%d AND `id`=%d',
2810                                         intval(api_user()),
2811                                         intval($_REQUEST['replyto']));
2812                         $replyto = $r[0]['parent-uri'];
2813                         $sub     = $r[0]['title'];
2814                 }
2815                 else {
2816                         if (x($_REQUEST,'title')) {
2817                                 $sub = $_REQUEST['title'];
2818                         }
2819                         else {
2820                                 $sub = ((strlen($_POST['text'])>10)?substr($_POST['text'],0,10)."...":$_POST['text']);
2821                         }
2822                 }
2823
2824                 $id = send_message($recipient['cid'], $_POST['text'], $sub, $replyto);
2825
2826                 if ($id>-1) {
2827                         $r = q("SELECT * FROM `mail` WHERE id=%d", intval($id));
2828                         $ret = api_format_messages($r[0], $recipient, $sender);
2829
2830                 } else {
2831                         $ret = array("error"=>$id);
2832                 }
2833
2834                 $data = Array('direct_message'=>$ret);
2835
2836                 switch($type){
2837                         case "atom":
2838                         case "rss":
2839                                 $data = api_rss_extra($a, $data, $user_info);
2840                 }
2841
2842                 return  api_format_data("direct-messages", $type, $data);
2843
2844         }
2845         api_register_func('api/direct_messages/new','api_direct_messages_new',true, API_METHOD_POST);
2846
2847
2848         /**
2849          * @brief delete a direct_message from mail table through api
2850          *
2851          * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
2852          * @return string
2853          */
2854         function api_direct_messages_destroy($type){
2855                 $a = get_app();
2856
2857                 if (api_user()===false) throw new ForbiddenException();
2858
2859                 // params
2860                 $user_info = api_get_user($a);
2861                 //required
2862                 $id = (x($_REQUEST,'id') ? $_REQUEST['id'] : 0);
2863                 // optional
2864                 $parenturi = (x($_REQUEST, 'friendica_parenturi') ? $_REQUEST['friendica_parenturi'] : "");
2865                 $verbose = (x($_GET,'friendica_verbose')?strtolower($_GET['friendica_verbose']):"false");
2866                 /// @todo optional parameter 'include_entities' from Twitter API not yet implemented
2867
2868                 $uid = $user_info['uid'];
2869                 // error if no id or parenturi specified (for clients posting parent-uri as well)
2870                 if ($verbose == "true") {
2871                         if ($id == 0 || $parenturi == "") {
2872                                 $answer = array('result' => 'error', 'message' => 'message id or parenturi not specified');
2873                                 return api_format_data("direct_messages_delete", $type, array('$result' => $answer));
2874                         }
2875                 }
2876
2877                 // BadRequestException if no id specified (for clients using Twitter API)
2878                 if ($id == 0) throw new BadRequestException('Message id not specified');
2879
2880                 // add parent-uri to sql command if specified by calling app
2881                 $sql_extra = ($parenturi != "" ? " AND `parent-uri` = '" . dbesc($parenturi) . "'" : "");
2882
2883                 // get data of the specified message id
2884                 $r = q("SELECT `id` FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
2885                         intval($uid),
2886                         intval($id));
2887
2888                 // error message if specified id is not in database
2889                 if (!dbm::is_result($r)) {
2890                         if ($verbose == "true") {
2891                                 $answer = array('result' => 'error', 'message' => 'message id not in database');
2892                                 return api_format_data("direct_messages_delete", $type, array('$result' => $answer));
2893                         }
2894                         /// @todo BadRequestException ok for Twitter API clients?
2895                         throw new BadRequestException('message id not in database');
2896                 }
2897
2898                 // delete message
2899                 $result = q("DELETE FROM `mail` WHERE `uid` = %d AND `id` = %d" . $sql_extra,
2900                         intval($uid),
2901                         intval($id));
2902
2903                 if ($verbose == "true") {
2904                         if ($result) {
2905                                 // return success
2906                                 $answer = array('result' => 'ok', 'message' => 'message deleted');
2907                                 return api_format_data("direct_message_delete", $type, array('$result' => $answer));
2908                         }
2909                         else {
2910                                 $answer = array('result' => 'error', 'message' => 'unknown error');
2911                                 return api_format_data("direct_messages_delete", $type, array('$result' => $answer));
2912                         }
2913                 }
2914                 /// @todo return JSON data like Twitter API not yet implemented
2915
2916         }
2917         api_register_func('api/direct_messages/destroy', 'api_direct_messages_destroy', true, API_METHOD_DELETE);
2918
2919
2920         function api_direct_messages_box($type, $box, $verbose) {
2921
2922                 $a = get_app();
2923
2924                 if (api_user()===false) throw new ForbiddenException();
2925
2926                 // params
2927                 $count = (x($_GET,'count')?$_GET['count']:20);
2928                 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
2929                 if ($page<0) $page=0;
2930
2931                 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
2932                 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
2933
2934                 $user_id = (x($_REQUEST,'user_id')?$_REQUEST['user_id']:"");
2935                 $screen_name = (x($_REQUEST,'screen_name')?$_REQUEST['screen_name']:"");
2936
2937                 //  caller user info
2938                 unset($_REQUEST["user_id"]);
2939                 unset($_GET["user_id"]);
2940
2941                 unset($_REQUEST["screen_name"]);
2942                 unset($_GET["screen_name"]);
2943
2944                 $user_info = api_get_user($a);
2945                 $profile_url = $user_info["url"];
2946
2947
2948                 // pagination
2949                 $start = $page*$count;
2950
2951                 // filters
2952                 if ($box=="sentbox") {
2953                         $sql_extra = "`mail`.`from-url`='".dbesc( $profile_url )."'";
2954                 }
2955                 elseif ($box=="conversation") {
2956                         $sql_extra = "`mail`.`parent-uri`='".dbesc( $_GET["uri"] )  ."'";
2957                 }
2958                 elseif ($box=="all") {
2959                         $sql_extra = "true";
2960                 }
2961                 elseif ($box=="inbox") {
2962                         $sql_extra = "`mail`.`from-url`!='".dbesc( $profile_url )."'";
2963                 }
2964
2965                 if ($max_id > 0)
2966                         $sql_extra .= ' AND `mail`.`id` <= '.intval($max_id);
2967
2968                 if ($user_id !="") {
2969                         $sql_extra .= ' AND `mail`.`contact-id` = ' . intval($user_id);
2970                 }
2971                 elseif($screen_name !=""){
2972                         $sql_extra .= " AND `contact`.`nick` = '" . dbesc($screen_name). "'";
2973                 }
2974
2975                 $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",
2976                                 intval(api_user()),
2977                                 intval($since_id),
2978                                 intval($start), intval($count)
2979                 );
2980                 if ($verbose == "true") {
2981                         // stop execution and return error message if no mails available
2982                         if($r == null) {
2983                                 $answer = array('result' => 'error', 'message' => 'no mails available');
2984                                 return api_format_data("direct_messages_all", $type, array('$result' => $answer));
2985                         }
2986                 }
2987
2988                 $ret = Array();
2989                 foreach($r as $item) {
2990                         if ($box == "inbox" || $item['from-url'] != $profile_url){
2991                                 $recipient = $user_info;
2992                                 $sender = api_get_user($a,normalise_link($item['contact-url']));
2993                         }
2994                         elseif ($box == "sentbox" || $item['from-url'] == $profile_url){
2995                                 $recipient = api_get_user($a,normalise_link($item['contact-url']));
2996                                 $sender = $user_info;
2997
2998                         }
2999                         $ret[]=api_format_messages($item, $recipient, $sender);
3000                 }
3001
3002
3003                 $data = array('direct_message' => $ret);
3004                 switch($type){
3005                         case "atom":
3006                         case "rss":
3007                                 $data = api_rss_extra($a, $data, $user_info);
3008                 }
3009
3010                 return  api_format_data("direct-messages", $type, $data);
3011
3012         }
3013
3014         function api_direct_messages_sentbox($type){
3015                 $verbose = (x($_GET,'friendica_verbose')?strtolower($_GET['friendica_verbose']):"false");
3016                 return api_direct_messages_box($type, "sentbox", $verbose);
3017         }
3018         function api_direct_messages_inbox($type){
3019                 $verbose = (x($_GET,'friendica_verbose')?strtolower($_GET['friendica_verbose']):"false");
3020                 return api_direct_messages_box($type, "inbox", $verbose);
3021         }
3022         function api_direct_messages_all($type){
3023                 $verbose = (x($_GET,'friendica_verbose')?strtolower($_GET['friendica_verbose']):"false");
3024                 return api_direct_messages_box($type, "all", $verbose);
3025         }
3026         function api_direct_messages_conversation($type){
3027                 $verbose = (x($_GET,'friendica_verbose')?strtolower($_GET['friendica_verbose']):"false");
3028                 return api_direct_messages_box($type, "conversation", $verbose);
3029         }
3030         api_register_func('api/direct_messages/conversation','api_direct_messages_conversation',true);
3031         api_register_func('api/direct_messages/all','api_direct_messages_all',true);
3032         api_register_func('api/direct_messages/sent','api_direct_messages_sentbox',true);
3033         api_register_func('api/direct_messages','api_direct_messages_inbox',true);
3034
3035
3036
3037         function api_oauth_request_token($type){
3038                 try{
3039                         $oauth = new FKOAuth1();
3040                         $r = $oauth->fetch_request_token(OAuthRequest::from_request());
3041                 }catch(Exception $e){
3042                         echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage()); killme();
3043                 }
3044                 echo $r;
3045                 killme();
3046         }
3047         function api_oauth_access_token($type){
3048                 try{
3049                         $oauth = new FKOAuth1();
3050                         $r = $oauth->fetch_access_token(OAuthRequest::from_request());
3051                 }catch(Exception $e){
3052                         echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage()); killme();
3053                 }
3054                 echo $r;
3055                 killme();
3056         }
3057
3058         api_register_func('api/oauth/request_token', 'api_oauth_request_token', false);
3059         api_register_func('api/oauth/access_token', 'api_oauth_access_token', false);
3060
3061
3062         function api_fr_photos_list($type) {
3063                 if (api_user()===false) throw new ForbiddenException();
3064                 $r = q("select `resource-id`, max(scale) as scale, album, filename, type from photo
3065                                 where uid = %d and album != 'Contact Photos' group by `resource-id`",
3066                         intval(local_user())
3067                 );
3068                 $typetoext = array(
3069                 'image/jpeg' => 'jpg',
3070                 'image/png' => 'png',
3071                 'image/gif' => 'gif'
3072                 );
3073                 $data = array('photo'=>array());
3074                 if ($r) {
3075                         foreach ($r as $rr) {
3076                                 $photo = array();
3077                                 $photo['id'] = $rr['resource-id'];
3078                                 $photo['album'] = $rr['album'];
3079                                 $photo['filename'] = $rr['filename'];
3080                                 $photo['type'] = $rr['type'];
3081                                 $thumb = App::get_baseurl()."/photo/".$rr['resource-id']."-".$rr['scale'].".".$typetoext[$rr['type']];
3082
3083                                 if ($type == "xml")
3084                                         $data['photo'][] = array("@attributes" => $photo, "1" => $thumb);
3085                                 else {
3086                                         $photo['thumb'] = $thumb;
3087                                         $data['photo'][] = $photo;
3088                                 }
3089                         }
3090                 }
3091                 return  api_format_data("photos", $type, $data);
3092         }
3093
3094         function api_fr_photo_detail($type) {
3095                 if (api_user()===false) throw new ForbiddenException();
3096                 if(!x($_REQUEST,'photo_id')) throw new BadRequestException("No photo id.");
3097
3098                 $scale = (x($_REQUEST, 'scale') ? intval($_REQUEST['scale']) : false);
3099                 $scale_sql = ($scale === false ? "" : sprintf("and scale=%d",intval($scale)));
3100                 $data_sql = ($scale === false ? "" : "data, ");
3101
3102                 $r = q("select %s `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
3103                                                 `type`, `height`, `width`, `datasize`, `profile`, min(`scale`) as minscale, max(`scale`) as maxscale
3104                                 from photo where `uid` = %d and `resource-id` = '%s' %s group by `resource-id`",
3105                         $data_sql,
3106                         intval(local_user()),
3107                         dbesc($_REQUEST['photo_id']),
3108                         $scale_sql
3109                 );
3110
3111                 $typetoext = array(
3112                 'image/jpeg' => 'jpg',
3113                 'image/png' => 'png',
3114                 'image/gif' => 'gif'
3115                 );
3116
3117                 if ($r) {
3118                         $data = array('photo' => $r[0]);
3119                         $data['photo']['id'] = $data['photo']['resource-id'];
3120                         if ($scale !== false) {
3121                                 $data['photo']['data'] = base64_encode($data['photo']['data']);
3122                         } else {
3123                                 unset($data['photo']['datasize']); //needed only with scale param
3124                         }
3125                         if ($type == "xml") {
3126                                 $data['photo']['links'] = array();
3127                                 for ($k=intval($data['photo']['minscale']); $k<=intval($data['photo']['maxscale']); $k++)
3128                                         $data['photo']['links'][$k.":link"]["@attributes"] = array("type" => $data['photo']['type'],
3129                                                                                         "scale" => $k,
3130                                                                                         "href" => App::get_baseurl()."/photo/".$data['photo']['resource-id']."-".$k.".".$typetoext[$data['photo']['type']]);
3131                         } else {
3132                                 $data['photo']['link'] = array();
3133                                 for ($k=intval($data['photo']['minscale']); $k<=intval($data['photo']['maxscale']); $k++) {
3134                                         $data['photo']['link'][$k] = App::get_baseurl()."/photo/".$data['photo']['resource-id']."-".$k.".".$typetoext[$data['photo']['type']];
3135                                 }
3136                         }
3137                         unset($data['photo']['resource-id']);
3138                         unset($data['photo']['minscale']);
3139                         unset($data['photo']['maxscale']);
3140
3141                 } else {
3142                         throw new NotFoundException();
3143                 }
3144
3145                 return api_format_data("photo_detail", $type, $data);
3146         }
3147
3148         api_register_func('api/friendica/photos/list', 'api_fr_photos_list', true);
3149         api_register_func('api/friendica/photo', 'api_fr_photo_detail', true);
3150
3151
3152
3153         /**
3154          * similar as /mod/redir.php
3155          * redirect to 'url' after dfrn auth
3156          *
3157          * why this when there is mod/redir.php already?
3158          * This use api_user() and api_login()
3159          *
3160          * params
3161          *              c_url: url of remote contact to auth to
3162          *              url: string, url to redirect after auth
3163          */
3164         function api_friendica_remoteauth() {
3165                 $url = ((x($_GET,'url')) ? $_GET['url'] : '');
3166                 $c_url = ((x($_GET,'c_url')) ? $_GET['c_url'] : '');
3167
3168                 if ($url === '' || $c_url === '')
3169                         throw new BadRequestException("Wrong parameters.");
3170
3171                 $c_url = normalise_link($c_url);
3172
3173                 // traditional DFRN
3174
3175                 $r = q("SELECT * FROM `contact` WHERE `id` = %d AND `nurl` = '%s' LIMIT 1",
3176                         dbesc($c_url),
3177                         intval(api_user())
3178                 );
3179
3180                 if ((! dbm::is_result($r)) || ($r[0]['network'] !== NETWORK_DFRN))
3181                         throw new BadRequestException("Unknown contact");
3182
3183                 $cid = $r[0]['id'];
3184
3185                 $dfrn_id = $orig_id = (($r[0]['issued-id']) ? $r[0]['issued-id'] : $r[0]['dfrn-id']);
3186
3187                 if($r[0]['duplex'] && $r[0]['issued-id']) {
3188                         $orig_id = $r[0]['issued-id'];
3189                         $dfrn_id = '1:' . $orig_id;
3190                 }
3191                 if($r[0]['duplex'] && $r[0]['dfrn-id']) {
3192                         $orig_id = $r[0]['dfrn-id'];
3193                         $dfrn_id = '0:' . $orig_id;
3194                 }
3195
3196                 $sec = random_string();
3197
3198                 q("INSERT INTO `profile_check` ( `uid`, `cid`, `dfrn_id`, `sec`, `expire`)
3199                         VALUES( %d, %s, '%s', '%s', %d )",
3200                         intval(api_user()),
3201                         intval($cid),
3202                         dbesc($dfrn_id),
3203                         dbesc($sec),
3204                         intval(time() + 45)
3205                 );
3206
3207                 logger($r[0]['name'] . ' ' . $sec, LOGGER_DEBUG);
3208                 $dest = (($url) ? '&destination_url=' . $url : '');
3209                 goaway ($r[0]['poll'] . '?dfrn_id=' . $dfrn_id
3210                                 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
3211                                 . '&type=profile&sec=' . $sec . $dest . $quiet );
3212         }
3213         api_register_func('api/friendica/remoteauth', 'api_friendica_remoteauth', true);
3214
3215         /**
3216          * @brief Return the item shared, if the item contains only the [share] tag
3217          *
3218          * @param array $item Sharer item
3219          * @return array Shared item or false if not a reshare
3220          */
3221         function api_share_as_retweet(&$item) {
3222                 $body = trim($item["body"]);
3223
3224                 if (Diaspora::is_reshare($body, false)===false) {
3225                         return false;
3226                 }
3227
3228                 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$1",$body);
3229                 // Skip if there is no shared message in there
3230                 // we already checked this in diaspora::is_reshare()
3231                 // but better one more than one less...
3232                 if ($body == $attributes)
3233                         return false;
3234
3235
3236                 // build the fake reshared item
3237                 $reshared_item = $item;
3238
3239                 $author = "";
3240                 preg_match("/author='(.*?)'/ism", $attributes, $matches);
3241                 if ($matches[1] != "")
3242                         $author = html_entity_decode($matches[1],ENT_QUOTES,'UTF-8');
3243
3244                 preg_match('/author="(.*?)"/ism', $attributes, $matches);
3245                 if ($matches[1] != "")
3246                         $author = $matches[1];
3247
3248                 $profile = "";
3249                 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
3250                 if ($matches[1] != "")
3251                         $profile = $matches[1];
3252
3253                 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
3254                 if ($matches[1] != "")
3255                         $profile = $matches[1];
3256
3257                 $avatar = "";
3258                 preg_match("/avatar='(.*?)'/ism", $attributes, $matches);
3259                 if ($matches[1] != "")
3260                         $avatar = $matches[1];
3261
3262                 preg_match('/avatar="(.*?)"/ism', $attributes, $matches);
3263                 if ($matches[1] != "")
3264                         $avatar = $matches[1];
3265
3266                 $link = "";
3267                 preg_match("/link='(.*?)'/ism", $attributes, $matches);
3268                 if ($matches[1] != "")
3269                         $link = $matches[1];
3270
3271                 preg_match('/link="(.*?)"/ism', $attributes, $matches);
3272                 if ($matches[1] != "")
3273                         $link = $matches[1];
3274
3275                 $posted = "";
3276                 preg_match("/posted='(.*?)'/ism", $attributes, $matches);
3277                 if ($matches[1] != "")
3278                         $posted= $matches[1];
3279
3280                 preg_match('/posted="(.*?)"/ism', $attributes, $matches);
3281                 if ($matches[1] != "")
3282                         $posted = $matches[1];
3283
3284                 $shared_body = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$2",$body);
3285
3286                 if (($shared_body == "") || ($profile == "") || ($author == "") || ($avatar == "") || ($posted == ""))
3287                         return false;
3288
3289
3290
3291                 $reshared_item["body"] = $shared_body;
3292                 $reshared_item["author-name"] = $author;
3293                 $reshared_item["author-link"] = $profile;
3294                 $reshared_item["author-avatar"] = $avatar;
3295                 $reshared_item["plink"] = $link;
3296                 $reshared_item["created"] = $posted;
3297                 $reshared_item["edited"] = $posted;
3298
3299                 return $reshared_item;
3300
3301         }
3302
3303         function api_get_nick($profile) {
3304                 /* To-Do:
3305                  - remove trailing junk from profile url
3306                  - pump.io check has to check the website
3307                 */
3308
3309                 $nick = "";
3310
3311                 $r = q("SELECT `nick` FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s'",
3312                         dbesc(normalise_link($profile)));
3313                 if ($r)
3314                         $nick = $r[0]["nick"];
3315
3316                 if (!$nick == "") {
3317                         $r = q("SELECT `nick` FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s'",
3318                                 dbesc(normalise_link($profile)));
3319                         if ($r)
3320                                 $nick = $r[0]["nick"];
3321                 }
3322
3323                 if (!$nick == "") {
3324                         $friendica = preg_replace("=https?://(.*)/profile/(.*)=ism", "$2", $profile);
3325                         if ($friendica != $profile)
3326                                 $nick = $friendica;
3327                 }
3328
3329                 if (!$nick == "") {
3330                         $diaspora = preg_replace("=https?://(.*)/u/(.*)=ism", "$2", $profile);
3331                         if ($diaspora != $profile)
3332                                 $nick = $diaspora;
3333                 }
3334
3335                 if (!$nick == "") {
3336                         $twitter = preg_replace("=https?://twitter.com/(.*)=ism", "$1", $profile);
3337                         if ($twitter != $profile)
3338                                 $nick = $twitter;
3339                 }
3340
3341
3342                 if (!$nick == "") {
3343                         $StatusnetHost = preg_replace("=https?://(.*)/user/(.*)=ism", "$1", $profile);
3344                         if ($StatusnetHost != $profile) {
3345                                 $StatusnetUser = preg_replace("=https?://(.*)/user/(.*)=ism", "$2", $profile);
3346                                 if ($StatusnetUser != $profile) {
3347                                         $UserData = fetch_url("http://".$StatusnetHost."/api/users/show.json?user_id=".$StatusnetUser);
3348                                         $user = json_decode($UserData);
3349                                         if ($user)
3350                                                 $nick = $user->screen_name;
3351                                 }
3352                         }
3353                 }
3354
3355                 // To-Do: look at the page if its really a pumpio site
3356                 //if (!$nick == "") {
3357                 //      $pumpio = preg_replace("=https?://(.*)/(.*)/=ism", "$2", $profile."/");
3358                 //      if ($pumpio != $profile)
3359                 //              $nick = $pumpio;
3360                         //      <div class="media" id="profile-block" data-profile-id="acct:kabniel@microca.st">
3361
3362                 //}
3363
3364                 if ($nick != "")
3365                         return($nick);
3366
3367                 return(false);
3368         }
3369
3370         function api_in_reply_to($item) {
3371                 $in_reply_to = array();
3372
3373                 $in_reply_to['status_id'] = NULL;
3374                 $in_reply_to['user_id'] = NULL;
3375                 $in_reply_to['status_id_str'] = NULL;
3376                 $in_reply_to['user_id_str'] = NULL;
3377                 $in_reply_to['screen_name'] = NULL;
3378
3379                 if (($item['thr-parent'] != $item['uri']) AND (intval($item['parent']) != intval($item['id']))) {
3380                         $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' LIMIT 1",
3381                                 intval($item['uid']),
3382                                 dbesc($item['thr-parent']));
3383
3384                         if (dbm::is_result($r)) {
3385                                 $in_reply_to['status_id'] = intval($r[0]['id']);
3386                         } else {
3387                                 $in_reply_to['status_id'] = intval($item['parent']);
3388                         }
3389
3390                         $in_reply_to['status_id_str'] = (string) intval($in_reply_to['status_id']);
3391
3392                         $r = q("SELECT `contact`.`nick`, `contact`.`name`, `contact`.`id`, `contact`.`url` FROM item
3393                                 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`author-id`
3394                                 WHERE `item`.`id` = %d LIMIT 1",
3395                                 intval($in_reply_to['status_id'])
3396                         );
3397
3398                         if (dbm::is_result($r)) {
3399                                 if ($r[0]['nick'] == "") {
3400                                         $r[0]['nick'] = api_get_nick($r[0]["url"]);
3401                                 }
3402
3403                                 $in_reply_to['screen_name'] = (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']);
3404                                 $in_reply_to['user_id'] = intval($r[0]['id']);
3405                                 $in_reply_to['user_id_str'] = (string) intval($r[0]['id']);
3406                         }
3407
3408                         // There seems to be situation, where both fields are identical:
3409                         // https://github.com/friendica/friendica/issues/1010
3410                         // This is a bugfix for that.
3411                         if (intval($in_reply_to['status_id']) == intval($item['id'])) {
3412                                 logger('this message should never appear: id: '.$item['id'].' similar to reply-to: '.$in_reply_to['status_id'], LOGGER_DEBUG);
3413                                 $in_reply_to['status_id'] = NULL;
3414                                 $in_reply_to['user_id'] = NULL;
3415                                 $in_reply_to['status_id_str'] = NULL;
3416                                 $in_reply_to['user_id_str'] = NULL;
3417                                 $in_reply_to['screen_name'] = NULL;
3418                         }
3419                 }
3420
3421                 return $in_reply_to;
3422         }
3423
3424         function api_clean_plain_items($Text) {
3425                 $include_entities = strtolower(x($_REQUEST,'include_entities')?$_REQUEST['include_entities']:"false");
3426
3427                 $Text = bb_CleanPictureLinks($Text);
3428                 $URLSearchString = "^\[\]";
3429
3430                 $Text = preg_replace("/([!#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'$1$3',$Text);
3431
3432                 if ($include_entities == "true") {
3433                         $Text = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'[url=$1]$1[/url]',$Text);
3434                 }
3435
3436                 // Simplify "attachment" element
3437                 $Text = api_clean_attachments($Text);
3438
3439                 return($Text);
3440         }
3441
3442         /**
3443          * @brief Removes most sharing information for API text export
3444          *
3445          * @param string $body The original body
3446          *
3447          * @return string Cleaned body
3448          */
3449         function api_clean_attachments($body) {
3450                 $data = get_attachment_data($body);
3451
3452                 if (!$data)
3453                         return $body;
3454
3455                 $body = "";
3456
3457                 if (isset($data["text"]))
3458                         $body = $data["text"];
3459
3460                 if (($body == "") AND (isset($data["title"])))
3461                         $body = $data["title"];
3462
3463                 if (isset($data["url"]))
3464                         $body .= "\n".$data["url"];
3465
3466                 $body .= $data["after"];
3467
3468                 return $body;
3469         }
3470
3471         function api_best_nickname(&$contacts) {
3472                 $best_contact = array();
3473
3474                 if (count($contact) == 0)
3475                         return;
3476
3477                 foreach ($contacts AS $contact)
3478                         if ($contact["network"] == "") {
3479                                 $contact["network"] = "dfrn";
3480                                 $best_contact = array($contact);
3481                         }
3482
3483                 if (sizeof($best_contact) == 0)
3484                         foreach ($contacts AS $contact)
3485                                 if ($contact["network"] == "dfrn")
3486                                         $best_contact = array($contact);
3487
3488                 if (sizeof($best_contact) == 0)
3489                         foreach ($contacts AS $contact)
3490                                 if ($contact["network"] == "dspr")
3491                                         $best_contact = array($contact);
3492
3493                 if (sizeof($best_contact) == 0)
3494                         foreach ($contacts AS $contact)
3495                                 if ($contact["network"] == "stat")
3496                                         $best_contact = array($contact);
3497
3498                 if (sizeof($best_contact) == 0)
3499                         foreach ($contacts AS $contact)
3500                                 if ($contact["network"] == "pump")
3501                                         $best_contact = array($contact);
3502
3503                 if (sizeof($best_contact) == 0)
3504                         foreach ($contacts AS $contact)
3505                                 if ($contact["network"] == "twit")
3506                                         $best_contact = array($contact);
3507
3508                 if (sizeof($best_contact) == 1)
3509                         $contacts = $best_contact;
3510                 else
3511                         $contacts = array($contacts[0]);
3512         }
3513
3514         // return all or a specified group of the user with the containing contacts
3515         function api_friendica_group_show($type) {
3516
3517                 $a = get_app();
3518
3519                 if (api_user()===false) throw new ForbiddenException();
3520
3521                 // params
3522                 $user_info = api_get_user($a);
3523                 $gid = (x($_REQUEST,'gid') ? $_REQUEST['gid'] : 0);
3524                 $uid = $user_info['uid'];
3525
3526                 // get data of the specified group id or all groups if not specified
3527                 if ($gid != 0) {
3528                         $r = q("SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d AND `id` = %d",
3529                                 intval($uid),
3530                                 intval($gid));
3531                         // error message if specified gid is not in database
3532                         if (!dbm::is_result($r))
3533                                 throw new BadRequestException("gid not available");
3534                 }
3535                 else
3536                         $r = q("SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d",
3537                                 intval($uid));
3538
3539                 // loop through all groups and retrieve all members for adding data in the user array
3540                 foreach ($r as $rr) {
3541                         $members = group_get_members($rr['id']);
3542                         $users = array();
3543
3544                         if ($type == "xml") {
3545                                 $user_element = "users";
3546                                 $k = 0;
3547                                 foreach ($members as $member) {
3548                                         $user = api_get_user($a, $member['nurl']);
3549                                         $users[$k++.":user"] = $user;
3550                                 }
3551                         } else {
3552                                 $user_element = "user";
3553                                 foreach ($members as $member) {
3554                                         $user = api_get_user($a, $member['nurl']);
3555                                         $users[] = $user;
3556                                 }
3557                         }
3558                         $grps[] = array('name' => $rr['name'], 'gid' => $rr['id'], $user_element => $users);
3559                 }
3560                 return api_format_data("groups", $type, array('group' => $grps));
3561         }
3562         api_register_func('api/friendica/group_show', 'api_friendica_group_show', true);
3563
3564
3565         // delete the specified group of the user
3566         function api_friendica_group_delete($type) {
3567
3568                 $a = get_app();
3569
3570                 if (api_user()===false) throw new ForbiddenException();
3571
3572                 // params
3573                 $user_info = api_get_user($a);
3574                 $gid = (x($_REQUEST,'gid') ? $_REQUEST['gid'] : 0);
3575                 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
3576                 $uid = $user_info['uid'];
3577
3578                 // error if no gid specified
3579                 if ($gid == 0 || $name == "")
3580                         throw new BadRequestException('gid or name not specified');
3581
3582                 // get data of the specified group id
3583                 $r = q("SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d",
3584                         intval($uid),
3585                         intval($gid));
3586                 // error message if specified gid is not in database
3587                 if (!dbm::is_result($r))
3588                         throw new BadRequestException('gid not available');
3589
3590                 // get data of the specified group id and group name
3591                 $rname = q("SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d AND `name` = '%s'",
3592                         intval($uid),
3593                         intval($gid),
3594                         dbesc($name));
3595                 // error message if specified gid is not in database
3596                 if (!dbm::is_result($rname))
3597                         throw new BadRequestException('wrong group name');
3598
3599                 // delete group
3600                 $ret = group_rmv($uid, $name);
3601                 if ($ret) {
3602                         // return success
3603                         $success = array('success' => $ret, 'gid' => $gid, 'name' => $name, 'status' => 'deleted', 'wrong users' => array());
3604                         return api_format_data("group_delete", $type, array('result' => $success));
3605                 }
3606                 else
3607                         throw new BadRequestException('other API error');
3608         }
3609         api_register_func('api/friendica/group_delete', 'api_friendica_group_delete', true, API_METHOD_DELETE);
3610
3611
3612         // create the specified group with the posted array of contacts
3613         function api_friendica_group_create($type) {
3614
3615                 $a = get_app();
3616
3617                 if (api_user()===false) throw new ForbiddenException();
3618
3619                 // params
3620                 $user_info = api_get_user($a);
3621                 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
3622                 $uid = $user_info['uid'];
3623                 $json = json_decode($_POST['json'], true);
3624                 $users = $json['user'];
3625
3626                 // error if no name specified
3627                 if ($name == "")
3628                         throw new BadRequestException('group name not specified');
3629
3630                 // get data of the specified group name
3631                 $rname = q("SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 0",
3632                         intval($uid),
3633                         dbesc($name));
3634                 // error message if specified group name already exists
3635                 if (dbm::is_result($rname))
3636                         throw new BadRequestException('group name already exists');
3637
3638                 // check if specified group name is a deleted group
3639                 $rname = q("SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 1",
3640                         intval($uid),
3641                         dbesc($name));
3642                 // error message if specified group name already exists
3643                 if (dbm::is_result($rname))
3644                         $reactivate_group = true;
3645
3646                 // create group
3647                 $ret = group_add($uid, $name);
3648                 if ($ret)
3649                         $gid = group_byname($uid, $name);
3650                 else
3651                         throw new BadRequestException('other API error');
3652
3653                 // add members
3654                 $erroraddinguser = false;
3655                 $errorusers = array();
3656                 foreach ($users as $user) {
3657                         $cid = $user['cid'];
3658                         // check if user really exists as contact
3659                         $contact = q("SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
3660                                 intval($cid),
3661                                 intval($uid));
3662                         if (count($contact))
3663                                 $result = group_add_member($uid, $name, $cid, $gid);
3664                         else {
3665                                 $erroraddinguser = true;
3666                                 $errorusers[] = $cid;
3667                         }
3668                 }
3669
3670                 // return success message incl. missing users in array
3671                 $status = ($erroraddinguser ? "missing user" : ($reactivate_group ? "reactivated" : "ok"));
3672                 $success = array('success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers);
3673                 return api_format_data("group_create", $type, array('result' => $success));
3674         }
3675         api_register_func('api/friendica/group_create', 'api_friendica_group_create', true, API_METHOD_POST);
3676
3677
3678         // update the specified group with the posted array of contacts
3679         function api_friendica_group_update($type) {
3680
3681                 $a = get_app();
3682
3683                 if (api_user()===false) throw new ForbiddenException();
3684
3685                 // params
3686                 $user_info = api_get_user($a);
3687                 $uid = $user_info['uid'];
3688                 $gid = (x($_REQUEST, 'gid') ? $_REQUEST['gid'] : 0);
3689                 $name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
3690                 $json = json_decode($_POST['json'], true);
3691                 $users = $json['user'];
3692
3693                 // error if no name specified
3694                 if ($name == "")
3695                         throw new BadRequestException('group name not specified');
3696
3697                 // error if no gid specified
3698                 if ($gid == "")
3699                         throw new BadRequestException('gid not specified');
3700
3701                 // remove members
3702                 $members = group_get_members($gid);
3703                 foreach ($members as $member) {
3704                         $cid = $member['id'];
3705                         foreach ($users as $user) {
3706                                 $found = ($user['cid'] == $cid ? true : false);
3707                         }
3708                         if (!$found) {
3709                                 $ret = group_rmv_member($uid, $name, $cid);
3710                         }
3711                 }
3712
3713                 // add members
3714                 $erroraddinguser = false;
3715                 $errorusers = array();
3716                 foreach ($users as $user) {
3717                         $cid = $user['cid'];
3718                         // check if user really exists as contact
3719                         $contact = q("SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
3720                                 intval($cid),
3721                                 intval($uid));
3722                         if (count($contact))
3723                                 $result = group_add_member($uid, $name, $cid, $gid);
3724                         else {
3725                                 $erroraddinguser = true;
3726                                 $errorusers[] = $cid;
3727                         }
3728                 }
3729
3730                 // return success message incl. missing users in array
3731                 $status = ($erroraddinguser ? "missing user" : "ok");
3732                 $success = array('success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers);
3733                 return api_format_data("group_update", $type, array('result' => $success));
3734         }
3735         api_register_func('api/friendica/group_update', 'api_friendica_group_update', true, API_METHOD_POST);
3736
3737
3738         function api_friendica_activity($type) {
3739
3740                 $a = get_app();
3741
3742                 if (api_user()===false) throw new ForbiddenException();
3743                 $verb = strtolower($a->argv[3]);
3744                 $verb = preg_replace("|\..*$|", "", $verb);
3745
3746                 $id = (x($_REQUEST, 'id') ? $_REQUEST['id'] : 0);
3747
3748                 $res = do_like($id, $verb);
3749
3750                 if ($res) {
3751                         if ($type == "xml")
3752                                 $ok = "true";
3753                         else
3754                                 $ok = "ok";
3755                         return api_format_data('ok', $type, array('ok' => $ok));
3756                 } else {
3757                         throw new BadRequestException('Error adding activity');
3758                 }
3759
3760         }
3761         api_register_func('api/friendica/activity/like', 'api_friendica_activity', true, API_METHOD_POST);
3762         api_register_func('api/friendica/activity/dislike', 'api_friendica_activity', true, API_METHOD_POST);
3763         api_register_func('api/friendica/activity/attendyes', 'api_friendica_activity', true, API_METHOD_POST);
3764         api_register_func('api/friendica/activity/attendno', 'api_friendica_activity', true, API_METHOD_POST);
3765         api_register_func('api/friendica/activity/attendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
3766         api_register_func('api/friendica/activity/unlike', 'api_friendica_activity', true, API_METHOD_POST);
3767         api_register_func('api/friendica/activity/undislike', 'api_friendica_activity', true, API_METHOD_POST);
3768         api_register_func('api/friendica/activity/unattendyes', 'api_friendica_activity', true, API_METHOD_POST);
3769         api_register_func('api/friendica/activity/unattendno', 'api_friendica_activity', true, API_METHOD_POST);
3770         api_register_func('api/friendica/activity/unattendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
3771
3772         /**
3773          * @brief Returns notifications
3774          *
3775          * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3776          * @return string
3777         */
3778         function api_friendica_notification($type) {
3779
3780                 $a = get_app();
3781
3782                 if (api_user()===false) throw new ForbiddenException();
3783                 if ($a->argc!==3) throw new BadRequestException("Invalid argument count");
3784                 $nm = new NotificationsManager();
3785
3786                 $notes = $nm->getAll(array(), "+seen -date", 50);
3787
3788                 if ($type == "xml") {
3789                         $xmlnotes = array();
3790                         foreach ($notes AS $note)
3791                                 $xmlnotes[] = array("@attributes" => $note);
3792
3793                         $notes = $xmlnotes;
3794                 }
3795
3796                 return api_format_data("notes", $type, array('note' => $notes));
3797         }
3798
3799         /**
3800          * @brief Set notification as seen and returns associated item (if possible)
3801          *
3802          * POST request with 'id' param as notification id
3803          *
3804          * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3805          * @return string
3806          */
3807         function api_friendica_notification_seen($type){
3808
3809                 $a = get_app();
3810
3811                 if (api_user()===false) throw new ForbiddenException();
3812                 if ($a->argc!==4) throw new BadRequestException("Invalid argument count");
3813
3814                 $id = (x($_REQUEST, 'id') ? intval($_REQUEST['id']) : 0);
3815
3816                 $nm = new NotificationsManager();
3817                 $note = $nm->getByID($id);
3818                 if (is_null($note)) throw new BadRequestException("Invalid argument");
3819
3820                 $nm->setSeen($note);
3821                 if ($note['otype']=='item') {
3822                         // would be really better with an ItemsManager and $im->getByID() :-P
3823                         $r = q("SELECT * FROM `item` WHERE `id`=%d AND `uid`=%d",
3824                                 intval($note['iid']),
3825                                 intval(local_user())
3826                         );
3827                         if ($r!==false) {
3828                                 // we found the item, return it to the user
3829                                 $user_info = api_get_user($a);
3830                                 $ret = api_format_items($r,$user_info, false, $type);
3831                                 $data = array('status' => $ret);
3832                                 return api_format_data("status", $type, $data);
3833                         }
3834                         // the item can't be found, but we set the note as seen, so we count this as a success
3835                 }
3836                 return api_format_data('result', $type, array('result' => "success"));
3837         }
3838
3839         api_register_func('api/friendica/notification/seen', 'api_friendica_notification_seen', true, API_METHOD_POST);
3840         api_register_func('api/friendica/notification', 'api_friendica_notification', true, API_METHOD_GET);
3841
3842
3843         /**
3844          * @brief update a direct_message to seen state
3845          *
3846          * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3847          * @return string (success result=ok, error result=error with error message)
3848          */
3849         function api_friendica_direct_messages_setseen($type){
3850                 $a = get_app();
3851                 if (api_user()===false) throw new ForbiddenException();
3852
3853                 // params
3854                 $user_info = api_get_user($a);
3855                 $uid = $user_info['uid'];
3856                 $id = (x($_REQUEST, 'id') ? $_REQUEST['id'] : 0);
3857
3858                 // return error if id is zero
3859                 if ($id == "") {
3860                         $answer = array('result' => 'error', 'message' => 'message id not specified');
3861                         return api_format_data("direct_messages_setseen", $type, array('$result' => $answer));
3862                 }
3863
3864                 // get data of the specified message id
3865                 $r = q("SELECT `id` FROM `mail` WHERE `id` = %d AND `uid` = %d",
3866                         intval($id),
3867                         intval($uid));
3868                 // error message if specified id is not in database
3869                 if (!dbm::is_result($r)) {
3870                         $answer = array('result' => 'error', 'message' => 'message id not in database');
3871                         return api_format_data("direct_messages_setseen", $type, array('$result' => $answer));
3872                 }
3873
3874                 // update seen indicator
3875                 $result = q("UPDATE `mail` SET `seen` = 1 WHERE `id` = %d AND `uid` = %d",
3876                         intval($id),
3877                         intval($uid));
3878
3879                 if ($result) {
3880                         // return success
3881                         $answer = array('result' => 'ok', 'message' => 'message set to seen');
3882                         return api_format_data("direct_message_setseen", $type, array('$result' => $answer));
3883                 } else {
3884                         $answer = array('result' => 'error', 'message' => 'unknown error');
3885                         return api_format_data("direct_messages_setseen", $type, array('$result' => $answer));
3886                 }
3887         }
3888         api_register_func('api/friendica/direct_messages_setseen', 'api_friendica_direct_messages_setseen', true);
3889
3890
3891
3892
3893         /**
3894          * @brief search for direct_messages containing a searchstring through api
3895          *
3896          * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3897          * @return string (success: success=true if found and search_result contains found messages
3898          *                          success=false if nothing was found, search_result='nothing found',
3899          *                 error: result=error with error message)
3900          */
3901         function api_friendica_direct_messages_search($type){
3902                 $a = get_app();
3903
3904                 if (api_user()===false) throw new ForbiddenException();
3905
3906                 // params
3907                 $user_info = api_get_user($a);
3908                 $searchstring = (x($_REQUEST,'searchstring') ? $_REQUEST['searchstring'] : "");
3909                 $uid = $user_info['uid'];
3910
3911                 // error if no searchstring specified
3912                 if ($searchstring == "") {
3913                         $answer = array('result' => 'error', 'message' => 'searchstring not specified');
3914                         return api_format_data("direct_messages_search", $type, array('$result' => $answer));
3915                 }
3916
3917                 // get data for the specified searchstring
3918                 $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",
3919                         intval($uid),
3920                         dbesc('%'.$searchstring.'%')
3921                 );
3922
3923                 $profile_url = $user_info["url"];
3924                 // message if nothing was found
3925                 if (!dbm::is_result($r))
3926                         $success = array('success' => false, 'search_results' => 'problem with query');
3927                 else if (count($r) == 0)
3928                         $success = array('success' => false, 'search_results' => 'nothing found');
3929                 else {
3930                         $ret = Array();
3931                         foreach($r as $item) {
3932                                 if ($box == "inbox" || $item['from-url'] != $profile_url){
3933                                         $recipient = $user_info;
3934                                         $sender = api_get_user($a,normalise_link($item['contact-url']));
3935                                 }
3936                                 elseif ($box == "sentbox" || $item['from-url'] == $profile_url){
3937                                         $recipient = api_get_user($a,normalise_link($item['contact-url']));
3938                                         $sender = $user_info;
3939                                 }
3940                                 $ret[]=api_format_messages($item, $recipient, $sender);
3941                         }
3942                         $success = array('success' => true, 'search_results' => $ret);
3943                 }
3944
3945                 return api_format_data("direct_message_search", $type, array('$result' => $success));
3946         }
3947         api_register_func('api/friendica/direct_messages_search', 'api_friendica_direct_messages_search', true);
3948
3949         /**
3950          * @brief return data of all the profiles a user has to the client
3951          *
3952          * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
3953          * @return string
3954          */
3955         function api_friendica_profile_show($type){
3956                 $a = get_app();
3957
3958                 if (api_user()===false) throw new ForbiddenException();
3959
3960                 // input params
3961                 $profileid = (x($_REQUEST,'profile_id') ? $_REQUEST['profile_id'] : 0);
3962
3963                 // retrieve general information about profiles for user
3964                 $multi_profiles = feature_enabled(api_user(),'multi_profiles');
3965                 $directory = get_config('system', 'directory');
3966
3967 // get data of the specified profile id or all profiles of the user if not specified
3968                 if ($profileid != 0) {
3969                         $r = q("SELECT * FROM `profile` WHERE `uid` = %d AND `id` = %d",
3970                                 intval(api_user()),
3971                                 intval($profileid));
3972                         // error message if specified gid is not in database
3973                         if (!dbm::is_result($r))
3974                                 throw new BadRequestException("profile_id not available");
3975                 }
3976                 else
3977                         $r = q("SELECT * FROM `profile` WHERE `uid` = %d",
3978                                 intval(api_user()));
3979
3980                 // loop through all returned profiles and retrieve data and users
3981                 $k = 0;
3982                 foreach ($r as $rr) {
3983                         $profile = api_format_items_profiles($rr, $type);
3984
3985                         // select all users from contact table, loop and prepare standard return for user data
3986                         $users = array();
3987                         $r = q("SELECT `id`, `nurl` FROM `contact` WHERE `uid`= %d AND `profile-id` = %d",
3988                                 intval(api_user()),
3989                                 intval($rr['profile_id']));
3990
3991                         foreach ($r as $rr) {
3992                                 $user = api_get_user($a, $rr['nurl']);
3993                                 ($type == "xml") ? $users[$k++.":user"] = $user : $users[] = $user;
3994                         }
3995                         $profile['users'] = $users;
3996
3997                         // add prepared profile data to array for final return
3998                         if ($type == "xml") {
3999                                 $profiles[$k++.":profile"] = $profile;
4000                         } else {
4001                                 $profiles[] = $profile;
4002                         }
4003                 }
4004
4005                 // return settings, authenticated user and profiles data
4006                 $result = array('multi_profiles' => $multi_profiles ? true : false,
4007                                                 'global_dir' => $directory,
4008                                                 'friendica_owner' => api_get_user($a, intval(api_user())),
4009                                                 'profiles' => $profiles);
4010                 return api_format_data("friendica_profiles", $type, array('$result' => $result));
4011         }
4012         api_register_func('api/friendica/profile/show', 'api_friendica_profile_show', true, API_METHOD_GET);
4013
4014 /*
4015 To.Do:
4016     [pagename] => api/1.1/statuses/lookup.json
4017     [id] => 605138389168451584
4018     [include_cards] => true
4019     [cards_platform] => Android-12
4020     [include_entities] => true
4021     [include_my_retweet] => 1
4022     [include_rts] => 1
4023     [include_reply_count] => true
4024     [include_descendent_reply_count] => true
4025 (?)
4026
4027
4028 Not implemented by now:
4029 statuses/retweets_of_me
4030 friendships/create
4031 friendships/destroy
4032 friendships/exists
4033 friendships/show
4034 account/update_location
4035 account/update_profile_background_image
4036 account/update_profile_image
4037 blocks/create
4038 blocks/destroy
4039 friendica/profile/update
4040 friendica/profile/create
4041 friendica/profile/delete
4042
4043 Not implemented in status.net:
4044 statuses/retweeted_to_me
4045 statuses/retweeted_by_me
4046 direct_messages/destroy
4047 account/end_session
4048 account/update_delivery_device
4049 notifications/follow
4050 notifications/leave
4051 blocks/exists
4052 blocks/blocking
4053 lists
4054 */