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