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