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