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