]> git.mxchange.org Git - friendica.git/blob - include/api.php
Merge pull request #1483 from annando/1504-api-upload-pictures
[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                 $r = q("UPDATE `item` SET `unseen` = 0 WHERE `unseen` AND `id` IN (%s)", $idlist);
1190
1191
1192                 $data = array('$statuses' => $ret);
1193                 switch($type){
1194                         case "atom":
1195                         case "rss":
1196                                 $data = api_rss_extra($a, $data, $user_info);
1197                                 break;
1198                         case "as":
1199                                 $as = api_format_as($a, $ret, $user_info);
1200                                 $as['title'] = $a->config['sitename']." Home Timeline";
1201                                 $as['link']['url'] = $a->get_baseurl()."/".$user_info["screen_name"]."/all";
1202                                 return($as);
1203                                 break;
1204                 }
1205
1206                 return  api_apply_template("timeline", $type, $data);
1207         }
1208         api_register_func('api/statuses/home_timeline','api_statuses_home_timeline', true);
1209         api_register_func('api/statuses/friends_timeline','api_statuses_home_timeline', true);
1210
1211         function api_statuses_public_timeline(&$a, $type){
1212                 if (api_user()===false) return false;
1213
1214                 $user_info = api_get_user($a);
1215                 // get last newtork messages
1216
1217
1218                 // params
1219                 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1220                 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1221                 if ($page<0) $page=0;
1222                 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1223                 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1224                 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1225                 $exclude_replies = (x($_REQUEST,'exclude_replies')?1:0);
1226                 $conversation_id = (x($_REQUEST,'conversation_id')?$_REQUEST['conversation_id']:0);
1227
1228                 $start = $page*$count;
1229
1230                 if ($max_id > 0)
1231                         $sql_extra = 'AND `item`.`id` <= '.intval($max_id);
1232                 if ($exclude_replies > 0)
1233                         $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
1234                 if ($conversation_id > 0)
1235                         $sql_extra .= ' AND `item`.`parent` = '.intval($conversation_id);
1236
1237                 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1238                         `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1239                         `contact`.`network`, `contact`.`thumb`, `contact`.`self`, `contact`.`writable`,
1240                         `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`,
1241                         `user`.`nickname`, `user`.`hidewall`
1242                         FROM `item` STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
1243                         STRAIGHT_JOIN `user` ON `user`.`uid` = `item`.`uid`
1244                         WHERE `verb` = '%s' AND `item`.`visible` = 1 AND `item`.`deleted` = 0 and `item`.`moderated` = 0
1245                         AND `item`.`allow_cid` = ''  AND `item`.`allow_gid` = ''
1246                         AND `item`.`deny_cid`  = '' AND `item`.`deny_gid`  = ''
1247                         AND `item`.`private` = 0 AND `item`.`wall` = 1 AND `user`.`hidewall` = 0
1248                         AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1249                         $sql_extra
1250                         AND `item`.`id`>%d
1251                         ORDER BY `item`.`id` DESC LIMIT %d, %d ",
1252                         dbesc(ACTIVITY_POST),
1253                         intval($since_id),
1254                         intval($start),
1255                         intval($count));
1256
1257                 $ret = api_format_items($r,$user_info);
1258
1259
1260                 $data = array('$statuses' => $ret);
1261                 switch($type){
1262                         case "atom":
1263                         case "rss":
1264                                 $data = api_rss_extra($a, $data, $user_info);
1265                                 break;
1266                         case "as":
1267                                 $as = api_format_as($a, $ret, $user_info);
1268                                 $as['title'] = $a->config['sitename']." Public Timeline";
1269                                 $as['link']['url'] = $a->get_baseurl()."/";
1270                                 return($as);
1271                                 break;
1272                 }
1273
1274                 return  api_apply_template("timeline", $type, $data);
1275         }
1276         api_register_func('api/statuses/public_timeline','api_statuses_public_timeline', true);
1277
1278         /**
1279          *
1280          */
1281         function api_statuses_show(&$a, $type){
1282                 if (api_user()===false) return false;
1283
1284                 $user_info = api_get_user($a);
1285
1286                 // params
1287                 $id = intval($a->argv[3]);
1288
1289                 if ($id == 0)
1290                         $id = intval($_REQUEST["id"]);
1291
1292                 // Hotot workaround
1293                 if ($id == 0)
1294                         $id = intval($a->argv[4]);
1295
1296                 logger('API: api_statuses_show: '.$id);
1297
1298                 $conversation = (x($_REQUEST,'conversation')?1:0);
1299
1300                 $sql_extra = '';
1301                 if ($conversation)
1302                         $sql_extra .= " AND `item`.`parent` = %d ORDER BY `received` ASC ";
1303                 else
1304                         $sql_extra .= " AND `item`.`id` = %d";
1305
1306                 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1307                         `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1308                         `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1309                         `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1310                         FROM `item`, `contact`
1311                         WHERE `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1312                         AND `contact`.`id` = `item`.`contact-id` AND `item`.`uid` = %d AND `item`.`verb` = '%s'
1313                         AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1314                         $sql_extra",
1315                         intval(api_user()),
1316                         dbesc(ACTIVITY_POST),
1317                         intval($id)
1318                 );
1319
1320                 if (!$r)
1321                         die(api_error($a, $type, t("There is no status with this id.")));
1322
1323                 $ret = api_format_items($r,$user_info);
1324
1325                 if ($conversation) {
1326                         $data = array('$statuses' => $ret);
1327                         return api_apply_template("timeline", $type, $data);
1328                 } else {
1329                         $data = array('$status' => $ret[0]);
1330                         /*switch($type){
1331                                 case "atom":
1332                                 case "rss":
1333                                         $data = api_rss_extra($a, $data, $user_info);
1334                         }*/
1335                         return  api_apply_template("status", $type, $data);
1336                 }
1337         }
1338         api_register_func('api/statuses/show','api_statuses_show', true);
1339
1340
1341         /**
1342          *
1343          */
1344         function api_conversation_show(&$a, $type){
1345                 if (api_user()===false) return false;
1346
1347                 $user_info = api_get_user($a);
1348
1349                 // params
1350                 $id = intval($a->argv[3]);
1351                 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1352                 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1353                 if ($page<0) $page=0;
1354                 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1355                 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1356
1357                 $start = $page*$count;
1358
1359                 if ($id == 0)
1360                         $id = intval($_REQUEST["id"]);
1361
1362                 // Hotot workaround
1363                 if ($id == 0)
1364                         $id = intval($a->argv[4]);
1365
1366                 logger('API: api_conversation_show: '.$id);
1367
1368                 $sql_extra = '';
1369
1370                 if ($max_id > 0)
1371                         $sql_extra = ' AND `item`.`id` <= '.intval($max_id);
1372
1373                 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1374                         `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1375                         `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1376                         `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1377                         FROM `item` INNER JOIN (SELECT `uri`,`parent` FROM `item` WHERE `id` = %d) AS `temp1`
1378                         ON (`item`.`thr-parent` = `temp1`.`uri` AND `item`.`parent` = `temp1`.`parent`), `contact`
1379                         WHERE `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1380                         AND `item`.`uid` = %d AND `item`.`verb` = '%s' AND `contact`.`id` = `item`.`contact-id`
1381                         AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1382                         AND `item`.`id`>%d $sql_extra
1383                         ORDER BY `item`.`id` DESC LIMIT %d ,%d",
1384                         intval($id), intval(api_user()),
1385                         dbesc(ACTIVITY_POST),
1386                         intval($since_id),
1387                         intval($start), intval($count)
1388                 );
1389
1390                 if (!$r)
1391                         die(api_error($a, $type, t("There is no conversation with this id.")));
1392
1393                 $ret = api_format_items($r,$user_info);
1394
1395                 $data = array('$statuses' => $ret);
1396                 return api_apply_template("timeline", $type, $data);
1397         }
1398         api_register_func('api/conversation/show','api_conversation_show', true);
1399
1400
1401         /**
1402          *
1403          */
1404         function api_statuses_repeat(&$a, $type){
1405                 global $called_api;
1406
1407                 if (api_user()===false) return false;
1408
1409                 $user_info = api_get_user($a);
1410
1411                 // params
1412                 $id = intval($a->argv[3]);
1413
1414                 if ($id == 0)
1415                         $id = intval($_REQUEST["id"]);
1416
1417                 // Hotot workaround
1418                 if ($id == 0)
1419                         $id = intval($a->argv[4]);
1420
1421                 logger('API: api_statuses_repeat: '.$id);
1422
1423                 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`, `contact`.`nick` as `reply_author`,
1424                         `contact`.`name`, `contact`.`photo` as `reply_photo`, `contact`.`url` as `reply_url`, `contact`.`rel`,
1425                         `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1426                         `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1427                         FROM `item`, `contact`
1428                         WHERE `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1429                         AND `contact`.`id` = `item`.`contact-id`
1430                         AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1431                         $sql_extra
1432                         AND `item`.`id`=%d",
1433                         intval($id)
1434                 );
1435
1436                 if ($r[0]['body'] != "") {
1437                         if (!intval(get_config('system','old_share'))) {
1438                                 if (strpos($r[0]['body'], "[/share]") !== false) {
1439                                         $pos = strpos($r[0]['body'], "[share");
1440                                         $post = substr($r[0]['body'], $pos);
1441                                 } else {
1442                                         $post = share_header($r[0]['author-name'], $r[0]['author-link'], $r[0]['author-avatar'], $r[0]['guid'], $r[0]['created'], $r[0]['plink']);
1443
1444                                         $post .= $r[0]['body'];
1445                                         $post .= "[/share]";
1446                                 }
1447                                 $_REQUEST['body'] = $post;
1448                         } else
1449                                 $_REQUEST['body'] = html_entity_decode("&#x2672; ", ENT_QUOTES, 'UTF-8')."[url=".$r[0]['reply_url']."]".$r[0]['reply_author']."[/url] \n".$r[0]['body'];
1450
1451                         $_REQUEST['profile_uid'] = api_user();
1452                         $_REQUEST['type'] = 'wall';
1453                         $_REQUEST['api_source'] = true;
1454
1455                         if (!x($_REQUEST, "source"))
1456                                 $_REQUEST["source"] = api_source();
1457
1458                         require_once('mod/item.php');
1459                         item_post($a);
1460                 }
1461
1462                 // this should output the last post (the one we just posted).
1463                 $called_api = null;
1464                 return(api_status_show($a,$type));
1465         }
1466         api_register_func('api/statuses/retweet','api_statuses_repeat', true);
1467
1468         /**
1469          *
1470          */
1471         function api_statuses_destroy(&$a, $type){
1472                 if (api_user()===false) return false;
1473
1474                 $user_info = api_get_user($a);
1475
1476                 // params
1477                 $id = intval($a->argv[3]);
1478
1479                 if ($id == 0)
1480                         $id = intval($_REQUEST["id"]);
1481
1482                 // Hotot workaround
1483                 if ($id == 0)
1484                         $id = intval($a->argv[4]);
1485
1486                 logger('API: api_statuses_destroy: '.$id);
1487
1488                 $ret = api_statuses_show($a, $type);
1489
1490                 require_once('include/items.php');
1491                 drop_item($id, false);
1492
1493                 return($ret);
1494         }
1495         api_register_func('api/statuses/destroy','api_statuses_destroy', true);
1496
1497         /**
1498          *
1499          * http://developer.twitter.com/doc/get/statuses/mentions
1500          *
1501          */
1502         function api_statuses_mentions(&$a, $type){
1503                 if (api_user()===false) return false;
1504
1505                 unset($_REQUEST["user_id"]);
1506                 unset($_GET["user_id"]);
1507
1508                 unset($_REQUEST["screen_name"]);
1509                 unset($_GET["screen_name"]);
1510
1511                 $user_info = api_get_user($a);
1512                 // get last newtork messages
1513
1514
1515                 // params
1516                 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1517                 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1518                 if ($page<0) $page=0;
1519                 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1520                 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1521                 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1522
1523                 $start = $page*$count;
1524
1525                 // Ugly code - should be changed
1526                 $myurl = $a->get_baseurl() . '/profile/'. $a->user['nickname'];
1527                 $myurl = substr($myurl,strpos($myurl,'://')+3);
1528                 //$myurl = str_replace(array('www.','.'),array('','\\.'),$myurl);
1529                 $myurl = str_replace('www.','',$myurl);
1530                 $diasp_url = str_replace('/profile/','/u/',$myurl);
1531
1532                 if ($max_id > 0)
1533                         $sql_extra = ' AND `item`.`id` <= '.intval($max_id);
1534
1535                 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1536                         `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1537                         `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1538                         `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1539                         FROM `item`, `contact`
1540                         WHERE `item`.`uid` = %d AND `verb` = '%s'
1541                         AND NOT (`item`.`author-link` IN ('https://%s', 'http://%s'))
1542                         AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1543                         AND `contact`.`id` = `item`.`contact-id`
1544                         AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1545                         AND `item`.`parent` IN (SELECT `iid` from thread where uid = %d AND `mention` AND !`ignored`)
1546                         $sql_extra
1547                         AND `item`.`id`>%d
1548                         ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1549                         intval(api_user()),
1550                         dbesc(ACTIVITY_POST),
1551                         dbesc(protect_sprintf($myurl)),
1552                         dbesc(protect_sprintf($myurl)),
1553                         intval(api_user()),
1554                         intval($since_id),
1555                         intval($start), intval($count)
1556                 );
1557
1558                 $ret = api_format_items($r,$user_info);
1559
1560
1561                 $data = array('$statuses' => $ret);
1562                 switch($type){
1563                         case "atom":
1564                         case "rss":
1565                                 $data = api_rss_extra($a, $data, $user_info);
1566                                 break;
1567                         case "as":
1568                                 $as = api_format_as($a, $ret, $user_info);
1569                                 $as["title"] = $a->config['sitename']." Mentions";
1570                                 $as['link']['url'] = $a->get_baseurl()."/";
1571                                 return($as);
1572                                 break;
1573                 }
1574
1575                 return  api_apply_template("timeline", $type, $data);
1576         }
1577         api_register_func('api/statuses/mentions','api_statuses_mentions', true);
1578         api_register_func('api/statuses/replies','api_statuses_mentions', true);
1579
1580
1581         function api_statuses_user_timeline(&$a, $type){
1582                 if (api_user()===false) return false;
1583
1584                 $user_info = api_get_user($a);
1585                 // get last network messages
1586
1587                 logger("api_statuses_user_timeline: api_user: ". api_user() .
1588                            "\nuser_info: ".print_r($user_info, true) .
1589                            "\n_REQUEST:  ".print_r($_REQUEST, true),
1590                            LOGGER_DEBUG);
1591
1592                 // params
1593                 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1594                 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1595                 if ($page<0) $page=0;
1596                 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1597                 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1598                 $exclude_replies = (x($_REQUEST,'exclude_replies')?1:0);
1599                 $conversation_id = (x($_REQUEST,'conversation_id')?$_REQUEST['conversation_id']:0);
1600
1601                 $start = $page*$count;
1602
1603                 $sql_extra = '';
1604                 if ($user_info['self']==1)
1605                         $sql_extra .= " AND `item`.`wall` = 1 ";
1606
1607                 if ($exclude_replies > 0)
1608                         $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
1609                 if ($conversation_id > 0)
1610                         $sql_extra .= ' AND `item`.`parent` = '.intval($conversation_id);
1611
1612                 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1613                         `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1614                         `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1615                         `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1616                         FROM `item`, `contact`
1617                         WHERE `item`.`uid` = %d AND `verb` = '%s'
1618                         AND `item`.`contact-id` = %d
1619                         AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1620                         AND `contact`.`id` = `item`.`contact-id`
1621                         AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1622                         $sql_extra
1623                         AND `item`.`id`>%d
1624                         ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1625                         intval(api_user()),
1626                         dbesc(ACTIVITY_POST),
1627                         intval($user_info['cid']),
1628                         intval($since_id),
1629                         intval($start), intval($count)
1630                 );
1631
1632                 $ret = api_format_items($r,$user_info, true);
1633
1634                 $data = array('$statuses' => $ret);
1635                 switch($type){
1636                         case "atom":
1637                         case "rss":
1638                                 $data = api_rss_extra($a, $data, $user_info);
1639                 }
1640
1641                 return  api_apply_template("timeline", $type, $data);
1642         }
1643
1644         api_register_func('api/statuses/user_timeline','api_statuses_user_timeline', true);
1645
1646
1647         /**
1648          * Star/unstar an item
1649          * param: id : id of the item
1650          *
1651          * api v1 : https://web.archive.org/web/20131019055350/https://dev.twitter.com/docs/api/1/post/favorites/create/%3Aid
1652          */
1653         function api_favorites_create_destroy(&$a, $type){
1654                 if (api_user()===false) return false;
1655
1656                 # for versioned api.
1657                 # TODO: we need a better global soluton
1658                 $action_argv_id=2;
1659                 if ($a->argv[1]=="1.1") $action_argv_id=3;
1660
1661                 if ($a->argc<=$action_argv_id) die(api_error($a, $type, t("Invalid request.")));
1662                 $action = str_replace(".".$type,"",$a->argv[$action_argv_id]);
1663                 if ($a->argc==$action_argv_id+2) {
1664                         $itemid = intval($a->argv[$action_argv_id+1]);
1665                 } else {
1666                         $itemid = intval($_REQUEST['id']);
1667                 }
1668
1669                 $item = q("SELECT * FROM item WHERE id=%d AND uid=%d",
1670                                 $itemid, api_user());
1671
1672                 if ($item===false || count($item)==0) die(api_error($a, $type, t("Invalid item.")));
1673
1674                 switch($action){
1675                         case "create":
1676                                 $item[0]['starred']=1;
1677                                 break;
1678                         case "destroy":
1679                                 $item[0]['starred']=0;
1680                                 break;
1681                         default:
1682                                 die(api_error($a, $type, t("Invalid action. ".$action)));
1683                 }
1684                 $r = q("UPDATE item SET starred=%d WHERE id=%d AND uid=%d",
1685                                 $item[0]['starred'], $itemid, api_user());
1686
1687                 q("UPDATE thread SET starred=%d WHERE iid=%d AND uid=%d",
1688                         $item[0]['starred'], $itemid, api_user());
1689
1690                 if ($r===false) die(api_error($a, $type, t("DB error")));
1691
1692
1693                 $user_info = api_get_user($a);
1694                 $rets = api_format_items($item,$user_info);
1695                 $ret = $rets[0];
1696
1697                 $data = array('$status' => $ret);
1698                 switch($type){
1699                         case "atom":
1700                         case "rss":
1701                                 $data = api_rss_extra($a, $data, $user_info);
1702                 }
1703
1704                 return api_apply_template("status", $type, $data);
1705         }
1706
1707         api_register_func('api/favorites/create', 'api_favorites_create_destroy', true);
1708         api_register_func('api/favorites/destroy', 'api_favorites_create_destroy', true);
1709
1710         function api_favorites(&$a, $type){
1711                 global $called_api;
1712
1713                 if (api_user()===false) return false;
1714
1715                 $called_api= array();
1716
1717                 $user_info = api_get_user($a);
1718
1719                 // in friendica starred item are private
1720                 // return favorites only for self
1721                 logger('api_favorites: self:' . $user_info['self']);
1722
1723                 if ($user_info['self']==0) {
1724                         $ret = array();
1725                 } else {
1726                         $sql_extra = "";
1727
1728                         // params
1729                         $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1730                         $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1731                         $count = (x($_GET,'count')?$_GET['count']:20);
1732                         $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1733                         if ($page<0) $page=0;
1734
1735                         $start = $page*$count;
1736
1737                         if ($max_id > 0)
1738                                 $sql_extra .= ' AND `item`.`id` <= '.intval($max_id);
1739
1740                         $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1741                                 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1742                                 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1743                                 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1744                                 FROM `item`, `contact`
1745                                 WHERE `item`.`uid` = %d
1746                                 AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1747                                 AND `item`.`starred` = 1
1748                                 AND `contact`.`id` = `item`.`contact-id`
1749                                 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1750                                 $sql_extra
1751                                 AND `item`.`id`>%d
1752                                 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1753                                 intval(api_user()),
1754                                 intval($since_id),
1755                                 intval($start), intval($count)
1756                         );
1757
1758                         $ret = api_format_items($r,$user_info);
1759
1760                 }
1761
1762                 $data = array('$statuses' => $ret);
1763                 switch($type){
1764                         case "atom":
1765                         case "rss":
1766                                 $data = api_rss_extra($a, $data, $user_info);
1767                 }
1768
1769                 return  api_apply_template("timeline", $type, $data);
1770         }
1771
1772         api_register_func('api/favorites','api_favorites', true);
1773
1774
1775
1776
1777         function api_format_as($a, $ret, $user_info) {
1778
1779                 $as = array();
1780                 $as['title'] = $a->config['sitename']." Public Timeline";
1781                 $items = array();
1782                 foreach ($ret as $item) {
1783                         $singleitem["actor"]["displayName"] = $item["user"]["name"];
1784                         $singleitem["actor"]["id"] = $item["user"]["contact_url"];
1785                         $avatar[0]["url"] = $item["user"]["profile_image_url"];
1786                         $avatar[0]["rel"] = "avatar";
1787                         $avatar[0]["type"] = "";
1788                         $avatar[0]["width"] = 96;
1789                         $avatar[0]["height"] = 96;
1790                         $avatar[1]["url"] = $item["user"]["profile_image_url"];
1791                         $avatar[1]["rel"] = "avatar";
1792                         $avatar[1]["type"] = "";
1793                         $avatar[1]["width"] = 48;
1794                         $avatar[1]["height"] = 48;
1795                         $avatar[2]["url"] = $item["user"]["profile_image_url"];
1796                         $avatar[2]["rel"] = "avatar";
1797                         $avatar[2]["type"] = "";
1798                         $avatar[2]["width"] = 24;
1799                         $avatar[2]["height"] = 24;
1800                         $singleitem["actor"]["avatarLinks"] = $avatar;
1801
1802                         $singleitem["actor"]["image"]["url"] = $item["user"]["profile_image_url"];
1803                         $singleitem["actor"]["image"]["rel"] = "avatar";
1804                         $singleitem["actor"]["image"]["type"] = "";
1805                         $singleitem["actor"]["image"]["width"] = 96;
1806                         $singleitem["actor"]["image"]["height"] = 96;
1807                         $singleitem["actor"]["type"] = "person";
1808                         $singleitem["actor"]["url"] = $item["person"]["contact_url"];
1809                         $singleitem["actor"]["statusnet:profile_info"]["local_id"] = $item["user"]["id"];
1810                         $singleitem["actor"]["statusnet:profile_info"]["following"] = $item["user"]["following"] ? "true" : "false";
1811                         $singleitem["actor"]["statusnet:profile_info"]["blocking"] = "false";
1812                         $singleitem["actor"]["contact"]["preferredUsername"] = $item["user"]["screen_name"];
1813                         $singleitem["actor"]["contact"]["displayName"] = $item["user"]["name"];
1814                         $singleitem["actor"]["contact"]["addresses"] = "";
1815
1816                         $singleitem["body"] = $item["text"];
1817                         $singleitem["object"]["displayName"] = $item["text"];
1818                         $singleitem["object"]["id"] = $item["url"];
1819                         $singleitem["object"]["type"] = "note";
1820                         $singleitem["object"]["url"] = $item["url"];
1821                         //$singleitem["context"] =;
1822                         $singleitem["postedTime"] = date("c", strtotime($item["published"]));
1823                         $singleitem["provider"]["objectType"] = "service";
1824                         $singleitem["provider"]["displayName"] = "Test";
1825                         $singleitem["provider"]["url"] = "http://test.tld";
1826                         $singleitem["title"] = $item["text"];
1827                         $singleitem["verb"] = "post";
1828                         $singleitem["statusnet:notice_info"]["local_id"] = $item["id"];
1829                         $singleitem["statusnet:notice_info"]["source"] = $item["source"];
1830                         $singleitem["statusnet:notice_info"]["favorite"] = "false";
1831                         $singleitem["statusnet:notice_info"]["repeated"] = "false";
1832                         //$singleitem["original"] = $item;
1833                         $items[] = $singleitem;
1834                 }
1835                 $as['items'] = $items;
1836                 $as['link']['url'] = $a->get_baseurl()."/".$user_info["screen_name"]."/all";
1837                 $as['link']['rel'] = "alternate";
1838                 $as['link']['type'] = "text/html";
1839                 return($as);
1840         }
1841
1842         function api_format_messages($item, $recipient, $sender) {
1843                 // standard meta information
1844                 $ret=Array(
1845                                 'id'                    => $item['id'],
1846                                 'sender_id'             => $sender['id'] ,
1847                                 'text'                  => "",
1848                                 'recipient_id'          => $recipient['id'],
1849                                 'created_at'            => api_date($item['created']),
1850                                 'sender_screen_name'    => $sender['screen_name'],
1851                                 'recipient_screen_name' => $recipient['screen_name'],
1852                                 'sender'                => $sender,
1853                                 'recipient'             => $recipient,
1854                 );
1855
1856                 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1857                 unset($ret["sender"]["uid"]);
1858                 unset($ret["sender"]["self"]);
1859                 unset($ret["recipient"]["uid"]);
1860                 unset($ret["recipient"]["self"]);
1861
1862                 //don't send title to regular StatusNET requests to avoid confusing these apps
1863                 if (x($_GET, 'getText')) {
1864                         $ret['title'] = $item['title'] ;
1865                         if ($_GET["getText"] == "html") {
1866                                 $ret['text'] = bbcode($item['body'], false, false);
1867                         }
1868                         elseif ($_GET["getText"] == "plain") {
1869                                 //$ret['text'] = html2plain(bbcode($item['body'], false, false, true), 0);
1870                                 $ret['text'] = trim(html2plain(bbcode(api_clean_plain_items($item['body']), false, false, 2, true), 0));
1871                         }
1872                 }
1873                 else {
1874                         $ret['text'] = $item['title']."\n".html2plain(bbcode(api_clean_plain_items($item['body']), false, false, 2, true), 0);
1875                 }
1876                 if (isset($_GET["getUserObjects"]) && $_GET["getUserObjects"] == "false") {
1877                         unset($ret['sender']);
1878                         unset($ret['recipient']);
1879                 }
1880
1881                 return $ret;
1882         }
1883
1884         function api_convert_item($item) {
1885
1886                 $body = $item['body'];
1887                 $attachments = api_get_attachments($body);
1888
1889                 // Workaround for ostatus messages where the title is identically to the body
1890                 $html = bbcode(api_clean_plain_items($body), false, false, 2, true);
1891                 $statusbody = trim(html2plain($html, 0));
1892
1893                 // handle data: images
1894                 $statusbody = api_format_items_embeded_images($item,$statusbody);
1895
1896                 $statustitle = trim($item['title']);
1897
1898                 if (($statustitle != '') and (strpos($statusbody, $statustitle) !== false))
1899                         $statustext = trim($statusbody);
1900                 else
1901                         $statustext = trim($statustitle."\n\n".$statusbody);
1902
1903                 if (($item["network"] == NETWORK_FEED) and (strlen($statustext)> 1000))
1904                         $statustext = substr($statustext, 0, 1000)."... \n".$item["plink"];
1905
1906                 $statushtml = trim(bbcode($body, false, false));
1907
1908                 if ($item['title'] != "")
1909                         $statushtml = "<h4>".bbcode($item['title'])."</h4>\n".$statushtml;
1910
1911                 $entities = api_get_entitities($statustext, $body);
1912
1913                 return(array("text" => $statustext, "html" => $statushtml, "attachments" => $attachments, "entities" => $entities));
1914         }
1915
1916         function api_get_attachments(&$body) {
1917
1918                 $text = $body;
1919                 $text = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $text);
1920
1921                 $URLSearchString = "^\[\]";
1922                 $ret = preg_match_all("/\[img\]([$URLSearchString]*)\[\/img\]/ism", $text, $images);
1923
1924                 if (!$ret)
1925                         return false;
1926
1927                 $attachments = array();
1928
1929                 foreach ($images[1] AS $image) {
1930                         $imagedata = get_photo_info($image);
1931
1932                         if ($imagedata)
1933                                 $attachments[] = array("url" => $image, "mimetype" => $imagedata["mime"], "size" => $imagedata["size"]);
1934                 }
1935
1936                 if (strstr($_SERVER['HTTP_USER_AGENT'], "AndStatus"))
1937                         foreach ($images[0] AS $orig)
1938                                 $body = str_replace($orig, "", $body);
1939
1940                 return $attachments;
1941         }
1942
1943         function api_get_entitities(&$text, $bbcode) {
1944                 /*
1945                 To-Do:
1946                 * Links at the first character of the post
1947                 */
1948
1949                 $a = get_app();
1950
1951                 $include_entities = strtolower(x($_REQUEST,'include_entities')?$_REQUEST['include_entities']:"false");
1952
1953                 if ($include_entities != "true") {
1954                         require_once("mod/proxy.php");
1955
1956                         preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
1957
1958                         foreach ($images[1] AS $image) {
1959                                 $replace = proxy_url($image);
1960                                 $text = str_replace($image, $replace, $text);
1961                         }
1962                         return array();
1963                 }
1964
1965                 $bbcode = bb_CleanPictureLinks($bbcode);
1966
1967                 // Change pure links in text to bbcode uris
1968                 $bbcode = preg_replace("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", '$1[url=$2]$2[/url]', $bbcode);
1969
1970                 $entities = array();
1971                 $entities["hashtags"] = array();
1972                 $entities["symbols"] = array();
1973                 $entities["urls"] = array();
1974                 $entities["user_mentions"] = array();
1975
1976                 $URLSearchString = "^\[\]";
1977
1978                 $bbcode = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'#$2',$bbcode);
1979
1980                 $bbcode = preg_replace("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism",'[url=$1]$2[/url]',$bbcode);
1981                 //$bbcode = preg_replace("/\[url\](.*?)\[\/url\]/ism",'[url=$1]$1[/url]',$bbcode);
1982                 $bbcode = preg_replace("/\[video\](.*?)\[\/video\]/ism",'[url=$1]$1[/url]',$bbcode);
1983
1984                 $bbcode = preg_replace("/\[youtube\]([A-Za-z0-9\-_=]+)(.*?)\[\/youtube\]/ism",
1985                                         '[url=https://www.youtube.com/watch?v=$1]https://www.youtube.com/watch?v=$1[/url]', $bbcode);
1986                 $bbcode = preg_replace("/\[youtube\](.*?)\[\/youtube\]/ism",'[url=$1]$1[/url]',$bbcode);
1987
1988                 $bbcode = preg_replace("/\[vimeo\]([0-9]+)(.*?)\[\/vimeo\]/ism",
1989                                         '[url=https://vimeo.com/$1]https://vimeo.com/$1[/url]', $bbcode);
1990                 $bbcode = preg_replace("/\[vimeo\](.*?)\[\/vimeo\]/ism",'[url=$1]$1[/url]',$bbcode);
1991
1992                 $bbcode = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $bbcode);
1993
1994                 //preg_match_all("/\[url\]([$URLSearchString]*)\[\/url\]/ism", $bbcode, $urls1);
1995                 preg_match_all("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $bbcode, $urls);
1996
1997                 $ordered_urls = array();
1998                 foreach ($urls[1] AS $id=>$url) {
1999                         //$start = strpos($text, $url, $offset);
2000                         $start = iconv_strpos($text, $url, 0, "UTF-8");
2001                         if (!($start === false))
2002                                 $ordered_urls[$start] = array("url" => $url, "title" => $urls[2][$id]);
2003                 }
2004
2005                 ksort($ordered_urls);
2006
2007                 $offset = 0;
2008                 //foreach ($urls[1] AS $id=>$url) {
2009                 foreach ($ordered_urls AS $url) {
2010                         if ((substr($url["title"], 0, 7) != "http://") AND (substr($url["title"], 0, 8) != "https://") AND
2011                                 !strpos($url["title"], "http://") AND !strpos($url["title"], "https://"))
2012                                 $display_url = $url["title"];
2013                         else {
2014                                 $display_url = str_replace(array("http://www.", "https://www."), array("", ""), $url["url"]);
2015                                 $display_url = str_replace(array("http://", "https://"), array("", ""), $display_url);
2016
2017                                 if (strlen($display_url) > 26)
2018                                         $display_url = substr($display_url, 0, 25)."…";
2019                         }
2020
2021                         //$start = strpos($text, $url, $offset);
2022                         $start = iconv_strpos($text, $url["url"], $offset, "UTF-8");
2023                         if (!($start === false)) {
2024                                 $entities["urls"][] = array("url" => $url["url"],
2025                                                                 "expanded_url" => $url["url"],
2026                                                                 "display_url" => $display_url,
2027                                                                 "indices" => array($start, $start+strlen($url["url"])));
2028                                 $offset = $start + 1;
2029                         }
2030                 }
2031
2032                 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2033                 $ordered_images = array();
2034                 foreach ($images[1] AS $image) {
2035                         //$start = strpos($text, $url, $offset);
2036                         $start = iconv_strpos($text, $image, 0, "UTF-8");
2037                         if (!($start === false))
2038                                 $ordered_images[$start] = $image;
2039                 }
2040                 //$entities["media"] = array();
2041                 $offset = 0;
2042
2043                 foreach ($ordered_images AS $url) {
2044                         $display_url = str_replace(array("http://www.", "https://www."), array("", ""), $url);
2045                         $display_url = str_replace(array("http://", "https://"), array("", ""), $display_url);
2046
2047                         if (strlen($display_url) > 26)
2048                                 $display_url = substr($display_url, 0, 25)."…";
2049
2050                         $start = iconv_strpos($text, $url, $offset, "UTF-8");
2051                         if (!($start === false)) {
2052                                 $image = get_photo_info($url);
2053                                 if ($image) {
2054                                         // If image cache is activated, then use the following sizes:
2055                                         // thumb  (150), small (340), medium (600) and large (1024)
2056                                         if (!get_config("system", "proxy_disabled")) {
2057                                                 require_once("mod/proxy.php");
2058                                                 $media_url = proxy_url($url);
2059
2060                                                 $sizes = array();
2061                                                 $scale = scale_image($image[0], $image[1], 150);
2062                                                 $sizes["thumb"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2063
2064                                                 if (($image[0] > 150) OR ($image[1] > 150)) {
2065                                                         $scale = scale_image($image[0], $image[1], 340);
2066                                                         $sizes["small"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2067                                                 }
2068
2069                                                 $scale = scale_image($image[0], $image[1], 600);
2070                                                 $sizes["medium"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2071
2072                                                 if (($image[0] > 600) OR ($image[1] > 600)) {
2073                                                         $scale = scale_image($image[0], $image[1], 1024);
2074                                                         $sizes["large"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2075                                                 }
2076                                         } else {
2077                                                 $media_url = $url;
2078                                                 $sizes["medium"] = array("w" => $image[0], "h" => $image[1], "resize" => "fit");
2079                                         }
2080
2081                                         $entities["media"][] = array(
2082                                                                 "id" => $start+1,
2083                                                                 "id_str" => (string)$start+1,
2084                                                                 "indices" => array($start, $start+strlen($url)),
2085                                                                 "media_url" => normalise_link($media_url),
2086                                                                 "media_url_https" => $media_url,
2087                                                                 "url" => $url,
2088                                                                 "display_url" => $display_url,
2089                                                                 "expanded_url" => $url,
2090                                                                 "type" => "photo",
2091                                                                 "sizes" => $sizes);
2092                                 }
2093                                 $offset = $start + 1;
2094                         }
2095                 }
2096
2097                 return($entities);
2098         }
2099         function api_format_items_embeded_images($item, $text){
2100                 $a = get_app();
2101                 $text = preg_replace_callback(
2102                                 "|data:image/([^;]+)[^=]+=*|m",
2103                                 function($match) use ($a, $item) {
2104                                         return $a->get_baseurl()."/display/".$item['guid'];
2105                                 },
2106                                 $text);
2107                 return $text;
2108         }
2109
2110         function api_format_items($r,$user_info, $filter_user = false) {
2111
2112                 $a = get_app();
2113                 $ret = Array();
2114
2115                 foreach($r as $item) {
2116                         api_share_as_retweet($item);
2117
2118                         localize_item($item);
2119                         $status_user = api_item_get_user($a,$item);
2120
2121                         // Look if the posts are matching if they should be filtered by user id
2122                         if ($filter_user AND ($status_user["id"] != $user_info["id"]))
2123                                 continue;
2124
2125                         if ($item['thr-parent'] != $item['uri']) {
2126                                 $r = q("SELECT id FROM item WHERE uid=%d AND uri='%s' LIMIT 1",
2127                                         intval(api_user()),
2128                                         dbesc($item['thr-parent']));
2129                                 if ($r)
2130                                         $in_reply_to_status_id = intval($r[0]['id']);
2131                                 else
2132                                         $in_reply_to_status_id = intval($item['parent']);
2133
2134                                 $in_reply_to_status_id_str = (string) intval($item['parent']);
2135
2136                                 $in_reply_to_screen_name = NULL;
2137                                 $in_reply_to_user_id = NULL;
2138                                 $in_reply_to_user_id_str = NULL;
2139
2140                                 $r = q("SELECT `author-link` FROM item WHERE uid=%d AND id=%d LIMIT 1",
2141                                         intval(api_user()),
2142                                         intval($in_reply_to_status_id));
2143                                 if ($r) {
2144                                         $r = q("SELECT * FROM unique_contacts WHERE `url` = '%s'", dbesc(normalise_link($r[0]['author-link'])));
2145
2146                                         if ($r) {
2147                                                 if ($r[0]['nick'] == "")
2148                                                         $r[0]['nick'] = api_get_nick($r[0]["url"]);
2149
2150                                                 $in_reply_to_screen_name = (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']);
2151                                                 $in_reply_to_user_id = intval($r[0]['id']);
2152                                                 $in_reply_to_user_id_str = (string) intval($r[0]['id']);
2153                                         }
2154                                 }
2155                         } else {
2156                                 $in_reply_to_screen_name = NULL;
2157                                 $in_reply_to_user_id = NULL;
2158                                 $in_reply_to_status_id = NULL;
2159                                 $in_reply_to_user_id_str = NULL;
2160                                 $in_reply_to_status_id_str = NULL;
2161                         }
2162
2163                         $converted = api_convert_item($item);
2164
2165                         $status = array(
2166                                 'text'          => $converted["text"],
2167                                 'truncated' => False,
2168                                 'created_at'=> api_date($item['created']),
2169                                 'in_reply_to_status_id' => $in_reply_to_status_id,
2170                                 'in_reply_to_status_id_str' => $in_reply_to_status_id_str,
2171                                 'source'    => (($item['app']) ? $item['app'] : 'web'),
2172                                 'id'            => intval($item['id']),
2173                                 'id_str'        => (string) intval($item['id']),
2174                                 'in_reply_to_user_id' => $in_reply_to_user_id,
2175                                 'in_reply_to_user_id_str' => $in_reply_to_user_id_str,
2176                                 'in_reply_to_screen_name' => $in_reply_to_screen_name,
2177                                 'geo' => NULL,
2178                                 'favorited' => $item['starred'] ? true : false,
2179                                 'user' =>  $status_user ,
2180                                 //'entities' => NULL,
2181                                 'statusnet_html'                => $converted["html"],
2182                                 'statusnet_conversation_id'     => $item['parent'],
2183                         );
2184
2185                         if (count($converted["attachments"]) > 0)
2186                                 $status["attachments"] = $converted["attachments"];
2187
2188                         if (count($converted["entities"]) > 0)
2189                                 $status["entities"] = $converted["entities"];
2190
2191                         if (($item['item_network'] != "") AND ($status["source"] == 'web'))
2192                                 $status["source"] = network_to_name($item['item_network']);
2193                         else if (($item['item_network'] != "") AND (network_to_name($item['item_network']) != $status["source"]))
2194                                 $status["source"] = trim($status["source"].' ('.network_to_name($item['item_network']).')');
2195
2196
2197                         // Retweets are only valid for top postings
2198                         // It doesn't work reliable with the link if its a feed
2199                         $IsRetweet = ($item['owner-link'] != $item['author-link']);
2200                         if ($IsRetweet)
2201                                 $IsRetweet = (($item['owner-name'] != $item['author-name']) OR ($item['owner-avatar'] != $item['author-avatar']));
2202
2203                         if ($IsRetweet AND ($item["id"] == $item["parent"])) {
2204                                 $retweeted_status = $status;
2205                                 $retweeted_status["user"] = api_get_user($a,$item["author-link"]);
2206
2207                                 $status["retweeted_status"] = $retweeted_status;
2208                         }
2209
2210                         // "uid" and "self" are only needed for some internal stuff, so remove it from here
2211                         unset($status["user"]["uid"]);
2212                         unset($status["user"]["self"]);
2213
2214                         // 'geo' => array('type' => 'Point',
2215                         //                   'coordinates' => array((float) $notice->lat,
2216                         //                                          (float) $notice->lon));
2217
2218                         $ret[] = $status;
2219                 };
2220                 return $ret;
2221         }
2222
2223
2224         function api_account_rate_limit_status(&$a,$type) {
2225
2226                 $hash = array(
2227                           'reset_time_in_seconds' => strtotime('now + 1 hour'),
2228                           'remaining_hits' => (string) 150,
2229                           'hourly_limit' => (string) 150,
2230                           'reset_time' => api_date(datetime_convert('UTC','UTC','now + 1 hour',ATOM_TIME)),
2231                 );
2232                 if ($type == "xml")
2233                         $hash['resettime_in_seconds'] = $hash['reset_time_in_seconds'];
2234
2235                 return api_apply_template('ratelimit', $type, array('$hash' => $hash));
2236
2237         }
2238         api_register_func('api/account/rate_limit_status','api_account_rate_limit_status',true);
2239
2240         function api_help_test(&$a,$type) {
2241
2242                 if ($type == 'xml')
2243                         $ok = "true";
2244                 else
2245                         $ok = "ok";
2246
2247                 return api_apply_template('test', $type, array("$ok" => $ok));
2248
2249         }
2250         api_register_func('api/help/test','api_help_test',false);
2251
2252         function api_lists(&$a,$type) {
2253
2254                 $ret = array();
2255                 return array($ret);
2256         }
2257         api_register_func('api/lists','api_lists',true);
2258
2259         function api_lists_list(&$a,$type) {
2260
2261                 $ret = array();
2262                 return array($ret);
2263         }
2264         api_register_func('api/lists/list','api_lists_list',true);
2265
2266         /**
2267          *  https://dev.twitter.com/docs/api/1/get/statuses/friends
2268          *  This function is deprecated by Twitter
2269          *  returns: json, xml
2270          **/
2271         function api_statuses_f(&$a, $type, $qtype) {
2272                 if (api_user()===false) return false;
2273                 $user_info = api_get_user($a);
2274
2275                 if (x($_GET,'cursor') && $_GET['cursor']=='undefined'){
2276                         /* this is to stop Hotot to load friends multiple times
2277                         *  I'm not sure if I'm missing return something or
2278                         *  is a bug in hotot. Workaround, meantime
2279                         */
2280
2281                         /*$ret=Array();
2282                         return array('$users' => $ret);*/
2283                         return false;
2284                 }
2285
2286                 if($qtype == 'friends')
2287                         $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
2288                 if($qtype == 'followers')
2289                         $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
2290
2291                 // friends and followers only for self
2292                 if ($user_info['self'] == 0)
2293                         $sql_extra = " AND false ";
2294
2295                 $r = q("SELECT `nurl` FROM `contact` WHERE `uid` = %d AND `self` = 0 AND `blocked` = 0 AND `pending` = 0 $sql_extra",
2296                         intval(api_user())
2297                 );
2298
2299                 $ret = array();
2300                 foreach($r as $cid){
2301                         $user = api_get_user($a, $cid['nurl']);
2302                         // "uid" and "self" are only needed for some internal stuff, so remove it from here
2303                         unset($user["uid"]);
2304                         unset($user["self"]);
2305
2306                         if ($user)
2307                                 $ret[] = $user;
2308                 }
2309
2310                 return array('$users' => $ret);
2311
2312         }
2313         function api_statuses_friends(&$a, $type){
2314                 $data =  api_statuses_f($a,$type,"friends");
2315                 if ($data===false) return false;
2316                 return  api_apply_template("friends", $type, $data);
2317         }
2318         function api_statuses_followers(&$a, $type){
2319                 $data = api_statuses_f($a,$type,"followers");
2320                 if ($data===false) return false;
2321                 return  api_apply_template("friends", $type, $data);
2322         }
2323         api_register_func('api/statuses/friends','api_statuses_friends',true);
2324         api_register_func('api/statuses/followers','api_statuses_followers',true);
2325
2326
2327
2328
2329
2330
2331         function api_statusnet_config(&$a,$type) {
2332                 $name = $a->config['sitename'];
2333                 $server = $a->get_hostname();
2334                 $logo = $a->get_baseurl() . '/images/friendica-64.png';
2335                 $email = $a->config['admin_email'];
2336                 $closed = (($a->config['register_policy'] == REGISTER_CLOSED) ? 'true' : 'false');
2337                 $private = (($a->config['system']['block_public']) ? 'true' : 'false');
2338                 $textlimit = (string) (($a->config['max_import_size']) ? $a->config['max_import_size'] : 200000);
2339                 if($a->config['api_import_size'])
2340                         $texlimit = string($a->config['api_import_size']);
2341                 $ssl = (($a->config['system']['have_ssl']) ? 'true' : 'false');
2342                 $sslserver = (($ssl === 'true') ? str_replace('http:','https:',$a->get_baseurl()) : '');
2343
2344                 $config = array(
2345                         'site' => array('name' => $name,'server' => $server, 'theme' => 'default', 'path' => '',
2346                                 'logo' => $logo, 'fancy' => true, 'language' => 'en', 'email' => $email, 'broughtby' => '',
2347                                 'broughtbyurl' => '', 'timezone' => 'UTC', 'closed' => $closed, 'inviteonly' => false,
2348                                 'private' => $private, 'textlimit' => $textlimit, 'sslserver' => $sslserver, 'ssl' => $ssl,
2349                                 'shorturllength' => '30',
2350                                 'friendica' => array(
2351                                                 'FRIENDICA_PLATFORM' => FRIENDICA_PLATFORM,
2352                                                 'FRIENDICA_VERSION' => FRIENDICA_VERSION,
2353                                                 'DFRN_PROTOCOL_VERSION' => DFRN_PROTOCOL_VERSION,
2354                                                 'DB_UPDATE_VERSION' => DB_UPDATE_VERSION
2355                                                 )
2356                         ),
2357                 );
2358
2359                 return api_apply_template('config', $type, array('$config' => $config));
2360
2361         }
2362         api_register_func('api/statusnet/config','api_statusnet_config',false);
2363
2364         function api_statusnet_version(&$a,$type) {
2365
2366                 // liar
2367
2368                 if($type === 'xml') {
2369                         header("Content-type: application/xml");
2370                         echo '<?xml version="1.0" encoding="UTF-8"?>' . "\r\n" . '<version>0.9.7</version>' . "\r\n";
2371                         killme();
2372                 }
2373                 elseif($type === 'json') {
2374                         header("Content-type: application/json");
2375                         echo '"0.9.7"';
2376                         killme();
2377                 }
2378         }
2379         api_register_func('api/statusnet/version','api_statusnet_version',false);
2380
2381
2382         function api_ff_ids(&$a,$type,$qtype) {
2383                 if(! api_user())
2384                         return false;
2385
2386                 $user_info = api_get_user($a);
2387
2388                 if($qtype == 'friends')
2389                         $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
2390                 if($qtype == 'followers')
2391                         $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
2392
2393                 if (!$user_info["self"])
2394                         $sql_extra = " AND false ";
2395
2396                 $stringify_ids = (x($_REQUEST,'stringify_ids')?$_REQUEST['stringify_ids']:false);
2397
2398                 $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",
2399                         intval(api_user())
2400                 );
2401
2402                 if(is_array($r)) {
2403
2404                         if($type === 'xml') {
2405                                 header("Content-type: application/xml");
2406                                 echo '<?xml version="1.0" encoding="UTF-8"?>' . "\r\n" . '<ids>' . "\r\n";
2407                                 foreach($r as $rr)
2408                                         echo '<id>' . $rr['id'] . '</id>' . "\r\n";
2409                                 echo '</ids>' . "\r\n";
2410                                 killme();
2411                         }
2412                         elseif($type === 'json') {
2413                                 $ret = array();
2414                                 header("Content-type: application/json");
2415                                 foreach($r as $rr)
2416                                         if ($stringify_ids)
2417                                                 $ret[] = $rr['id'];
2418                                         else
2419                                                 $ret[] = intval($rr['id']);
2420
2421                                 echo json_encode($ret);
2422                                 killme();
2423                         }
2424                 }
2425         }
2426
2427         function api_friends_ids(&$a,$type) {
2428                 api_ff_ids($a,$type,'friends');
2429         }
2430         function api_followers_ids(&$a,$type) {
2431                 api_ff_ids($a,$type,'followers');
2432         }
2433         api_register_func('api/friends/ids','api_friends_ids',true);
2434         api_register_func('api/followers/ids','api_followers_ids',true);
2435
2436
2437         function api_direct_messages_new(&$a, $type) {
2438                 if (api_user()===false) return false;
2439
2440                 if (!x($_POST, "text") OR (!x($_POST,"screen_name") AND !x($_POST,"user_id"))) return;
2441
2442                 $sender = api_get_user($a);
2443
2444                 require_once("include/message.php");
2445
2446                 if ($_POST['screen_name']) {
2447                         $r = q("SELECT `id`, `nurl`, `network` FROM `contact` WHERE `uid`=%d AND `nick`='%s'",
2448                                         intval(api_user()),
2449                                         dbesc($_POST['screen_name']));
2450
2451                         // Selecting the id by priority, friendica first
2452                         api_best_nickname($r);
2453
2454                         $recipient = api_get_user($a, $r[0]['nurl']);
2455                 } else
2456                         $recipient = api_get_user($a, $_POST['user_id']);
2457
2458                 $replyto = '';
2459                 $sub     = '';
2460                 if (x($_REQUEST,'replyto')) {
2461                         $r = q('SELECT `parent-uri`, `title` FROM `mail` WHERE `uid`=%d AND `id`=%d',
2462                                         intval(api_user()),
2463                                         intval($_REQUEST['replyto']));
2464                         $replyto = $r[0]['parent-uri'];
2465                         $sub     = $r[0]['title'];
2466                 }
2467                 else {
2468                         if (x($_REQUEST,'title')) {
2469                                 $sub = $_REQUEST['title'];
2470                         }
2471                         else {
2472                                 $sub = ((strlen($_POST['text'])>10)?substr($_POST['text'],0,10)."...":$_POST['text']);
2473                         }
2474                 }
2475
2476                 $id = send_message($recipient['cid'], $_POST['text'], $sub, $replyto);
2477
2478                 if ($id>-1) {
2479                         $r = q("SELECT * FROM `mail` WHERE id=%d", intval($id));
2480                         $ret = api_format_messages($r[0], $recipient, $sender);
2481
2482                 } else {
2483                         $ret = array("error"=>$id);
2484                 }
2485
2486                 $data = Array('$messages'=>$ret);
2487
2488                 switch($type){
2489                         case "atom":
2490                         case "rss":
2491                                 $data = api_rss_extra($a, $data, $user_info);
2492                 }
2493
2494                 return  api_apply_template("direct_messages", $type, $data);
2495
2496         }
2497         api_register_func('api/direct_messages/new','api_direct_messages_new',true);
2498
2499         function api_direct_messages_box(&$a, $type, $box) {
2500                 if (api_user()===false) return false;
2501
2502
2503                 // params
2504                 $count = (x($_GET,'count')?$_GET['count']:20);
2505                 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
2506                 if ($page<0) $page=0;
2507
2508                 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
2509                 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
2510
2511                 $user_id = (x($_REQUEST,'user_id')?$_REQUEST['user_id']:"");
2512                 $screen_name = (x($_REQUEST,'screen_name')?$_REQUEST['screen_name']:"");
2513
2514                 //  caller user info
2515                 unset($_REQUEST["user_id"]);
2516                 unset($_GET["user_id"]);
2517
2518                 unset($_REQUEST["screen_name"]);
2519                 unset($_GET["screen_name"]);
2520
2521                 $user_info = api_get_user($a);
2522                 //$profile_url = $a->get_baseurl() . '/profile/' . $a->user['nickname'];
2523                 $profile_url = $user_info["url"];
2524
2525
2526                 // pagination
2527                 $start = $page*$count;
2528
2529                 // filters
2530                 if ($box=="sentbox") {
2531                         $sql_extra = "`mail`.`from-url`='".dbesc( $profile_url )."'";
2532                 }
2533                 elseif ($box=="conversation") {
2534                         $sql_extra = "`mail`.`parent-uri`='".dbesc( $_GET["uri"] )  ."'";
2535                 }
2536                 elseif ($box=="all") {
2537                         $sql_extra = "true";
2538                 }
2539                 elseif ($box=="inbox") {
2540                         $sql_extra = "`mail`.`from-url`!='".dbesc( $profile_url )."'";
2541                 }
2542
2543                 if ($max_id > 0)
2544                         $sql_extra .= ' AND `mail`.`id` <= '.intval($max_id);
2545
2546                 if ($user_id !="") {
2547                         $sql_extra .= ' AND `mail`.`contact-id` = ' . intval($user_id);
2548                 }
2549                 elseif($screen_name !=""){
2550                         $sql_extra .= " AND `contact`.`nick` = '" . dbesc($screen_name). "'";
2551                 }
2552
2553                 $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",
2554                                 intval(api_user()),
2555                                 intval($since_id),
2556                                 intval($start), intval($count)
2557                 );
2558
2559
2560                 $ret = Array();
2561                 foreach($r as $item) {
2562                         if ($box == "inbox" || $item['from-url'] != $profile_url){
2563                                 $recipient = $user_info;
2564                                 $sender = api_get_user($a,normalise_link($item['contact-url']));
2565                         }
2566                         elseif ($box == "sentbox" || $item['from-url'] == $profile_url){
2567                                 $recipient = api_get_user($a,normalise_link($item['contact-url']));
2568                                 $sender = $user_info;
2569
2570                         }
2571                         $ret[]=api_format_messages($item, $recipient, $sender);
2572                 }
2573
2574
2575                 $data = array('$messages' => $ret);
2576                 switch($type){
2577                         case "atom":
2578                         case "rss":
2579                                 $data = api_rss_extra($a, $data, $user_info);
2580                 }
2581
2582                 return  api_apply_template("direct_messages", $type, $data);
2583
2584         }
2585
2586         function api_direct_messages_sentbox(&$a, $type){
2587                 return api_direct_messages_box($a, $type, "sentbox");
2588         }
2589         function api_direct_messages_inbox(&$a, $type){
2590                 return api_direct_messages_box($a, $type, "inbox");
2591         }
2592         function api_direct_messages_all(&$a, $type){
2593                 return api_direct_messages_box($a, $type, "all");
2594         }
2595         function api_direct_messages_conversation(&$a, $type){
2596                 return api_direct_messages_box($a, $type, "conversation");
2597         }
2598         api_register_func('api/direct_messages/conversation','api_direct_messages_conversation',true);
2599         api_register_func('api/direct_messages/all','api_direct_messages_all',true);
2600         api_register_func('api/direct_messages/sent','api_direct_messages_sentbox',true);
2601         api_register_func('api/direct_messages','api_direct_messages_inbox',true);
2602
2603
2604
2605         function api_oauth_request_token(&$a, $type){
2606                 try{
2607                         $oauth = new FKOAuth1();
2608                         $r = $oauth->fetch_request_token(OAuthRequest::from_request());
2609                 }catch(Exception $e){
2610                         echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage()); killme();
2611                 }
2612                 echo $r;
2613                 killme();
2614         }
2615         function api_oauth_access_token(&$a, $type){
2616                 try{
2617                         $oauth = new FKOAuth1();
2618                         $r = $oauth->fetch_access_token(OAuthRequest::from_request());
2619                 }catch(Exception $e){
2620                         echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage()); killme();
2621                 }
2622                 echo $r;
2623                 killme();
2624         }
2625
2626         api_register_func('api/oauth/request_token', 'api_oauth_request_token', false);
2627         api_register_func('api/oauth/access_token', 'api_oauth_access_token', false);
2628
2629
2630         function api_fr_photos_list(&$a,$type) {
2631                 if (api_user()===false) return false;
2632                 $r = q("select distinct `resource-id` from photo where uid = %d and album != 'Contact Photos' ",
2633                         intval(local_user())
2634                 );
2635                 if($r) {
2636                         $ret = array();
2637                         foreach($r as $rr)
2638                                 $ret[] = $rr['resource-id'];
2639                         header("Content-type: application/json");
2640                         echo json_encode($ret);
2641                 }
2642                 killme();
2643         }
2644
2645         function api_fr_photo_detail(&$a,$type) {
2646                 if (api_user()===false) return false;
2647                 if(! $_REQUEST['photo_id']) return false;
2648                 $scale = ((array_key_exists('scale',$_REQUEST)) ? intval($_REQUEST['scale']) : 0);
2649                 $r = q("select * from photo where uid = %d and `resource-id` = '%s' and scale = %d limit 1",
2650                         intval(local_user()),
2651                         dbesc($_REQUEST['photo_id']),
2652                         intval($scale)
2653                 );
2654                 if($r) {
2655                         header("Content-type: application/json");
2656                         $r[0]['data'] = base64_encode($r[0]['data']);
2657                         echo json_encode($r[0]);
2658                 }
2659
2660                 killme();
2661         }
2662
2663         api_register_func('api/friendica/photos/list', 'api_fr_photos_list', true);
2664         api_register_func('api/friendica/photo', 'api_fr_photo_detail', true);
2665
2666
2667
2668 function api_share_as_retweet(&$item) {
2669         $body = trim($item["body"]);
2670
2671         // Skip if it isn't a pure repeated messages
2672         // Does it start with a share?
2673         if (strpos($body, "[share") > 0)
2674                 return(false);
2675
2676         // Does it end with a share?
2677         if (strlen($body) > (strrpos($body, "[/share]") + 8))
2678                 return(false);
2679
2680         $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$1",$body);
2681         // Skip if there is no shared message in there
2682         if ($body == $attributes)
2683                 return(false);
2684
2685         $author = "";
2686         preg_match("/author='(.*?)'/ism", $attributes, $matches);
2687         if ($matches[1] != "")
2688                 $author = html_entity_decode($matches[1],ENT_QUOTES,'UTF-8');
2689
2690         preg_match('/author="(.*?)"/ism', $attributes, $matches);
2691         if ($matches[1] != "")
2692                 $author = $matches[1];
2693
2694         $profile = "";
2695         preg_match("/profile='(.*?)'/ism", $attributes, $matches);
2696         if ($matches[1] != "")
2697                 $profile = $matches[1];
2698
2699         preg_match('/profile="(.*?)"/ism', $attributes, $matches);
2700         if ($matches[1] != "")
2701                 $profile = $matches[1];
2702
2703         $avatar = "";
2704         preg_match("/avatar='(.*?)'/ism", $attributes, $matches);
2705         if ($matches[1] != "")
2706                 $avatar = $matches[1];
2707
2708         preg_match('/avatar="(.*?)"/ism', $attributes, $matches);
2709         if ($matches[1] != "")
2710                 $avatar = $matches[1];
2711
2712         $link = "";
2713         preg_match("/link='(.*?)'/ism", $attributes, $matches);
2714         if ($matches[1] != "")
2715                 $link = $matches[1];
2716
2717         preg_match('/link="(.*?)"/ism', $attributes, $matches);
2718         if ($matches[1] != "")
2719                 $link = $matches[1];
2720
2721         $shared_body = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$2",$body);
2722
2723         if (($shared_body == "") OR ($profile == "") OR ($author == "") OR ($avatar == ""))
2724                 return(false);
2725
2726         $item["body"] = $shared_body;
2727         $item["author-name"] = $author;
2728         $item["author-link"] = $profile;
2729         $item["author-avatar"] = $avatar;
2730         $item["plink"] = $link;
2731
2732         return(true);
2733
2734 }
2735
2736 function api_get_nick($profile) {
2737 /* To-Do:
2738  - remove trailing jung from profile url
2739  - pump.io check has to check the website
2740 */
2741
2742         $nick = "";
2743
2744         $friendica = preg_replace("=https?://(.*)/profile/(.*)=ism", "$2", $profile);
2745         if ($friendica != $profile)
2746                 $nick = $friendica;
2747
2748         if (!$nick == "") {
2749                 $diaspora = preg_replace("=https?://(.*)/u/(.*)=ism", "$2", $profile);
2750                 if ($diaspora != $profile)
2751                         $nick = $diaspora;
2752         }
2753
2754         if (!$nick == "") {
2755                 $twitter = preg_replace("=https?://twitter.com/(.*)=ism", "$1", $profile);
2756                 if ($twitter != $profile)
2757                         $nick = $twitter;
2758         }
2759
2760
2761         if (!$nick == "") {
2762                 $StatusnetHost = preg_replace("=https?://(.*)/user/(.*)=ism", "$1", $profile);
2763                 if ($StatusnetHost != $profile) {
2764                         $StatusnetUser = preg_replace("=https?://(.*)/user/(.*)=ism", "$2", $profile);
2765                         if ($StatusnetUser != $profile) {
2766                                 $UserData = fetch_url("http://".$StatusnetHost."/api/users/show.json?user_id=".$StatusnetUser);
2767                                 $user = json_decode($UserData);
2768                                 if ($user)
2769                                         $nick = $user->screen_name;
2770                         }
2771                 }
2772         }
2773
2774         // To-Do: look at the page if its really a pumpio site
2775         //if (!$nick == "") {
2776         //      $pumpio = preg_replace("=https?://(.*)/(.*)/=ism", "$2", $profile."/");
2777         //      if ($pumpio != $profile)
2778         //              $nick = $pumpio;
2779                 //      <div class="media" id="profile-block" data-profile-id="acct:kabniel@microca.st">
2780
2781         //}
2782
2783         if ($nick != "") {
2784                 q("UPDATE unique_contacts SET nick = '%s' WHERE url = '%s'",
2785                         dbesc($nick), dbesc(normalise_link($profile)));
2786                 return($nick);
2787         }
2788
2789         return(false);
2790 }
2791
2792 function api_clean_plain_items($Text) {
2793         $include_entities = strtolower(x($_REQUEST,'include_entities')?$_REQUEST['include_entities']:"false");
2794
2795         $Text = bb_CleanPictureLinks($Text);
2796
2797         $URLSearchString = "^\[\]";
2798
2799         $Text = preg_replace("/([!#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'$1$3',$Text);
2800
2801         if ($include_entities == "true") {
2802                 $Text = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'[url=$1]$1[/url]',$Text);
2803         }
2804
2805         $Text = preg_replace_callback("((.*?)\[class=(.*?)\](.*?)\[\/class\])ism","api_cleanup_share",$Text);
2806         return($Text);
2807 }
2808
2809 function api_cleanup_share($shared) {
2810         if ($shared[2] != "type-link")
2811                 return($shared[0]);
2812
2813         if (!preg_match_all("/\[bookmark\=([^\]]*)\](.*?)\[\/bookmark\]/ism",$shared[3], $bookmark))
2814                 return($shared[0]);
2815
2816         $title = "";
2817         $link = "";
2818
2819         if (isset($bookmark[2][0]))
2820                 $title = $bookmark[2][0];
2821
2822         if (isset($bookmark[1][0]))
2823                 $link = $bookmark[1][0];
2824
2825         if (strpos($shared[1],$title) !== false)
2826                 $title = "";
2827
2828         if (strpos($shared[1],$link) !== false)
2829                 $link = "";
2830
2831         $text = trim($shared[1]);
2832
2833         //if (strlen($text) < strlen($title))
2834         if (($text == "") AND ($title != ""))
2835                 $text .= "\n\n".trim($title);
2836
2837         if ($link != "")
2838                 $text .= "\n".trim($link);
2839
2840         return(trim($text));
2841 }
2842
2843 function api_best_nickname(&$contacts) {
2844         $best_contact = array();
2845
2846         if (count($contact) == 0)
2847                 return;
2848
2849         foreach ($contacts AS $contact)
2850                 if ($contact["network"] == "") {
2851                         $contact["network"] = "dfrn";
2852                         $best_contact = array($contact);
2853                 }
2854
2855         if (sizeof($best_contact) == 0)
2856                 foreach ($contacts AS $contact)
2857                         if ($contact["network"] == "dfrn")
2858                                 $best_contact = array($contact);
2859
2860         if (sizeof($best_contact) == 0)
2861                 foreach ($contacts AS $contact)
2862                         if ($contact["network"] == "dspr")
2863                                 $best_contact = array($contact);
2864
2865         if (sizeof($best_contact) == 0)
2866                 foreach ($contacts AS $contact)
2867                         if ($contact["network"] == "stat")
2868                                 $best_contact = array($contact);
2869
2870         if (sizeof($best_contact) == 0)
2871                 foreach ($contacts AS $contact)
2872                         if ($contact["network"] == "pump")
2873                                 $best_contact = array($contact);
2874
2875         if (sizeof($best_contact) == 0)
2876                 foreach ($contacts AS $contact)
2877                         if ($contact["network"] == "twit")
2878                                 $best_contact = array($contact);
2879
2880         if (sizeof($best_contact) == 1)
2881                 $contacts = $best_contact;
2882         else
2883                 $contacts = array($contacts[0]);
2884 }
2885
2886 /*
2887 Not implemented by now:
2888 statuses/retweets_of_me
2889 friendships/create
2890 friendships/destroy
2891 friendships/exists
2892 friendships/show
2893 account/update_location
2894 account/update_profile_background_image
2895 account/update_profile_image
2896 blocks/create
2897 blocks/destroy
2898
2899 Not implemented in status.net:
2900 statuses/retweeted_to_me
2901 statuses/retweeted_by_me
2902 direct_messages/destroy
2903 account/end_session
2904 account/update_delivery_device
2905 notifications/follow
2906 notifications/leave
2907 blocks/exists
2908 blocks/blocking
2909 lists
2910 */