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