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