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