]> git.mxchange.org Git - friendica.git/blob - include/api.php
API: Several improvements to make the api more compatible
[friendica.git] / include / api.php
1 <?php
2 /* To-Do:
3  - Automatically detect if incoming data is HTML or BBCode
4 */
5         require_once("include/bbcode.php");
6         require_once("include/datetime.php");
7         require_once("include/conversation.php");
8         require_once("include/oauth.php");
9         require_once("include/html2plain.php");
10         /*
11          * Twitter-Like API
12          *
13          */
14
15         $API = Array();
16         $called_api = Null;
17
18         function api_user() {
19           // It is not sufficient to use local_user() to check whether someone is allowed to use the API,
20           // because this will open CSRF holes (just embed an image with src=friendicasite.com/api/statuses/update?status=CSRF
21           // into a page, and visitors will post something without noticing it).
22           // Instead, use this function.
23           if ($_SESSION["allow_api"])
24             return local_user();
25
26           return false;
27         }
28
29         function api_date($str){
30                 //Wed May 23 06:01:13 +0000 2007
31                 return datetime_convert('UTC', 'UTC', $str, "D M d H:i:s +0000 Y" );
32         }
33
34
35         function api_register_func($path, $func, $auth=false){
36                 global $API;
37                 $API[$path] = array('func'=>$func,
38                                                         'auth'=>$auth);
39         }
40
41         /**
42          * Simple HTTP Login
43          */
44
45         function api_login(&$a){
46                 // login with oauth
47                 try{
48                         $oauth = new FKOAuth1();
49                         list($consumer,$token) = $oauth->verify_request(OAuthRequest::from_request());
50                         if (!is_null($token)){
51                                 $oauth->loginUser($token->uid);
52                                 call_hooks('logged_in', $a->user);
53                                 return;
54                         }
55                         echo __file__.__line__.__function__."<pre>"; var_dump($consumer, $token); die();
56                 }catch(Exception $e){
57                         logger(__file__.__line__.__function__."\n".$e);
58                         //die(__file__.__line__.__function__."<pre>".$e); die();
59                 }
60
61
62
63                 // workaround for HTTP-auth in CGI mode
64                 if(x($_SERVER,'REDIRECT_REMOTE_USER')) {
65                         $userpass = base64_decode(substr($_SERVER["REDIRECT_REMOTE_USER"],6)) ;
66                         if(strlen($userpass)) {
67                                 list($name, $password) = explode(':', $userpass);
68                                 $_SERVER['PHP_AUTH_USER'] = $name;
69                                 $_SERVER['PHP_AUTH_PW'] = $password;
70                         }
71                 }
72
73                 if (!isset($_SERVER['PHP_AUTH_USER'])) {
74                         logger('API_login: ' . print_r($_SERVER,true), LOGGER_DEBUG);
75                         header('WWW-Authenticate: Basic realm="Friendica"');
76                         header('HTTP/1.0 401 Unauthorized');
77                         die((api_error(&$a, 'json', "This api requires login")));
78
79                         //die('This api requires login');
80                 }
81
82                 $user = $_SERVER['PHP_AUTH_USER'];
83                 $encrypted = hash('whirlpool',trim($_SERVER['PHP_AUTH_PW']));
84
85
86                 /**
87                  *  next code from mod/auth.php. needs better solution
88                  */
89
90                 // process normal login request
91
92                 $r = q("SELECT * FROM `user` WHERE ( `email` = '%s' OR `nickname` = '%s' )
93                         AND `password` = '%s' AND `blocked` = 0 AND `account_expired` = 0 AND `account_removed` = 0 AND `verified` = 1 LIMIT 1",
94                         dbesc(trim($user)),
95                         dbesc(trim($user)),
96                         dbesc($encrypted)
97                 );
98                 if(count($r)){
99                         $record = $r[0];
100                 } else {
101                    logger('API_login failure: ' . print_r($_SERVER,true), LOGGER_DEBUG);
102                     header('WWW-Authenticate: Basic realm="Friendica"');
103                     header('HTTP/1.0 401 Unauthorized');
104                     die('This api requires login');
105                 }
106
107                 require_once('include/security.php');
108                 authenticate_success($record); $_SESSION["allow_api"] = true;
109
110                 call_hooks('logged_in', $a->user);
111
112         }
113
114         /**************************
115          *  MAIN API ENTRY POINT  *
116          **************************/
117         function api_call(&$a){
118                 GLOBAL $API, $called_api;
119
120                 // preset
121                 $type="json";
122
123                 foreach ($API as $p=>$info){
124                         if (strpos($a->query_string, $p)===0){
125                                 $called_api= explode("/",$p);
126                                 //unset($_SERVER['PHP_AUTH_USER']);
127                                 if ($info['auth']===true && api_user()===false) {
128                                                 api_login($a);
129                                 }
130
131                                 load_contact_links(api_user());
132
133                                 logger('API call for ' . $a->user['username'] . ': ' . $a->query_string);
134                                 logger('API parameters: ' . print_r($_REQUEST,true));
135                                 $type="json";
136                                 if (strpos($a->query_string, ".xml")>0) $type="xml";
137                                 if (strpos($a->query_string, ".json")>0) $type="json";
138                                 if (strpos($a->query_string, ".rss")>0) $type="rss";
139                                 if (strpos($a->query_string, ".atom")>0) $type="atom";
140                                 if (strpos($a->query_string, ".as")>0) $type="as";
141
142                                 $r = call_user_func($info['func'], $a, $type);
143                                 if ($r===false) return;
144
145                                 switch($type){
146                                         case "xml":
147                                                 $r = mb_convert_encoding($r, "UTF-8",mb_detect_encoding($r));
148                                                 header ("Content-Type: text/xml");
149                                                 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
150                                                 break;
151                                         case "json":
152                                                 header ("Content-Type: application/json");
153                                                 foreach($r as $rr)
154                                                     return json_encode($rr);
155                                                 break;
156                                         case "rss":
157                                                 header ("Content-Type: application/rss+xml");
158                                                 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
159                                                 break;
160                                         case "atom":
161                                                 header ("Content-Type: application/atom+xml");
162                                                 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
163                                                 break;
164                                         case "as":
165                                                 //header ("Content-Type: application/json");
166                                                 //foreach($r as $rr)
167                                                 //    return json_encode($rr);
168                                                 return json_encode($r);
169                                                 break;
170
171                                 }
172                                 //echo "<pre>"; var_dump($r); die();
173                         }
174                 }
175                 header("HTTP/1.1 404 Not Found");
176                 logger('API call not implemented: '.$a->query_string." - ".print_r($_REQUEST,true));
177                 return(api_error(&$a, $type, "not implemented"));
178
179         }
180
181         function api_error(&$a, $type, $error) {
182                 $r = "<status><error>".$error."</error><request>".$a->query_string."</request></status>";
183                 switch($type){
184                         case "xml":
185                                 header ("Content-Type: text/xml");
186                                 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
187                                 break;
188                         case "json":
189                                 header ("Content-Type: application/json");
190                                 return json_encode(array('error' => $error, 'request' => $a->query_string));
191                                 break;
192                         case "rss":
193                                 header ("Content-Type: application/rss+xml");
194                                 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
195                                 break;
196                         case "atom":
197                                 header ("Content-Type: application/atom+xml");
198                                 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
199                                 break;
200                 }
201         }
202
203         /**
204          * RSS extra info
205          */
206         function api_rss_extra(&$a, $arr, $user_info){
207                 if (is_null($user_info)) $user_info = api_get_user($a);
208                 $arr['$user'] = $user_info;
209                 $arr['$rss'] = array(
210                         'alternate' => $user_info['url'],
211                         'self' => $a->get_baseurl(). "/". $a->query_string,
212                         'base' => $a->get_baseurl(),
213                         'updated' => api_date(null),
214                         'atom_updated' => datetime_convert('UTC','UTC','now',ATOM_TIME),
215                         'language' => $user_info['language'],
216                         'logo'  => $a->get_baseurl()."/images/friendica-32.png",
217                 );
218
219                 return $arr;
220         }
221
222
223         /**
224          * Unique contact to contact url.
225          */
226         function api_unique_id_to_url($id){
227                 $r = q("SELECT url FROM unique_contacts WHERE id=%d LIMIT 1",
228                         intval($id));
229                 if ($r)
230                         return ($r[0]["url"]);
231                 else
232                         return false;
233         }
234
235         /**
236          * Returns user info array.
237          */
238         function api_get_user(&$a, $contact_id = Null, $type = "json"){
239                 global $called_api;
240                 $user = null;
241                 $extra_query = "";
242                 $url = "";
243                 $nick = "";
244
245                 logger("api_get_user: Fetching user data for user ".$contact_id, LOGGER_DEBUG);
246
247                 // Searching for contact URL
248                 if(!is_null($contact_id) AND (intval($contact_id) == 0)){
249                         $user = dbesc(normalise_link($contact_id));
250                         $url = $user;
251                         $extra_query = "AND `contact`.`nurl` = '%s' ";
252                         if (api_user()!==false)  $extra_query .= "AND `contact`.`uid`=".intval(api_user());
253                 }
254
255                 // Searching for unique contact id
256                 if(!is_null($contact_id) AND (intval($contact_id) != 0)){
257                         $user = dbesc(api_unique_id_to_url($contact_id));
258
259                         if ($user == "")
260                                 die(api_error($a, $type, t("User not found.")));
261
262                         $url = $user;
263                         $extra_query = "AND `contact`.`nurl` = '%s' ";
264                         if (api_user()!==false)  $extra_query .= "AND `contact`.`uid`=".intval(api_user());
265                 }
266
267                 if(is_null($user) && x($_GET, 'user_id')) {
268                         $user = dbesc(api_unique_id_to_url($_GET['user_id']));
269
270                         if ($user == "")
271                                 die(api_error($a, $type, t("User not found.")));
272
273                         $url = $user;
274                         $extra_query = "AND `contact`.`nurl` = '%s' ";
275                         if (api_user()!==false)  $extra_query .= "AND `contact`.`uid`=".intval(api_user());
276                 }
277                 if(is_null($user) && x($_GET, 'screen_name')) {
278                         $user = dbesc($_GET['screen_name']);
279                         $nick = $user;
280                         $extra_query = "AND `contact`.`nick` = '%s' ";
281                         if (api_user()!==false)  $extra_query .= "AND `contact`.`uid`=".intval(api_user());
282                 }
283
284                 if (is_null($user) AND ($a->argc > (count($called_api)-1)) AND (count($called_api) > 0)){
285                         $argid = count($called_api);
286                         list($user, $null) = explode(".",$a->argv[$argid]);
287                         if(is_numeric($user)){
288                                 $user = dbesc(api_unique_id_to_url($user));
289
290                                 if ($user == "")
291                                         return false;
292
293                                 $url = $user;
294                                 $extra_query = "AND `contact`.`nurl` = '%s' ";
295                                 if (api_user()!==false)  $extra_query .= "AND `contact`.`uid`=".intval(api_user());
296                         } else {
297                                 $user = dbesc($user);
298                                 $nick = $user;
299                                 $extra_query = "AND `contact`.`nick` = '%s' ";
300                                 if (api_user()!==false)  $extra_query .= "AND `contact`.`uid`=".intval(api_user());
301                         }
302                 }
303
304                 if (!$user) {
305                         if (api_user()===false) {
306                                 api_login($a); return False;
307                         } else {
308                                 $user = $_SESSION['uid'];
309                                 $extra_query = "AND `contact`.`uid` = %d AND `contact`.`self` = 1 ";
310                         }
311
312                 }
313
314                 logger('api_user: ' . $extra_query . ', user: ' . $user);
315                 // user info
316                 $uinfo = q("SELECT *, `contact`.`id` as `cid` FROM `contact`
317                                 WHERE 1
318                                 $extra_query",
319                                 $user
320                 );
321
322                 // Selecting the id by priority, friendica first
323                 api_best_nickname($uinfo);
324
325                 // if the contact wasn't found, fetch it from the unique contacts
326                 if (count($uinfo)==0) {
327                         $r = array();
328
329                         if ($url != "")
330                                 $r = q("SELECT * FROM unique_contacts WHERE url='%s' LIMIT 1", $url);
331                         elseif ($nick != "")
332                                 $r = q("SELECT * FROM unique_contacts WHERE nick='%s' LIMIT 1", $nick);
333
334                         if ($r) {
335                                 // If no nick where given, extract it from the address
336                                 if (($r[0]['nick'] == "") OR ($r[0]['name'] == $r[0]['nick']))
337                                         $r[0]['nick'] = api_get_nick($r[0]["url"]);
338
339                                 $ret = array(
340                                         'id' => $r[0]["id"],
341                                         'name' => $r[0]["name"],
342                                         'screen_name' => (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']),
343                                         'location' => NULL,
344                                         'description' => NULL,
345                                         'profile_image_url' => $r[0]["avatar"],
346                                         'profile_image_url_https' => $r[0]["avatar"],
347                                         'url' => $r[0]["url"],
348                                         'protected' => false,
349                                         'followers_count' => 0,
350                                         'friends_count' => 0,
351                                         'created_at' => api_date(0),
352                                         'favourites_count' => 0,
353                                         'utc_offset' => 0,
354                                         'time_zone' => 'UTC',
355                                         'statuses_count' => 0,
356                                         'following' => false,
357                                         'verified' => false,
358                                         'statusnet_blocking' => false,
359                                         'notifications' => false,
360                                         'statusnet_profile_url' => $r[0]["url"],
361                                         'uid' => 0,
362                                         'cid' => 0,
363                                         'self' => 0,
364                                         'network' => '',
365                                 );
366
367                                 return $ret;
368                         } else
369                                 die(api_error($a, $type, t("User not found.")));
370
371                 }
372
373                 if($uinfo[0]['self']) {
374                         $usr = q("select * from user where uid = %d limit 1",
375                                 intval(api_user())
376                         );
377                         $profile = q("select * from profile where uid = %d and `is-default` = 1 limit 1",
378                                 intval(api_user())
379                         );
380
381                         // count public wall messages
382                         $r = q("SELECT COUNT(`id`) as `count` FROM `item` USE INDEX (uid, type)
383                                         WHERE  `uid` = %d
384                                         AND `type`='wall'
385                                         AND `allow_cid`='' AND `allow_gid`='' AND `deny_cid`='' AND `deny_gid`=''",
386                                         intval($uinfo[0]['uid'])
387                         );
388                         $countitms = $r[0]['count'];
389                 }
390                 else {
391                         $r = q("SELECT COUNT(`id`) as `count` FROM `item`
392                                         WHERE  `contact-id` = %d
393                                         AND `allow_cid`='' AND `allow_gid`='' AND `deny_cid`='' AND `deny_gid`=''",
394                                         intval($uinfo[0]['id'])
395                         );
396                         $countitms = $r[0]['count'];
397                 }
398
399                 // count friends
400                 $r = q("SELECT COUNT(`id`) as `count` FROM `contact`
401                                 WHERE  `uid` = %d AND `rel` IN ( %d, %d )
402                                 AND `self`=0 AND `blocked`=0 AND `pending`=0 AND `hidden`=0",
403                                 intval($uinfo[0]['uid']),
404                                 intval(CONTACT_IS_SHARING),
405                                 intval(CONTACT_IS_FRIEND)
406                 );
407                 $countfriends = $r[0]['count'];
408
409                 $r = q("SELECT COUNT(`id`) as `count` FROM `contact`
410                                 WHERE  `uid` = %d AND `rel` IN ( %d, %d )
411                                 AND `self`=0 AND `blocked`=0 AND `pending`=0 AND `hidden`=0",
412                                 intval($uinfo[0]['uid']),
413                                 intval(CONTACT_IS_FOLLOWER),
414                                 intval(CONTACT_IS_FRIEND)
415                 );
416                 $countfollowers = $r[0]['count'];
417
418                 $r = q("SELECT count(`id`) as `count` FROM item where starred = 1 and uid = %d and deleted = 0",
419                         intval($uinfo[0]['uid'])
420                 );
421                 $starred = $r[0]['count'];
422
423
424                 if(! $uinfo[0]['self']) {
425                         $countfriends = 0;
426                         $countfollowers = 0;
427                         $starred = 0;
428                 }
429
430                 // Add a nick if it isn't present there
431                 if (($uinfo[0]['nick'] == "") OR ($uinfo[0]['name'] == $uinfo[0]['nick'])) {
432                         $uinfo[0]['nick'] = api_get_nick($uinfo[0]["url"]);
433                         //if ($uinfo[0]['nick'] != "")
434                         //      q("UPDATE contact SET nick = '%s' WHERE id = %d",
435                         //              dbesc($uinfo[0]['nick']), intval($uinfo[0]["id"]));
436                 }
437
438                 // Fetching unique id
439                 $r = q("SELECT id FROM unique_contacts WHERE url='%s' LIMIT 1", dbesc(normalise_link($uinfo[0]['url'])));
440
441                 // If not there, then add it
442                 if (count($r) == 0) {
443                         q("INSERT INTO unique_contacts (url, name, nick, avatar) VALUES ('%s', '%s', '%s', '%s')",
444                                 dbesc(normalise_link($uinfo[0]['url'])), dbesc($uinfo[0]['name']),dbesc($uinfo[0]['nick']), dbesc($uinfo[0]['micro']));
445
446                         $r = q("SELECT id FROM unique_contacts WHERE url='%s' LIMIT 1", dbesc(normalise_link($uinfo[0]['url'])));
447                 }
448
449                 $ret = Array(
450                         'id' => intval($r[0]['id']),
451                         'name' => (($uinfo[0]['name']) ? $uinfo[0]['name'] : $uinfo[0]['nick']),
452                         'screen_name' => (($uinfo[0]['nick']) ? $uinfo[0]['nick'] : $uinfo[0]['name']),
453                         'location' => ($usr) ? $usr[0]['default-location'] : NULL,
454                         'description' => (($profile) ? $profile[0]['pdesc'] : NULL),
455                         'profile_image_url' => $uinfo[0]['micro'],
456                         'profile_image_url_https' => $uinfo[0]['micro'],
457                         'url' => $uinfo[0]['url'],
458                         'protected' => false,
459                         'followers_count' => intval($countfollowers),
460                         'friends_count' => intval($countfriends),
461                         'created_at' => api_date($uinfo[0]['name-date']),
462                         'favourites_count' => intval($starred),
463                         'utc_offset' => "0", // To-Do
464                         'time_zone' => 'UTC', // To-Do $uinfo[0]['timezone'],
465                         'statuses_count' => intval($countitms),
466                         'following' => true, //#XXX: fix me
467                         'verified' => true, //#XXX: fix me
468                         'statusnet_blocking' => false,
469                         'notifications' => false,
470                         'statusnet_profile_url' => $a->get_baseurl()."/contacts/".$uinfo[0]['cid'],
471                         'uid' => intval($uinfo[0]['uid']),
472                         'cid' => intval($uinfo[0]['cid']),
473                         'self' => $uinfo[0]['self'],
474                         'network' => $uinfo[0]['network'],
475                 );
476
477                 return $ret;
478
479         }
480
481         function api_item_get_user(&$a, $item) {
482
483                 $author = q("SELECT * FROM unique_contacts WHERE url='%s' LIMIT 1",
484                         dbesc(normalise_link($item['author-link'])));
485
486                 if (count($author) == 0) {
487                         q("INSERT INTO unique_contacts (url, name, avatar) VALUES ('%s', '%s', '%s')",
488                         dbesc(normalise_link($item["author-link"])), dbesc($item["author-name"]), dbesc($item["author-avatar"]));
489
490                         $author = q("SELECT id FROM unique_contacts WHERE url='%s' LIMIT 1",
491                                 dbesc(normalise_link($item['author-link'])));
492                 } else if ($item["author-link"].$item["author-name"] != $author[0]["url"].$author[0]["name"]) {
493                         q("UPDATE unique_contacts SET name = '%s', avatar = '%s' WHERE url = '%s'",
494                         dbesc($item["author-name"]), dbesc($item["author-avatar"]), dbesc(normalise_link($item["author-link"])));
495                 }
496
497                 $owner = q("SELECT id FROM unique_contacts WHERE url='%s' LIMIT 1",
498                         dbesc(normalise_link($item['owner-link'])));
499
500                 if (count($owner) == 0) {
501                         q("INSERT INTO unique_contacts (url, name, avatar) VALUES ('%s', '%s', '%s')",
502                         dbesc(normalise_link($item["owner-link"])), dbesc($item["owner-name"]), dbesc($item["owner-avatar"]));
503
504                         $owner = q("SELECT id FROM unique_contacts WHERE url='%s' LIMIT 1",
505                                 dbesc(normalise_link($item['owner-link'])));
506                 } else if ($item["owner-link"].$item["owner-name"] != $owner[0]["url"].$owner[0]["name"]) {
507                         q("UPDATE unique_contacts SET name = '%s', avatar = '%s' WHERE url = '%s'",
508                         dbesc($item["owner-name"]), dbesc($item["owner-avatar"]), dbesc(normalise_link($item["owner-link"])));
509                 }
510
511                 // Comments in threads may appear as wall-to-wall postings.
512                 // So only take the owner at the top posting.
513                 if ($item["id"] == $item["parent"])
514                         return api_get_user($a,$item["owner-link"]);
515                 else
516                         return api_get_user($a,$item["author-link"]);
517         }
518
519
520         /**
521          *  load api $templatename for $type and replace $data array
522          */
523         function api_apply_template($templatename, $type, $data){
524
525                 $a = get_app();
526
527                 switch($type){
528                         case "atom":
529                         case "rss":
530                         case "xml":
531                                 $data = array_xmlify($data);
532                                 $tpl = get_markup_template("api_".$templatename."_".$type.".tpl");
533                                 if(! $tpl) {
534                                         header ("Content-Type: text/xml");
535                                         echo '<?xml version="1.0" encoding="UTF-8"?>'."\n".'<status><error>not implemented</error></status>';
536                                         killme();
537                                 }
538                                 $ret = replace_macros($tpl, $data);
539                                 break;
540                         case "json":
541                                 $ret = $data;
542                                 break;
543                 }
544                 return $ret;
545         }
546
547         /**
548          ** TWITTER API
549          */
550
551         /**
552          * Returns an HTTP 200 OK response code and a representation of the requesting user if authentication was successful;
553          * returns a 401 status code and an error message if not.
554          * http://developer.twitter.com/doc/get/account/verify_credentials
555          */
556         function api_account_verify_credentials(&$a, $type){
557                 if (api_user()===false) return false;
558
559                 unset($_REQUEST["user_id"]);
560                 unset($_GET["user_id"]);
561
562                 unset($_REQUEST["screen_name"]);
563                 unset($_GET["screen_name"]);
564
565                 $skip_status = (x($_REQUEST,'skip_status')?$_REQUEST['skip_status']:false);
566
567                 $user_info = api_get_user($a);
568
569                 // "verified" isn't used here in the standard
570                 unset($user_info["verified"]);
571
572                 // - Adding last status
573                 if (!$skip_status) {
574                         $user_info["status"] = api_status_show($a,"raw");
575                         if (!count($user_info["status"]))
576                                 unset($user_info["status"]);
577                         else
578                                 unset($user_info["status"]["user"]);
579                 }
580
581                 // "cid", "uid" and "self" are only needed for some internal stuff, so remove it from here
582                 unset($user_info["cid"]);
583                 unset($user_info["uid"]);
584                 unset($user_info["self"]);
585
586                 return api_apply_template("user", $type, array('$user' => $user_info));
587
588         }
589         api_register_func('api/account/verify_credentials','api_account_verify_credentials', true);
590
591
592         /**
593          * get data from $_POST or $_GET
594          */
595         function requestdata($k){
596                 if (isset($_POST[$k])){
597                         return $_POST[$k];
598                 }
599                 if (isset($_GET[$k])){
600                         return $_GET[$k];
601                 }
602                 return null;
603         }
604
605 /*Waitman Gobble Mod*/
606         function api_statuses_mediap(&$a, $type) {
607                 if (api_user()===false) {
608                         logger('api_statuses_update: no user');
609                         return false;
610                 }
611                 $user_info = api_get_user($a);
612
613                 $_REQUEST['type'] = 'wall';
614                 $_REQUEST['profile_uid'] = api_user();
615                 $_REQUEST['api_source'] = true;
616                 $txt = requestdata('status');
617                 //$txt = urldecode(requestdata('status'));
618
619                 require_once('library/HTMLPurifier.auto.php');
620                 require_once('include/html2bbcode.php');
621
622                 if((strpos($txt,'<') !== false) || (strpos($txt,'>') !== false)) {
623                         $txt = html2bb_video($txt);
624                         $config = HTMLPurifier_Config::createDefault();
625                         $config->set('Cache.DefinitionImpl', null);
626                         $purifier = new HTMLPurifier($config);
627                         $txt = $purifier->purify($txt);
628                 }
629                 $txt = html2bbcode($txt);
630
631                 $a->argv[1]=$user_info['screen_name']; //should be set to username?
632
633                 $_REQUEST['hush']='yeah'; //tell wall_upload function to return img info instead of echo
634                 require_once('mod/wall_upload.php');
635                 $bebop = wall_upload_post($a);
636
637                 //now that we have the img url in bbcode we can add it to the status and insert the wall item.
638                 $_REQUEST['body']=$txt."\n\n".$bebop;
639                 require_once('mod/item.php');
640                 item_post($a);
641
642                 // this should output the last post (the one we just posted).
643                 return api_status_show($a,$type);
644         }
645         api_register_func('api/statuses/mediap','api_statuses_mediap', true);
646 /*Waitman Gobble Mod*/
647
648
649         function api_statuses_update(&$a, $type) {
650                 if (api_user()===false) {
651                         logger('api_statuses_update: no user');
652                         return false;
653                 }
654                 $user_info = api_get_user($a);
655
656                 // convert $_POST array items to the form we use for web posts.
657
658                 // logger('api_post: ' . print_r($_POST,true));
659
660                 if(requestdata('htmlstatus')) {
661                         require_once('library/HTMLPurifier.auto.php');
662                         require_once('include/html2bbcode.php');
663
664                         $txt = requestdata('htmlstatus');
665                         if((strpos($txt,'<') !== false) || (strpos($txt,'>') !== false)) {
666
667                                 $txt = html2bb_video($txt);
668
669                                 $config = HTMLPurifier_Config::createDefault();
670                                 $config->set('Cache.DefinitionImpl', null);
671
672
673                                 $purifier = new HTMLPurifier($config);
674                                 $txt = $purifier->purify($txt);
675
676                                 $_REQUEST['body'] = html2bbcode($txt);
677                         }
678
679                 }
680                 else
681                         $_REQUEST['body'] = requestdata('status');
682
683                 $_REQUEST['title'] = requestdata('title');
684
685                 $parent = requestdata('in_reply_to_status_id');
686                 if(ctype_digit($parent))
687                         $_REQUEST['parent'] = $parent;
688                 else
689                         $_REQUEST['parent_uri'] = $parent;
690
691                 if(requestdata('lat') && requestdata('long'))
692                         $_REQUEST['coord'] = sprintf("%s %s",requestdata('lat'),requestdata('long'));
693                 $_REQUEST['profile_uid'] = api_user();
694
695                 if($parent)
696                         $_REQUEST['type'] = 'net-comment';
697                 else {
698                         $_REQUEST['type'] = 'wall';
699                         if(x($_FILES,'media')) {
700                                 // upload the image if we have one
701                                 $_REQUEST['hush']='yeah'; //tell wall_upload function to return img info instead of echo
702                                 require_once('mod/wall_upload.php');
703                                 $media = wall_upload_post($a);
704                                 if(strlen($media)>0)
705                                         $_REQUEST['body'] .= "\n\n".$media;
706                         }
707                 }
708
709                 // set this so that the item_post() function is quiet and doesn't redirect or emit json
710
711                 $_REQUEST['api_source'] = true;
712
713                 // call out normal post function
714
715                 require_once('mod/item.php');
716                 item_post($a);
717
718                 // this should output the last post (the one we just posted).
719                 return api_status_show($a,$type);
720         }
721         api_register_func('api/statuses/update','api_statuses_update', true);
722         api_register_func('api/statuses/update_with_media','api_statuses_update', true);
723
724
725         function api_status_show(&$a, $type){
726                 $user_info = api_get_user($a);
727                 // get last public wall message
728                 $lastwall = q("SELECT `item`.*, `i`.`contact-id` as `reply_uid`, `c`.`nick` as `reply_author`, `i`.`author-link` AS `item-author`
729                                 FROM `item`, `contact`, `item` as `i`, `contact` as `c`
730                                 WHERE `item`.`contact-id` = %d AND `item`.`owner-link` = '%s'
731                                         AND `i`.`id` = `item`.`parent`
732                                         AND `contact`.`id`=`item`.`contact-id` AND `c`.`id`=`i`.`contact-id` AND `contact`.`self`=1
733                                         AND `item`.`type`!='activity'
734                                         AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''
735                                 ORDER BY `item`.`created` DESC
736                                 LIMIT 1",
737                                 intval($user_info['cid']),
738                                 dbesc($user_info['url'])
739                 );
740
741                 if (count($lastwall)>0){
742                         $lastwall = $lastwall[0];
743
744                         $in_reply_to_status_id = NULL;
745                         $in_reply_to_user_id = NULL;
746                         $in_reply_to_screen_name = NULL;
747                         if ($lastwall['parent']!=$lastwall['id']) {
748                                 $in_reply_to_status_id=$lastwall['parent'];
749                                 //$in_reply_to_user_id = $lastwall['reply_uid'];
750                                 //$in_reply_to_screen_name = $lastwall['reply_author'];
751
752                                 $r = q("SELECT * FROM unique_contacts WHERE `url` = '%s'", dbesc(normalise_link($lastwall['item-author'])));
753                                 if ($r) {
754                                         if ($r[0]['nick'] == "")
755                                                 $r[0]['nick'] = api_get_nick($r[0]["url"]);
756
757                                         $in_reply_to_screen_name = (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']);
758                                         $in_reply_to_user_id = $r[0]['id'];
759                                 }
760                         }
761                         $status_info = array(
762                                 'text' => trim(html2plain(bbcode(api_clean_plain_items($lastwall['body']), false, false, 2, true), 0)),
763                                 'truncated' => false,
764                                 'created_at' => api_date($lastwall['created']),
765                                 'in_reply_to_status_id' => $in_reply_to_status_id,
766                                 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
767                                 'id' => $lastwall['id'],
768                                 'in_reply_to_user_id' => $in_reply_to_user_id,
769                                 'in_reply_to_screen_name' => $in_reply_to_screen_name,
770                                 'geo' => NULL,
771                                 'favorited' => false,
772                                 // attachments
773                                 'user' => $user_info,
774                                 'statusnet_html'                => trim(bbcode($lastwall['body'], false, false)),
775                                 'statusnet_conversation_id'     => $lastwall['parent'],
776                         );
777
778                         if (($lastwall['item_network'] != "") AND ($status["source"] == 'web'))
779                                 $status_info["source"] = network_to_name($lastwall['item_network']);
780                         elseif (($lastwall['item_network'] != "") AND (network_to_name($lastwall['item_network']) != $status_info["source"]))
781                                 $status_info["source"] = trim($status_info["source"].' ('.network_to_name($lastwall['item_network']).')');
782
783                         // "cid", "uid" and "self" are only needed for some internal stuff, so remove it from here
784                         unset($status_info["user"]["cid"]);
785                         unset($status_info["user"]["uid"]);
786                         unset($status_info["user"]["self"]);
787                 }
788
789                 if ($type == "raw")
790                         return($status_info);
791
792                 return  api_apply_template("status", $type, array('$status' => $status_info));
793
794         }
795
796
797
798
799
800         /**
801          * Returns extended information of a given user, specified by ID or screen name as per the required id parameter.
802          * The author's most recent status will be returned inline.
803          * http://developer.twitter.com/doc/get/users/show
804          */
805         function api_users_show(&$a, $type){
806                 $user_info = api_get_user($a);
807
808                 $lastwall = q("SELECT `item`.*
809                                 FROM `item`, `contact`
810                                 WHERE `item`.`contact-id` = %d  AND `item`.`owner-link` = '%s'
811                                         AND `contact`.`id`=`item`.`contact-id`
812                                         AND `type`!='activity'
813                                         AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''
814                                 ORDER BY `created` DESC
815                                 LIMIT 1",
816                                 intval($user_info['cid']),
817                                 dbesc($user_info['url'])
818                 );
819
820                 if (count($lastwall)>0){
821                         $lastwall = $lastwall[0];
822
823                         $in_reply_to_status_id = NULL;
824                         $in_reply_to_user_id = NULL;
825                         $in_reply_to_screen_name = NULL;
826                         if ($lastwall['parent']!=$lastwall['id']) {
827                                 $reply = q("SELECT `item`.`id`, `item`.`contact-id` as `reply_uid`, `contact`.`nick` as `reply_author`, `item`.`author-link` AS `item-author`
828                                             FROM `item`,`contact` WHERE `contact`.`id`=`item`.`contact-id` AND `item`.`id` = %d", intval($lastwall['parent']));
829                                 if (count($reply)>0) {
830                                         $in_reply_to_status_id=$lastwall['parent'];
831                                         //$in_reply_to_user_id = $reply[0]['reply_uid'];
832                                         //$in_reply_to_screen_name = $reply[0]['reply_author'];
833                                         $r = q("SELECT * FROM unique_contacts WHERE `url` = '%s'", dbesc(normalise_link($reply[0]['item-author'])));
834                                         if ($r) {
835                                                 if ($r[0]['nick'] == "")
836                                                         $r[0]['nick'] = api_get_nick($r[0]["url"]);
837
838                                                 $in_reply_to_screen_name = (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']);
839                                                 $in_reply_to_user_id = $r[0]['id'];
840                                         }
841                                 }
842                         }
843                         $user_info['status'] = array(
844                                 'text' => trim(html2plain(bbcode(api_clean_plain_items($lastwall['body']), false, false, 2, true), 0)),
845                                 'truncated' => false,
846                                 'created_at' => api_date($lastwall['created']),
847                                 'in_reply_to_status_id' => $in_reply_to_status_id,
848                                 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
849                                 'id' => $lastwall['contact-id'],
850                                 'in_reply_to_user_id' => $in_reply_to_user_id,
851                                 'in_reply_to_screen_name' => $in_reply_to_screen_name,
852                                 'geo' => NULL,
853                                 'favorited' => false,
854                                 'statusnet_html'                => trim(bbcode($lastwall['body'], false, false)),
855                                 'statusnet_conversation_id'     => $lastwall['parent'],
856                         );
857
858                         if (($lastwall['item_network'] != "") AND ($user_info["status"]["source"] == 'web'))
859                                 $user_info["status"]["source"] = network_to_name($lastwall['item_network']);
860                         if (($lastwall['item_network'] != "") AND (network_to_name($lastwall['item_network']) != $user_info["status"]["source"]))
861                                 $user_info["status"]["source"] = trim($user_info["status"]["source"].' ('.network_to_name($lastwall['item_network']).')');
862
863                 }
864
865                 // "cid", "uid" and "self" are only needed for some internal stuff, so remove it from here
866                 unset($user_info["cid"]);
867                 unset($user_info["uid"]);
868                 unset($user_info["self"]);
869
870                 return  api_apply_template("user", $type, array('$user' => $user_info));
871
872         }
873         api_register_func('api/users/show','api_users_show');
874
875         /**
876          *
877          * http://developer.twitter.com/doc/get/statuses/home_timeline
878          *
879          * TODO: Optional parameters
880          * TODO: Add reply info
881          */
882         function api_statuses_home_timeline(&$a, $type){
883                 if (api_user()===false) return false;
884
885                 unset($_REQUEST["user_id"]);
886                 unset($_GET["user_id"]);
887
888                 unset($_REQUEST["screen_name"]);
889                 unset($_GET["screen_name"]);
890
891                 $user_info = api_get_user($a);
892                 // get last newtork messages
893
894
895                 // params
896                 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
897                 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
898                 if ($page<0) $page=0;
899                 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
900                 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
901                 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
902                 $exclude_replies = (x($_REQUEST,'exclude_replies')?1:0);
903                 $conversation_id = (x($_REQUEST,'conversation_id')?$_REQUEST['conversation_id']:0);
904
905                 $start = $page*$count;
906
907                 //$include_entities = (x($_REQUEST,'include_entities')?$_REQUEST['include_entities']:false);
908
909                 $sql_extra = '';
910                 if ($max_id > 0)
911                         $sql_extra .= ' AND `item`.`id` <= '.intval($max_id);
912                 if ($exclude_replies > 0)
913                         $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
914                 if ($conversation_id > 0)
915                         $sql_extra .= ' AND `item`.`parent` = '.intval($conversation_id);
916
917                 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
918                         `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
919                         `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
920                         `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
921                         FROM `item`, `contact`
922                         WHERE `item`.`uid` = %d
923                         AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
924                         AND `contact`.`id` = `item`.`contact-id`
925                         AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
926                         $sql_extra
927                         AND `item`.`id`>%d
928                         ORDER BY `item`.`received` DESC LIMIT %d ,%d ",
929                         //intval($user_info['uid']),
930                         intval(api_user()),
931                         intval($since_id),
932                         intval($start), intval($count)
933                 );
934
935                 $ret = api_format_items($r,$user_info);
936
937                 // We aren't going to try to figure out at the item, group, and page
938                 // level which items you've seen and which you haven't. If you're looking
939                 // at the network timeline just mark everything seen. 
940
941                 $r = q("UPDATE `item` SET `unseen` = 0 
942                         WHERE `unseen` = 1 AND `uid` = %d",
943                         //intval($user_info['uid'])
944                         intval(api_user())
945                 );
946
947
948                 $data = array('$statuses' => $ret);
949                 switch($type){
950                         case "atom":
951                         case "rss":
952                                 $data = api_rss_extra($a, $data, $user_info);
953                                 break;
954                         case "as":
955                                 $as = api_format_as($a, $ret, $user_info);
956                                 $as['title'] = $a->config['sitename']." Home Timeline";
957                                 $as['link']['url'] = $a->get_baseurl()."/".$user_info["screen_name"]."/all";
958                                 return($as);
959                                 break;
960                 }
961
962                 return  api_apply_template("timeline", $type, $data);
963         }
964         api_register_func('api/statuses/home_timeline','api_statuses_home_timeline', true);
965         api_register_func('api/statuses/friends_timeline','api_statuses_home_timeline', true);
966
967         function api_statuses_public_timeline(&$a, $type){
968                 if (api_user()===false) return false;
969
970                 $user_info = api_get_user($a);
971                 // get last newtork messages
972
973
974                 // params
975                 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
976                 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
977                 if ($page<0) $page=0;
978                 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
979                 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
980                 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
981                 $exclude_replies = (x($_REQUEST,'exclude_replies')?1:0);
982                 $conversation_id = (x($_REQUEST,'conversation_id')?$_REQUEST['conversation_id']:0);
983
984                 $start = $page*$count;
985
986                 //$include_entities = (x($_REQUEST,'include_entities')?$_REQUEST['include_entities']:false);
987
988                 if ($max_id > 0)
989                         $sql_extra = 'AND `item`.`id` <= '.intval($max_id);
990                 if ($exclude_replies > 0)
991                         $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
992                 if ($conversation_id > 0)
993                         $sql_extra .= ' AND `item`.`parent` = '.intval($conversation_id);
994
995                 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
996                         `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
997                         `contact`.`network`, `contact`.`thumb`, `contact`.`self`, `contact`.`writable`,
998                         `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`,
999                         `user`.`nickname`, `user`.`hidewall`
1000                         FROM `item` LEFT JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
1001                         LEFT JOIN `user` ON `user`.`uid` = `item`.`uid`
1002                         WHERE `item`.`visible` = 1 AND `item`.`deleted` = 0 and `item`.`moderated` = 0
1003                         AND `item`.`allow_cid` = ''  AND `item`.`allow_gid` = ''
1004                         AND `item`.`deny_cid`  = '' AND `item`.`deny_gid`  = ''
1005                         AND `item`.`private` = 0 AND `item`.`wall` = 1 AND `user`.`hidewall` = 0
1006                         AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1007                         $sql_extra
1008                         AND `item`.`id`>%d
1009                         ORDER BY `received` DESC LIMIT %d, %d ",
1010                         intval($since_id),
1011                         intval($start),
1012                         intval($count));
1013
1014                 $ret = api_format_items($r,$user_info);
1015
1016
1017                 $data = array('$statuses' => $ret);
1018                 switch($type){
1019                         case "atom":
1020                         case "rss":
1021                                 $data = api_rss_extra($a, $data, $user_info);
1022                                 break;
1023                         case "as":
1024                                 $as = api_format_as($a, $ret, $user_info);
1025                                 $as['title'] = $a->config['sitename']." Public Timeline";
1026                                 $as['link']['url'] = $a->get_baseurl()."/";
1027                                 return($as);
1028                                 break;
1029                 }
1030
1031                 return  api_apply_template("timeline", $type, $data);
1032         }
1033         api_register_func('api/statuses/public_timeline','api_statuses_public_timeline', true);
1034
1035         /**
1036          * 
1037          */
1038         function api_statuses_show(&$a, $type){
1039                 if (api_user()===false) return false;
1040
1041                 $user_info = api_get_user($a);
1042
1043                 // params
1044                 $id = intval($a->argv[3]);
1045
1046                 if ($id == 0)
1047                         $id = intval($_REQUEST["id"]);
1048
1049                 logger('API: api_statuses_show: '.$id);
1050
1051                 //$include_entities = (x($_REQUEST,'include_entities')?$_REQUEST['include_entities']:false);
1052                 $conversation = (x($_REQUEST,'conversation')?1:0);
1053
1054                 $sql_extra = '';
1055                 if ($conversation)
1056                         $sql_extra .= " AND `item`.`parent` = %d ORDER BY `received` ASC ";
1057                 else
1058                         $sql_extra .= " AND `item`.`id` = %d";
1059
1060                 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1061                         `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1062                         `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1063                         `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1064                         FROM `item`, `contact`
1065                         WHERE `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1066                         AND `contact`.`id` = `item`.`contact-id`
1067                         AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1068                         $sql_extra",
1069                         intval($id)
1070                 );
1071
1072                 if (!$r)
1073                         die(api_error($a, $type, t("There is no status with this id.")));
1074
1075                 $ret = api_format_items($r,$user_info);
1076
1077                 if ($conversation) {
1078                         $data = array('$statuses' => $ret);
1079                         return api_apply_template("timeline", $type, $data);
1080                 } else {
1081                         $data = array('$status' => $ret[0]);
1082                         /*switch($type){
1083                                 case "atom":
1084                                 case "rss":
1085                                         $data = api_rss_extra($a, $data, $user_info);
1086                         }*/
1087                         return  api_apply_template("status", $type, $data);
1088                 }
1089         }
1090         api_register_func('api/statuses/show','api_statuses_show', true);
1091
1092
1093         /**
1094          * 
1095          */
1096         function api_statuses_repeat(&$a, $type){
1097                 if (api_user()===false) return false;
1098
1099                 $user_info = api_get_user($a);
1100
1101                 // params
1102                 $id = intval($a->argv[3]);
1103
1104                 if ($id == 0)
1105                         $id = intval($_REQUEST["id"]);
1106
1107                 logger('API: api_statuses_repeat: '.$id);
1108
1109                 //$include_entities = (x($_REQUEST,'include_entities')?$_REQUEST['include_entities']:false);
1110
1111                 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`, `contact`.`nick` as `reply_author`,
1112                         `contact`.`name`, `contact`.`photo` as `reply_photo`, `contact`.`url` as `reply_url`, `contact`.`rel`,
1113                         `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1114                         `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1115                         FROM `item`, `contact`
1116                         WHERE `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1117                         AND `contact`.`id` = `item`.`contact-id`
1118                         AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1119                         $sql_extra
1120                         AND `item`.`id`=%d",
1121                         intval($id)
1122                 );
1123
1124                 if ($r[0]['body'] != "") {
1125                         if (!intval(get_config('system','old_share'))) {
1126                                 $post = "[share author='".str_replace("'", "&#039;", $r[0]['reply_author']).
1127                                                 "' profile='".$r[0]['reply_url'].
1128                                                 "' avatar='".$r[0]['reply_photo'].
1129                                                 "' link='".$r[0]['plink']."']";
1130
1131                                 $post .= $r[0]['body'];
1132                                 $post .= "[/share]";
1133                                 $_REQUEST['body'] = $post;
1134                         } else
1135                                 $_REQUEST['body'] = html_entity_decode("&#x2672; ", ENT_QUOTES, 'UTF-8')."[url=".$r[0]['reply_url']."]".$r[0]['reply_author']."[/url] \n".$r[0]['body'];
1136
1137                         $_REQUEST['profile_uid'] = api_user();
1138                         $_REQUEST['type'] = 'wall';
1139                         $_REQUEST['api_source'] = true;
1140
1141                         require_once('mod/item.php');
1142                         item_post($a);
1143                 }
1144
1145                 if ($type == 'xml')
1146                         $ok = "true";
1147                 else
1148                         $ok = "ok";
1149
1150                 return api_apply_template('test', $type, array('$ok' => $ok));
1151         }
1152         api_register_func('api/statuses/retweet','api_statuses_repeat', true);
1153
1154         /**
1155          * 
1156          */
1157         function api_statuses_destroy(&$a, $type){
1158                 if (api_user()===false) return false;
1159
1160                 $user_info = api_get_user($a);
1161
1162                 // params
1163                 $id = intval($a->argv[3]);
1164
1165                 if ($id == 0)
1166                         $id = intval($_REQUEST["id"]);
1167
1168                 logger('API: api_statuses_destroy: '.$id);
1169
1170                 require_once('include/items.php');
1171                 drop_item($id, false);
1172
1173                 if ($type == 'xml')
1174                         $ok = "true";
1175                 else
1176                         $ok = "ok";
1177
1178                 return api_apply_template('test', $type, array('$ok' => $ok));
1179         }
1180         api_register_func('api/statuses/destroy','api_statuses_destroy', true);
1181
1182         /**
1183          * 
1184          * http://developer.twitter.com/doc/get/statuses/mentions
1185          * 
1186          */
1187         function api_statuses_mentions(&$a, $type){
1188                 if (api_user()===false) return false;
1189
1190                 unset($_REQUEST["user_id"]);
1191                 unset($_GET["user_id"]);
1192
1193                 unset($_REQUEST["screen_name"]);
1194                 unset($_GET["screen_name"]);
1195
1196                 $user_info = api_get_user($a);
1197                 // get last newtork messages
1198
1199
1200                 // params
1201                 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1202                 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1203                 if ($page<0) $page=0;
1204                 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1205                 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1206                 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1207
1208                 $start = $page*$count;
1209
1210                 //$include_entities = (x($_REQUEST,'include_entities')?$_REQUEST['include_entities']:false);
1211
1212                 // Ugly code - should be changed
1213                 $myurl = $a->get_baseurl() . '/profile/'. $a->user['nickname'];
1214                 $myurl = substr($myurl,strpos($myurl,'://')+3);
1215                 //$myurl = str_replace(array('www.','.'),array('','\\.'),$myurl);
1216                 $myurl = str_replace('www.','',$myurl);
1217                 $diasp_url = str_replace('/profile/','/u/',$myurl);
1218
1219                 $sql_extra .= sprintf(" AND `item`.`parent` IN (SELECT distinct(`parent`) from item where `author-link` IN ('https://%s', 'http://%s') OR `mention`)",
1220                         dbesc(protect_sprintf($myurl)),
1221                         dbesc(protect_sprintf($myurl))
1222                 );
1223
1224                 if ($max_id > 0)
1225                         $sql_extra .= ' AND `item`.`id` <= '.intval($max_id);
1226
1227                 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1228                         `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1229                         `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1230                         `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1231                         FROM `item`, `contact`
1232                         WHERE `item`.`uid` = %d
1233                         AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1234                         AND `contact`.`id` = `item`.`contact-id`
1235                         AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1236                         $sql_extra
1237                         AND `item`.`id`>%d
1238                         ORDER BY `item`.`received` DESC LIMIT %d ,%d ",
1239                         //intval($user_info['uid']),
1240                         intval(api_user()),
1241                         intval($since_id),
1242                         intval($start), intval($count)
1243                 );
1244
1245                 $ret = api_format_items($r,$user_info);
1246
1247
1248                 $data = array('$statuses' => $ret);
1249                 switch($type){
1250                         case "atom":
1251                         case "rss":
1252                                 $data = api_rss_extra($a, $data, $user_info);
1253                                 break;
1254                         case "as":
1255                                 $as = api_format_as($a, $ret, $user_info);
1256                                 $as["title"] = $a->config['sitename']." Mentions";
1257                                 $as['link']['url'] = $a->get_baseurl()."/";
1258                                 return($as);
1259                                 break;
1260                 }
1261
1262                 return  api_apply_template("timeline", $type, $data);
1263         }
1264         api_register_func('api/statuses/mentions','api_statuses_mentions', true);
1265         api_register_func('api/statuses/replies','api_statuses_mentions', true);
1266
1267
1268         function api_statuses_user_timeline(&$a, $type){
1269                 if (api_user()===false) return false;
1270
1271                 $user_info = api_get_user($a);
1272                 // get last network messages
1273
1274                 logger("api_statuses_user_timeline: api_user: ". api_user() .
1275                            "\nuser_info: ".print_r($user_info, true) .
1276                            "\n_REQUEST:  ".print_r($_REQUEST, true),
1277                            LOGGER_DEBUG);
1278
1279                 // params
1280                 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1281                 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1282                 if ($page<0) $page=0;
1283                 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1284                 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1285                 $exclude_replies = (x($_REQUEST,'exclude_replies')?1:0);
1286                 $conversation_id = (x($_REQUEST,'conversation_id')?$_REQUEST['conversation_id']:0);
1287
1288                 $start = $page*$count;
1289
1290                 $sql_extra = '';
1291                 if ($user_info['self']==1)
1292                         $sql_extra .= " AND `item`.`wall` = 1 ";
1293
1294                 if ($exclude_replies > 0)
1295                         $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
1296                 if ($conversation_id > 0)
1297                         $sql_extra .= ' AND `item`.`parent` = '.intval($conversation_id);
1298
1299                 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1300                         `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1301                         `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1302                         `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1303                         FROM `item`, `contact`
1304                         WHERE `item`.`uid` = %d
1305                         AND `item`.`contact-id` = %d
1306                         AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1307                         AND `contact`.`id` = `item`.`contact-id`
1308                         AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1309                         $sql_extra
1310                         AND `item`.`id`>%d
1311                         ORDER BY `item`.`received` DESC LIMIT %d ,%d ",
1312                         intval(api_user()),
1313                         intval($user_info['cid']),
1314                         intval($since_id),
1315                         intval($start), intval($count)
1316                 );
1317
1318                 $ret = api_format_items($r,$user_info, true);
1319
1320                 $data = array('$statuses' => $ret);
1321                 switch($type){
1322                         case "atom":
1323                         case "rss":
1324                                 $data = api_rss_extra($a, $data, $user_info);
1325                 }
1326
1327                 return  api_apply_template("timeline", $type, $data);
1328         }
1329
1330         api_register_func('api/statuses/user_timeline','api_statuses_user_timeline', true);
1331
1332
1333         function api_favorites(&$a, $type){
1334                 global $called_api;
1335
1336                 if (api_user()===false) return false;
1337
1338                 $called_api= array();
1339
1340                 $user_info = api_get_user($a);
1341
1342                 // in friendica starred item are private
1343                 // return favorites only for self
1344                 logger('api_favorites: self:' . $user_info['self']);
1345
1346                 if ($user_info['self']==0) {
1347                         $ret = array();
1348                 } else {
1349                         $sql_extra = "";
1350
1351                         // params
1352                         $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1353                         $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1354                         $count = (x($_GET,'count')?$_GET['count']:20);
1355                         $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1356                         if ($page<0) $page=0;
1357
1358                         $start = $page*$count;
1359
1360                         if ($max_id > 0)
1361                                 $sql_extra .= ' AND `item`.`id` <= '.intval($max_id);
1362
1363                         $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1364                                 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1365                                 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1366                                 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1367                                 FROM `item`, `contact`
1368                                 WHERE `item`.`uid` = %d
1369                                 AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1370                                 AND `item`.`starred` = 1
1371                                 AND `contact`.`id` = `item`.`contact-id`
1372                                 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1373                                 $sql_extra
1374                                 AND `item`.`id`>%d
1375                                 ORDER BY `item`.`received` DESC LIMIT %d ,%d ",
1376                                 //intval($user_info['uid']),
1377                                 intval(api_user()),
1378                                 intval($since_id),
1379                                 intval($start), intval($count)
1380                         );
1381
1382                         $ret = api_format_items($r,$user_info);
1383
1384                 }
1385
1386                 $data = array('$statuses' => $ret);
1387                 switch($type){
1388                         case "atom":
1389                         case "rss":
1390                                 $data = api_rss_extra($a, $data, $user_info);
1391                 }
1392
1393                 return  api_apply_template("timeline", $type, $data);
1394         }
1395
1396         api_register_func('api/favorites','api_favorites', true);
1397
1398         function api_format_as($a, $ret, $user_info) {
1399
1400                 $as = array();
1401                 $as['title'] = $a->config['sitename']." Public Timeline";
1402                 $items = array();
1403                 foreach ($ret as $item) {
1404                         $singleitem["actor"]["displayName"] = $item["user"]["name"];
1405                         $singleitem["actor"]["id"] = $item["user"]["contact_url"];
1406                         $avatar[0]["url"] = $item["user"]["profile_image_url"];
1407                         $avatar[0]["rel"] = "avatar";
1408                         $avatar[0]["type"] = "";
1409                         $avatar[0]["width"] = 96;
1410                         $avatar[0]["height"] = 96;
1411                         $avatar[1]["url"] = $item["user"]["profile_image_url"];
1412                         $avatar[1]["rel"] = "avatar";
1413                         $avatar[1]["type"] = "";
1414                         $avatar[1]["width"] = 48;
1415                         $avatar[1]["height"] = 48;
1416                         $avatar[2]["url"] = $item["user"]["profile_image_url"];
1417                         $avatar[2]["rel"] = "avatar";
1418                         $avatar[2]["type"] = "";
1419                         $avatar[2]["width"] = 24;
1420                         $avatar[2]["height"] = 24;
1421                         $singleitem["actor"]["avatarLinks"] = $avatar;
1422
1423                         $singleitem["actor"]["image"]["url"] = $item["user"]["profile_image_url"];
1424                         $singleitem["actor"]["image"]["rel"] = "avatar";
1425                         $singleitem["actor"]["image"]["type"] = "";
1426                         $singleitem["actor"]["image"]["width"] = 96;
1427                         $singleitem["actor"]["image"]["height"] = 96;
1428                         $singleitem["actor"]["type"] = "person";
1429                         $singleitem["actor"]["url"] = $item["person"]["contact_url"];
1430                         $singleitem["actor"]["statusnet:profile_info"]["local_id"] = $item["user"]["id"];
1431                         $singleitem["actor"]["statusnet:profile_info"]["following"] = $item["user"]["following"] ? "true" : "false";
1432                         $singleitem["actor"]["statusnet:profile_info"]["blocking"] = "false";
1433                         $singleitem["actor"]["contact"]["preferredUsername"] = $item["user"]["screen_name"];
1434                         $singleitem["actor"]["contact"]["displayName"] = $item["user"]["name"];
1435                         $singleitem["actor"]["contact"]["addresses"] = "";
1436
1437                         $singleitem["body"] = $item["text"];
1438                         $singleitem["object"]["displayName"] = $item["text"];
1439                         $singleitem["object"]["id"] = $item["url"];
1440                         $singleitem["object"]["type"] = "note";
1441                         $singleitem["object"]["url"] = $item["url"];
1442                         //$singleitem["context"] =;
1443                         $singleitem["postedTime"] = date("c", strtotime($item["published"]));
1444                         $singleitem["provider"]["objectType"] = "service";
1445                         $singleitem["provider"]["displayName"] = "Test";
1446                         $singleitem["provider"]["url"] = "http://test.tld";
1447                         $singleitem["title"] = $item["text"];
1448                         $singleitem["verb"] = "post";
1449                         $singleitem["statusnet:notice_info"]["local_id"] = $item["id"];
1450                                 $singleitem["statusnet:notice_info"]["source"] = $item["source"];
1451                                 $singleitem["statusnet:notice_info"]["favorite"] = "false";
1452                                 $singleitem["statusnet:notice_info"]["repeated"] = "false";
1453                                 //$singleitem["original"] = $item;
1454                                 $items[] = $singleitem;
1455                 }
1456                 $as['items'] = $items;
1457                 $as['link']['url'] = $a->get_baseurl()."/".$user_info["screen_name"]."/all";
1458                 $as['link']['rel'] = "alternate";
1459                 $as['link']['type'] = "text/html";
1460                 return($as);
1461         }
1462
1463         function api_format_messages($item, $recipient, $sender) {
1464                 // standard meta information
1465                 $ret=Array(
1466                                 'id'                    => $item['id'],
1467                                 'sender_id'             => $sender['id'] ,
1468                                 'text'                  => "",
1469                                 'recipient_id'          => $recipient['id'],
1470                                 'created_at'            => api_date($item['created']),
1471                                 'sender_screen_name'    => $sender['screen_name'],
1472                                 'recipient_screen_name' => $recipient['screen_name'],
1473                                 'sender'                => $sender,
1474                                 'recipient'             => $recipient,
1475                 );
1476
1477                 // "cid", "uid" and "self" are only needed for some internal stuff, so remove it from here
1478                 unset($ret["sender"]["cid"]);
1479                 unset($ret["sender"]["uid"]);
1480                 unset($ret["sender"]["self"]);
1481                 unset($ret["recipient"]["cid"]);
1482                 unset($ret["recipient"]["uid"]);
1483                 unset($ret["recipient"]["self"]);
1484
1485                 //don't send title to regular StatusNET requests to avoid confusing these apps
1486                 if (x($_GET, 'getText')) {
1487                         $ret['title'] = $item['title'] ;
1488                         if ($_GET["getText"] == "html") {
1489                                 $ret['text'] = bbcode($item['body'], false, false);
1490                         }
1491                         elseif ($_GET["getText"] == "plain") {
1492                                 //$ret['text'] = html2plain(bbcode($item['body'], false, false, true), 0);
1493                                 $ret['text'] = trim(html2plain(bbcode(api_clean_plain_items($item['body']), false, false, 2, true), 0));
1494                         }
1495                 }
1496                 else {
1497                         $ret['text'] = $item['title']."\n".html2plain(bbcode(api_clean_plain_items($item['body']), false, false, 2, true), 0);
1498                 }
1499                 if (isset($_GET["getUserObjects"]) && $_GET["getUserObjects"] == "false") {
1500                         unset($ret['sender']);
1501                         unset($ret['recipient']);
1502                 }
1503
1504                 return $ret;
1505         }
1506
1507         function api_format_items($r,$user_info, $filter_user = false) {
1508
1509                 $a = get_app();
1510                 $ret = Array();
1511
1512                 foreach($r as $item) {
1513                         api_share_as_retweet($a, api_user(), $item);
1514
1515                         localize_item($item);
1516                         $status_user = api_item_get_user($a,$item);
1517
1518                         // Look if the posts are matching if they should be filtered by user id
1519                         if ($filter_user AND ($status_user["id"] != $user_info["id"]))
1520                                 continue;
1521
1522                         if ($item['thr-parent'] != $item['uri']) {
1523                                 $r = q("SELECT id FROM item WHERE uid=%d AND uri='%s' LIMIT 1",
1524                                         intval(api_user()),
1525                                         dbesc($item['thr-parent']));
1526                                 if ($r)
1527                                         $in_reply_to_status_id = $r[0]['id'];
1528                                 else
1529                                         $in_reply_to_status_id = $item['parent'];
1530
1531                                 $in_reply_to_screen_name = NULL;
1532                                 $in_reply_to_user_id = NULL;
1533
1534                                 $r = q("SELECT `author-link` FROM item WHERE uid=%d AND id=%d LIMIT 1",
1535                                         intval(api_user()),
1536                                         intval($in_reply_to_status_id));
1537                                 if ($r) {
1538                                         $r = q("SELECT * FROM unique_contacts WHERE `url` = '%s'", dbesc(normalise_link($r[0]['author-link'])));
1539
1540                                         if ($r) {
1541                                                 if ($r[0]['nick'] == "")
1542                                                         $r[0]['nick'] = api_get_nick($r[0]["url"]);
1543
1544                                                 $in_reply_to_screen_name = (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']);
1545                                                 $in_reply_to_user_id = $r[0]['id'];
1546                                         }
1547                                 }
1548                         } else {
1549                                 $in_reply_to_screen_name = NULL;
1550                                 $in_reply_to_user_id = NULL;
1551                                 $in_reply_to_status_id = NULL;
1552                         }
1553
1554                         // Workaround for ostatus messages where the title is identically to the body
1555                         $statusbody = trim(html2plain(bbcode(api_clean_plain_items($item['body']), false, false, 2, true), 0));
1556
1557                         $statustitle = trim($item['title']);
1558
1559                         if (($statustitle != '') and (strpos($statusbody, $statustitle) !== false))
1560                                 $statustext = trim($statusbody);
1561                         else
1562                                 $statustext = trim($statustitle."\n\n".$statusbody);
1563
1564                         if (($item["network"] == NETWORK_FEED) and (strlen($statustext)> 1000))
1565                                 $statustext = substr($statustext, 0, 1000)."... \n".$item["plink"];
1566
1567                         $status = array(
1568                                 'text'          => $statustext,
1569                                 'truncated' => False,
1570                                 'created_at'=> api_date($item['created']),
1571                                 'in_reply_to_status_id' => $in_reply_to_status_id,
1572                                 'source'    => (($item['app']) ? $item['app'] : 'web'),
1573                                 'id'            => intval($item['id']),
1574                                 'in_reply_to_user_id' => $in_reply_to_user_id,
1575                                 'in_reply_to_screen_name' => $in_reply_to_screen_name,
1576                                 'geo' => NULL,
1577                                 'favorited' => $item['starred'] ? true : false,
1578                                 //'attachments' => array(),
1579                                 'user' =>  $status_user ,
1580                                 'statusnet_html'                => trim(bbcode($item['body'], false, false)),
1581                                 'statusnet_conversation_id'     => $item['parent'],
1582                         );
1583
1584                         if (($item['item_network'] != "") AND ($status["source"] == 'web'))
1585                                 $status["source"] = network_to_name($item['item_network']);
1586                         else if (($item['item_network'] != "") AND (network_to_name($item['item_network']) != $status["source"]))
1587                                 $status["source"] = trim($status["source"].' ('.network_to_name($item['item_network']).')');
1588
1589
1590                         // Retweets are only valid for top postings
1591                         if (($item['owner-link'] != $item['author-link']) AND ($item["id"] == $item["parent"])) {
1592                                 $retweeted_status = $status;
1593                                 $retweeted_status["user"] = api_get_user($a,$item["author-link"]);
1594
1595                                 $status["retweeted_status"] = $retweeted_status;
1596                         }
1597
1598                         // "cid", "uid" and "self" are only needed for some internal stuff, so remove it from here
1599                         unset($status["user"]["cid"]);
1600                         unset($status["user"]["uid"]);
1601                         unset($status["user"]["self"]);
1602
1603                         // 'geo' => array('type' => 'Point',
1604                         //                   'coordinates' => array((float) $notice->lat,
1605                         //                                          (float) $notice->lon));
1606
1607                         // Seesmic doesn't like the following content
1608                         // completely disabled to make friendica totally compatible to the statusnet API
1609                         /*if ($_SERVER['HTTP_USER_AGENT'] != 'Seesmic') {
1610                                 $status2 = array(
1611                                         'updated'   => api_date($item['edited']),
1612                                         'published' => api_date($item['created']),
1613                                         'message_id' => $item['uri'],
1614                                         'url'           => ($item['plink']!=''?$item['plink']:$item['author-link']),
1615                                         'coordinates' => $item['coord'],
1616                                         'place' => $item['location'],
1617                                         'contributors' => '',
1618                                         'annotations'  => '',
1619                                         'entities'  => '',
1620                                         'objecttype' => (($item['object-type']) ? $item['object-type'] : ACTIVITY_OBJ_NOTE),
1621                                         'verb' => (($item['verb']) ? $item['verb'] : ACTIVITY_POST),
1622                                         'self' => $a->get_baseurl()."/api/statuses/show/".$item['id'].".".$type,
1623                                         'edit' => $a->get_baseurl()."/api/statuses/show/".$item['id'].".".$type,
1624                                 );
1625
1626                                 $status = array_merge($status, $status2);
1627                         }*/
1628
1629                         $ret[] = $status;
1630                 };
1631                 return $ret;
1632         }
1633
1634
1635         function api_account_rate_limit_status(&$a,$type) {
1636
1637                 $hash = array(
1638                           'reset_time_in_seconds' => strtotime('now + 1 hour'),
1639                           'remaining_hits' => (string) 150,
1640                           'hourly_limit' => (string) 150,
1641                           'reset_time' => api_date(datetime_convert('UTC','UTC','now + 1 hour',ATOM_TIME)),
1642                 );
1643                 if ($type == "xml")
1644                         $hash['resettime_in_seconds'] = $hash['reset_time_in_seconds'];
1645
1646                 return api_apply_template('ratelimit', $type, array('$hash' => $hash));
1647
1648         }
1649         api_register_func('api/account/rate_limit_status','api_account_rate_limit_status',true);
1650
1651         function api_help_test(&$a,$type) {
1652
1653                 if ($type == 'xml')
1654                         $ok = "true";
1655                 else
1656                         $ok = "ok";
1657
1658                 return api_apply_template('test', $type, array('$ok' => $ok));
1659
1660         }
1661         api_register_func('api/help/test','api_help_test',false);
1662
1663         /**
1664          *  https://dev.twitter.com/docs/api/1/get/statuses/friends 
1665          *  This function is deprecated by Twitter
1666          *  returns: json, xml 
1667          **/
1668         function api_statuses_f(&$a, $type, $qtype) {
1669                 if (api_user()===false) return false;
1670                 $user_info = api_get_user($a);
1671
1672                 if (x($_GET,'cursor') && $_GET['cursor']=='undefined'){
1673                         /* this is to stop Hotot to load friends multiple times
1674                         *  I'm not sure if I'm missing return something or
1675                         *  is a bug in hotot. Workaround, meantime
1676                         */
1677
1678                         /*$ret=Array();
1679                         return array('$users' => $ret);*/
1680                         return false;
1681                 }
1682
1683                 if($qtype == 'friends')
1684                         $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
1685                 if($qtype == 'followers')
1686                         $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
1687
1688                 // friends and followers only for self
1689                 if ($user_info['self'] == 0)
1690                         $sql_extra = " AND false ";
1691
1692                 $r = q("SELECT `nurl` FROM `contact` WHERE `uid` = %d AND `self` = 0 AND `blocked` = 0 AND `pending` = 0 $sql_extra",
1693                         intval(api_user())
1694                 );
1695
1696                 $ret = array();
1697                 foreach($r as $cid){
1698                         $user = api_get_user($a, $cid['nurl']);
1699                         // "cid", "uid" and "self" are only needed for some internal stuff, so remove it from here
1700                         unset($user["cid"]);
1701                         unset($user["uid"]);
1702                         unset($user["self"]);
1703
1704                         if ($user)
1705                                 $ret[] = $user;
1706                 }
1707
1708                 return array('$users' => $ret);
1709
1710         }
1711         function api_statuses_friends(&$a, $type){
1712                 $data =  api_statuses_f($a,$type,"friends");
1713                 if ($data===false) return false;
1714                 return  api_apply_template("friends", $type, $data);
1715         }
1716         function api_statuses_followers(&$a, $type){
1717                 $data = api_statuses_f($a,$type,"followers");
1718                 if ($data===false) return false;
1719                 return  api_apply_template("friends", $type, $data);
1720         }
1721         api_register_func('api/statuses/friends','api_statuses_friends',true);
1722         api_register_func('api/statuses/followers','api_statuses_followers',true);
1723
1724
1725
1726
1727
1728
1729         function api_statusnet_config(&$a,$type) {
1730                 $name = $a->config['sitename'];
1731                 $server = $a->get_hostname();
1732                 $logo = $a->get_baseurl() . '/images/friendica-64.png';
1733                 $email = $a->config['admin_email'];
1734                 $closed = (($a->config['register_policy'] == REGISTER_CLOSED) ? 'true' : 'false');
1735                 $private = (($a->config['system']['block_public']) ? 'true' : 'false');
1736                 $textlimit = (string) (($a->config['max_import_size']) ? $a->config['max_import_size'] : 200000);
1737                 if($a->config['api_import_size'])
1738                         $texlimit = string($a->config['api_import_size']);
1739                 $ssl = (($a->config['system']['have_ssl']) ? 'true' : 'false');
1740                 $sslserver = (($ssl === 'true') ? str_replace('http:','https:',$a->get_baseurl()) : '');
1741
1742                 $config = array(
1743                         'site' => array('name' => $name,'server' => $server, 'theme' => 'default', 'path' => '',
1744                                 'logo' => $logo, 'fancy' => true, 'language' => 'en', 'email' => $email, 'broughtby' => '',
1745                                 'broughtbyurl' => '', 'timezone' => 'UTC', 'closed' => $closed, 'inviteonly' => false,
1746                                 'private' => $private, 'textlimit' => $textlimit, 'sslserver' => $sslserver, 'ssl' => $ssl,
1747                                 'shorturllength' => '30',
1748                                 'friendica' => array(
1749                                                 'FRIENDICA_PLATFORM' => FRIENDICA_PLATFORM,
1750                                                 'FRIENDICA_VERSION' => FRIENDICA_VERSION,
1751                                                 'DFRN_PROTOCOL_VERSION' => DFRN_PROTOCOL_VERSION,
1752                                                 'DB_UPDATE_VERSION' => DB_UPDATE_VERSION
1753                                                 )
1754                         ),
1755                 );
1756
1757                 return api_apply_template('config', $type, array('$config' => $config));
1758
1759         }
1760         api_register_func('api/statusnet/config','api_statusnet_config',false);
1761
1762         function api_statusnet_version(&$a,$type) {
1763
1764                 // liar
1765
1766                 if($type === 'xml') {
1767                         header("Content-type: application/xml");
1768                         echo '<?xml version="1.0" encoding="UTF-8"?>' . "\r\n" . '<version>0.9.7</version>' . "\r\n";
1769                         killme();
1770                 }
1771                 elseif($type === 'json') {
1772                         header("Content-type: application/json");
1773                         echo '"0.9.7"';
1774                         killme();
1775                 }
1776         }
1777         api_register_func('api/statusnet/version','api_statusnet_version',false);
1778
1779
1780         function api_ff_ids(&$a,$type,$qtype) {
1781                 if(! api_user())
1782                         return false;
1783
1784                 $user_info = api_get_user($a);
1785
1786                 if($qtype == 'friends')
1787                         $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
1788                 if($qtype == 'followers')
1789                         $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
1790
1791                 if (!$user_info["self"])
1792                         $sql_extra = " AND false ";
1793
1794                 $stringify_ids = (x($_REQUEST,'stringify_ids')?$_REQUEST['stringify_ids']:false);
1795
1796                 $r = q("SELECT unique_contacts.id FROM contact, unique_contacts WHERE contact.nurl = unique_contacts.url AND `uid` = %d AND `self` = 0 AND `blocked` = 0 AND `pending` = 0 $sql_extra",
1797                         intval(api_user())
1798                 );
1799
1800                 if(is_array($r)) {
1801
1802                         if($type === 'xml') {
1803                                 header("Content-type: application/xml");
1804                                 echo '<?xml version="1.0" encoding="UTF-8"?>' . "\r\n" . '<ids>' . "\r\n";
1805                                 foreach($r as $rr)
1806                                         echo '<id>' . $rr['id'] . '</id>' . "\r\n";
1807                                 echo '</ids>' . "\r\n";
1808                                 killme();
1809                         }
1810                         elseif($type === 'json') {
1811                                 $ret = array();
1812                                 header("Content-type: application/json");
1813                                 foreach($r as $rr)
1814                                         if ($stringify_ids)
1815                                                 $ret[] = $rr['id'];
1816                                         else
1817                                                 $ret[] = intval($rr['id']);
1818
1819                                 echo json_encode($ret);
1820                                 killme();
1821                         }
1822                 }
1823         }
1824
1825         function api_friends_ids(&$a,$type) {
1826                 api_ff_ids($a,$type,'friends');
1827         }
1828         function api_followers_ids(&$a,$type) {
1829                 api_ff_ids($a,$type,'followers');
1830         }
1831         api_register_func('api/friends/ids','api_friends_ids',true);
1832         api_register_func('api/followers/ids','api_followers_ids',true);
1833
1834
1835         function api_direct_messages_new(&$a, $type) {
1836                 if (api_user()===false) return false;
1837
1838                 if (!x($_POST, "text") OR (!x($_POST,"screen_name") AND !x($_POST,"user_id"))) return;
1839
1840                 $sender = api_get_user($a);
1841
1842                 require_once("include/message.php");
1843
1844                 if ($_POST['screen_name']) {
1845                         $r = q("SELECT `id`, `nurl`, `network` FROM `contact` WHERE `uid`=%d AND `nick`='%s'",
1846                                         intval(api_user()),
1847                                         dbesc($_POST['screen_name']));
1848
1849                         // Selecting the id by priority, friendica first
1850                         api_best_nickname($r);
1851
1852                         $recipient = api_get_user($a, $r[0]['nurl']);
1853                 } else
1854                         $recipient = api_get_user($a, $_POST['user_id']);
1855
1856                 $replyto = '';
1857                 $sub     = '';
1858                 if (x($_REQUEST,'replyto')) {
1859                         $r = q('SELECT `parent-uri`, `title` FROM `mail` WHERE `uid`=%d AND `id`=%d',
1860                                         intval(api_user()),
1861                                         intval($_REQUEST['replyto']));
1862                         $replyto = $r[0]['parent-uri'];
1863                         $sub     = $r[0]['title'];
1864                 }
1865                 else {
1866                         if (x($_REQUEST,'title')) {
1867                                 $sub = $_REQUEST['title'];
1868                         }
1869                         else {
1870                                 $sub = ((strlen($_POST['text'])>10)?substr($_POST['text'],0,10)."...":$_POST['text']);
1871                         }
1872                 }
1873
1874                 $id = send_message($recipient['cid'], $_POST['text'], $sub, $replyto);
1875
1876                 if ($id>-1) {
1877                         $r = q("SELECT * FROM `mail` WHERE id=%d", intval($id));
1878                         $ret = api_format_messages($r[0], $recipient, $sender);
1879
1880                 } else {
1881                         $ret = array("error"=>$id);
1882                 }
1883
1884                 $data = Array('$messages'=>$ret);
1885
1886                 switch($type){
1887                         case "atom":
1888                         case "rss":
1889                                 $data = api_rss_extra($a, $data, $user_info);
1890                 }
1891
1892                 return  api_apply_template("direct_messages", $type, $data);
1893
1894         }
1895         api_register_func('api/direct_messages/new','api_direct_messages_new',true);
1896
1897         function api_direct_messages_box(&$a, $type, $box) {
1898                 if (api_user()===false) return false;
1899
1900                 unset($_REQUEST["user_id"]);
1901                 unset($_GET["user_id"]);
1902
1903                 unset($_REQUEST["screen_name"]);
1904                 unset($_GET["screen_name"]);
1905
1906                 $user_info = api_get_user($a);
1907
1908                 // params
1909                 $count = (x($_GET,'count')?$_GET['count']:20);
1910                 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1911                 if ($page<0) $page=0;
1912
1913                 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1914                 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1915
1916                 $start = $page*$count;
1917
1918                 //$profile_url = $a->get_baseurl() . '/profile/' . $a->user['nickname'];
1919                 $profile_url = $user_info["url"];
1920
1921                 if ($box=="sentbox") {
1922                         $sql_extra = "`mail`.`from-url`='".dbesc( $profile_url )."'";
1923                 }
1924                 elseif ($box=="conversation") {
1925                         $sql_extra = "`mail`.`parent-uri`='".dbesc( $_GET["uri"] )  ."'";
1926                 }
1927                 elseif ($box=="all") {
1928                         $sql_extra = "true";
1929                 }
1930                 elseif ($box=="inbox") {
1931                         $sql_extra = "`mail`.`from-url`!='".dbesc( $profile_url )."'";
1932                 }
1933
1934                 if ($max_id > 0)
1935                         $sql_extra .= ' AND `mail`.`id` <= '.intval($max_id);
1936
1937                 $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`.`created` DESC LIMIT %d,%d",
1938                                 intval(api_user()),
1939                                 intval($since_id),
1940                                 intval($start), intval($count)
1941                 );
1942
1943                 $ret = Array();
1944                 foreach($r as $item) {
1945                         if ($box == "inbox" || $item['from-url'] != $profile_url){
1946                                 $recipient = $user_info;
1947                                 $sender = api_get_user($a,normalise_link($item['contact-url']));
1948                         }
1949                         elseif ($box == "sentbox" || $item['from-url'] != $profile_url){
1950                                 $recipient = api_get_user($a,normalise_link($item['contact-url']));
1951                                 $sender = $user_info;
1952
1953                         }
1954
1955                         $ret[]=api_format_messages($item, $recipient, $sender);
1956                 }
1957
1958
1959                 $data = array('$messages' => $ret);
1960                 switch($type){
1961                         case "atom":
1962                         case "rss":
1963                                 $data = api_rss_extra($a, $data, $user_info);
1964                 }
1965
1966                 return  api_apply_template("direct_messages", $type, $data);
1967
1968         }
1969
1970         function api_direct_messages_sentbox(&$a, $type){
1971                 return api_direct_messages_box($a, $type, "sentbox");
1972         }
1973         function api_direct_messages_inbox(&$a, $type){
1974                 return api_direct_messages_box($a, $type, "inbox");
1975         }
1976         function api_direct_messages_all(&$a, $type){
1977                 return api_direct_messages_box($a, $type, "all");
1978         }
1979         function api_direct_messages_conversation(&$a, $type){
1980                 return api_direct_messages_box($a, $type, "conversation");
1981         }
1982         api_register_func('api/direct_messages/conversation','api_direct_messages_conversation',true);
1983         api_register_func('api/direct_messages/all','api_direct_messages_all',true);
1984         api_register_func('api/direct_messages/sent','api_direct_messages_sentbox',true);
1985         api_register_func('api/direct_messages','api_direct_messages_inbox',true);
1986
1987
1988
1989         function api_oauth_request_token(&$a, $type){
1990                 try{
1991                         $oauth = new FKOAuth1();
1992                         $r = $oauth->fetch_request_token(OAuthRequest::from_request());
1993                 }catch(Exception $e){
1994                         echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage()); killme();
1995                 }
1996                 echo $r;
1997                 killme();
1998         }
1999         function api_oauth_access_token(&$a, $type){
2000                 try{
2001                         $oauth = new FKOAuth1();
2002                         $r = $oauth->fetch_access_token(OAuthRequest::from_request());
2003                 }catch(Exception $e){
2004                         echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage()); killme();
2005                 }
2006                 echo $r;
2007                 killme();
2008         }
2009
2010         api_register_func('api/oauth/request_token', 'api_oauth_request_token', false);
2011         api_register_func('api/oauth/access_token', 'api_oauth_access_token', false);
2012
2013 function api_share_as_retweet($a, $uid, &$item) {
2014         $body = trim($item["body"]);
2015
2016         // Skip if it isn't a pure repeated messages
2017         // Does it start with a share?
2018         if (strpos($body, "[share") > 0)
2019                 return(false);
2020
2021         // Does it end with a share?
2022         if (strlen($body) > (strrpos($body, "[/share]") + 8))
2023                 return(false);
2024
2025         $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$1",$body);
2026         // Skip if there is no shared message in there
2027         if ($body == $attributes)
2028                 return(false);
2029
2030         $author = "";
2031         preg_match("/author='(.*?)'/ism", $attributes, $matches);
2032         if ($matches[1] != "")
2033                 $author = html_entity_decode($matches[1],ENT_QUOTES,'UTF-8');
2034
2035         preg_match('/author="(.*?)"/ism', $attributes, $matches);
2036         if ($matches[1] != "")
2037                 $author = $matches[1];
2038
2039         $profile = "";
2040         preg_match("/profile='(.*?)'/ism", $attributes, $matches);
2041         if ($matches[1] != "")
2042                 $profile = $matches[1];
2043
2044         preg_match('/profile="(.*?)"/ism', $attributes, $matches);
2045         if ($matches[1] != "")
2046                 $profile = $matches[1];
2047
2048         $avatar = "";
2049         preg_match("/avatar='(.*?)'/ism", $attributes, $matches);
2050         if ($matches[1] != "")
2051                 $avatar = $matches[1];
2052
2053         preg_match('/avatar="(.*?)"/ism', $attributes, $matches);
2054         if ($matches[1] != "")
2055                 $avatar = $matches[1];
2056
2057         $shared_body = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$2",$body);
2058
2059         if (($shared_body == "") OR ($profile == "") OR ($author == "") OR ($avatar == ""))
2060                 return(false);
2061
2062         $item["body"] = $shared_body;
2063         $item["author-name"] = $author;
2064         $item["author-link"] = $profile;
2065         $item["author-avatar"] = $avatar;
2066
2067         return(true);
2068
2069 }
2070
2071 function api_get_nick($profile) {
2072 /* To-Do:
2073  - remove trailing jung from profile url
2074  - pump.io check has to check the website
2075 */
2076
2077         $nick = "";
2078
2079         $friendica = preg_replace("=https?://(.*)/profile/(.*)=ism", "$2", $profile);
2080         if ($friendica != $profile)
2081                 $nick = $friendica;
2082
2083         if (!$nick == "") {
2084                 $diaspora = preg_replace("=https?://(.*)/u/(.*)=ism", "$2", $profile);
2085                 if ($diaspora != $profile)
2086                         $nick = $diaspora;
2087         }
2088
2089         if (!$nick == "") {
2090                 $twitter = preg_replace("=https?://twitter.com/(.*)=ism", "$1", $profile);
2091                 if ($twitter != $profile)
2092                         $nick = $twitter;
2093         }
2094
2095
2096         if (!$nick == "") {
2097                 $StatusnetHost = preg_replace("=https?://(.*)/user/(.*)=ism", "$1", $profile);
2098                 if ($StatusnetHost != $profile) {
2099                         $StatusnetUser = preg_replace("=https?://(.*)/user/(.*)=ism", "$2", $profile);
2100                         if ($StatusnetUser != $profile) {
2101                                 $UserData = fetch_url("http://".$StatusnetHost."/api/users/show.json?user_id=".$StatusnetUser);
2102                                 $user = json_decode($UserData);
2103                                 if ($user)
2104                                         $nick = $user->screen_name;
2105                         }
2106                 }
2107         }
2108
2109         // To-Do: look at the page if its really a pumpio site
2110         //if (!$nick == "") {
2111         //      $pumpio = preg_replace("=https?://(.*)/(.*)/=ism", "$2", $profile."/");
2112         //      if ($pumpio != $profile)
2113         //              $nick = $pumpio;
2114                 //      <div class="media" id="profile-block" data-profile-id="acct:kabniel@microca.st">
2115
2116         //}
2117
2118         if ($nick != "") {
2119                 q("UPDATE unique_contacts SET nick = '%s' WHERE url = '%s'",
2120                         dbesc($nick), dbesc(normalise_link($profile)));
2121                 return($nick);
2122         }
2123
2124         return(false);
2125 }
2126
2127 function api_clean_plain_items($Text) {
2128         $Text = preg_replace_callback("((.*?)\[class=(.*?)\](.*?)\[\/class\])ism","api_cleanup_share",$Text);
2129         return($Text);
2130 }
2131
2132 function api_cleanup_share($shared) {
2133         if ($shared[2] != "type-link")
2134                 return($shared[3]);
2135
2136         if (!preg_match_all("/\[bookmark\=([^\]]*)\](.*?)\[\/bookmark\]/ism",$shared[3], $bookmark))
2137                 return($shared[3]);
2138
2139         $title = "";
2140         $link = "";
2141
2142         if (isset($bookmark[2][0]))
2143                 $title = $bookmark[2][0];
2144
2145         if (isset($bookmark[1][0]))
2146                 $link = $bookmark[1][0];
2147
2148         if (strpos($shared[1],$title) !== false)
2149                 $title = "";
2150
2151         if (strpos($shared[1],$link) !== false)
2152                 $link = "";
2153
2154         $text = trim($shared[1]);
2155
2156         //if (strlen($text) < strlen($title))
2157         if (($text == "") AND ($title != ""))
2158                 $text .= "\n\n".trim($title);
2159
2160         if ($link != "")
2161                 $text .= "\n".trim($link);
2162
2163         return(trim($text));
2164 }
2165
2166 function api_best_nickname(&$contacts) {
2167         $best_contact = array();
2168
2169         foreach ($contacts AS $contact)
2170                 if ($contact["network"] == "") {
2171                         $contact["network"] = "dfrn";
2172                         $best_contact = array($contact);
2173                 }
2174
2175         if (sizeof($best_contact) == 0)
2176                 foreach ($contacts AS $contact)
2177                         if ($contact["network"] == "dfrn")
2178                                 $best_contact = array($contact);
2179
2180         if (sizeof($best_contact) == 0)
2181                 foreach ($contacts AS $contact)
2182                         if ($contact["network"] == "dspr")
2183                                 $best_contact = array($contact);
2184
2185         if (sizeof($best_contact) == 0)
2186                 foreach ($contacts AS $contact)
2187                         if ($contact["network"] == "stat")
2188                                 $best_contact = array($contact);
2189
2190         if (sizeof($best_contact) == 0)
2191                 foreach ($contacts AS $contact)
2192                         if ($contact["network"] == "pump")
2193                                 $best_contact = array($contact);
2194
2195         if (sizeof($best_contact) == 0)
2196                 foreach ($contacts AS $contact)
2197                         if ($contact["network"] == "twit")
2198                                 $best_contact = array($contact);
2199
2200         if (sizeof($best_contact) == 1)
2201                 $contacts = $best_contact;
2202         else
2203                 $contacts = array($contacts[0]);
2204 }
2205
2206 /*
2207 Not implemented by now:
2208 favorites
2209 favorites/create
2210 favorites/destroy
2211 statuses/retweets_of_me
2212 friendships/create
2213 friendships/destroy
2214 friendships/exists
2215 friendships/show
2216 account/update_location
2217 account/update_profile_background_image
2218 account/update_profile_image
2219 blocks/create
2220 blocks/destroy
2221
2222 Not implemented in status.net:
2223 statuses/retweeted_to_me
2224 statuses/retweeted_by_me
2225 direct_messages/destroy
2226 account/end_session
2227 account/update_delivery_device
2228 notifications/follow
2229 notifications/leave
2230 blocks/exists
2231 blocks/blocking
2232 lists
2233 */