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