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