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