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