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