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