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