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