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