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