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