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