]> git.mxchange.org Git - friendica.git/blob - include/api.php
f4e744f0450c6ec011b978f0cf1142b62d753f7f
[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                 if (!isset($_REQUEST["source"]) OR ($_REQUEST["source"] == ""))
730                         $_REQUEST["source"] = "api";
731
732                 // call out normal post function
733
734                 require_once('mod/item.php');
735                 item_post($a);
736
737                 // this should output the last post (the one we just posted).
738                 return api_status_show($a,$type);
739         }
740         api_register_func('api/statuses/update','api_statuses_update', true);
741         api_register_func('api/statuses/update_with_media','api_statuses_update', true);
742
743
744         function api_status_show(&$a, $type){
745                 $user_info = api_get_user($a);
746
747                 logger('api_status_show: user_info: '.print_r($user_info, true), LOGGER_DEBUG);
748
749                 // get last public wall message
750                 $lastwall = q("SELECT `item`.*, `i`.`contact-id` as `reply_uid`, `i`.`author-link` AS `item-author`
751                                 FROM `item`, `item` as `i`
752                                 WHERE `item`.`contact-id` = %d
753                                         AND ((`item`.`author-link` IN ('%s', '%s')) OR (`item`.`owner-link` IN ('%s', '%s')))
754                                         AND `i`.`id` = `item`.`parent`
755                                         AND `item`.`type`!='activity'
756                                         AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''
757                                 ORDER BY `item`.`created` DESC
758                                 LIMIT 1",
759                                 intval($user_info['cid']),
760                                 dbesc($user_info['url']),
761                                 dbesc(normalise_link($user_info['url'])),
762                                 dbesc($user_info['url']),
763                                 dbesc(normalise_link($user_info['url']))
764                 );
765
766                 if (count($lastwall)>0){
767                         $lastwall = $lastwall[0];
768
769                         $in_reply_to_status_id = NULL;
770                         $in_reply_to_user_id = NULL;
771                         $in_reply_to_status_id_str = NULL;
772                         $in_reply_to_user_id_str = NULL;
773                         $in_reply_to_screen_name = NULL;
774                         if (intval($lastwall['parent']) != intval($lastwall['id'])) {
775                                 $in_reply_to_status_id= intval($lastwall['parent']);
776                                 $in_reply_to_status_id_str = (string) intval($lastwall['parent']);
777
778                                 $r = q("SELECT * FROM unique_contacts WHERE `url` = '%s'", dbesc(normalise_link($lastwall['item-author'])));
779                                 if ($r) {
780                                         if ($r[0]['nick'] == "")
781                                                 $r[0]['nick'] = api_get_nick($r[0]["url"]);
782
783                                         $in_reply_to_screen_name = (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']);
784                                         $in_reply_to_user_id = intval($r[0]['id']);
785                                         $in_reply_to_user_id_str = (string) intval($r[0]['id']);
786                                 }
787                         }
788
789                         // There seems to be situation, where both fields are identical:
790                         // https://github.com/friendica/friendica/issues/1010
791                         // This is a bugfix for that.
792                         if (intval($in_reply_to_status_id) == intval($lastwall['id'])) {
793                                 logger('api_status_show: this message should never appear: id: '.$lastwall['id'].' similar to reply-to: '.$in_reply_to_status_id, LOGGER_DEBUG);
794                                 $in_reply_to_status_id = NULL;
795                                 $in_reply_to_user_id = NULL;
796                                 $in_reply_to_status_id_str = NULL;
797                                 $in_reply_to_user_id_str = NULL;
798                                 $in_reply_to_screen_name = NULL;
799                         }
800
801                         $status_info = array(
802                                 'text' => trim(html2plain(bbcode(api_clean_plain_items($lastwall['body']), false, false, 2, true), 0)),
803                                 'truncated' => false,
804                                 'created_at' => api_date($lastwall['created']),
805                                 'in_reply_to_status_id' => $in_reply_to_status_id,
806                                 'in_reply_to_status_id_str' => $in_reply_to_status_id_str,
807                                 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
808                                 'id' => intval($lastwall['id']),
809                                 'id_str' => (string) $lastwall['id'],
810                                 'in_reply_to_user_id' => $in_reply_to_user_id,
811                                 'in_reply_to_user_id_str' => $in_reply_to_user_id_str,
812                                 'in_reply_to_screen_name' => $in_reply_to_screen_name,
813                                 'geo' => NULL,
814                                 'favorited' => false,
815                                 // attachments
816                                 'user' => $user_info,
817                                 'statusnet_html'                => trim(bbcode($lastwall['body'], false, false)),
818                                 'statusnet_conversation_id'     => $lastwall['parent'],
819                         );
820
821                         if ($lastwall['title'] != "")
822                                 $status_info['statusnet_html'] = "<h4>".bbcode($lastwall['title'])."</h4>\n".$status_info['statusnet_html'];
823
824                         $entities = api_get_entitities($status_info['text'], $lastwall['body']);
825                         if (count($entities) > 0)
826                                 $status_info['entities'] = $entities;
827
828                         if (($lastwall['item_network'] != "") AND ($status["source"] == 'web'))
829                                 $status_info["source"] = network_to_name($lastwall['item_network']);
830                         elseif (($lastwall['item_network'] != "") AND (network_to_name($lastwall['item_network']) != $status_info["source"]))
831                                 $status_info["source"] = trim($status_info["source"].' ('.network_to_name($lastwall['item_network']).')');
832
833                         // "uid" and "self" are only needed for some internal stuff, so remove it from here
834                         unset($status_info["user"]["uid"]);
835                         unset($status_info["user"]["self"]);
836                 }
837
838                 if ($type == "raw")
839                         return($status_info);
840
841                 return  api_apply_template("status", $type, array('$status' => $status_info));
842
843         }
844
845
846
847
848
849         /**
850          * Returns extended information of a given user, specified by ID or screen name as per the required id parameter.
851          * The author's most recent status will be returned inline.
852          * http://developer.twitter.com/doc/get/users/show
853          */
854         function api_users_show(&$a, $type){
855                 $user_info = api_get_user($a);
856
857                 $lastwall = q("SELECT `item`.*
858                                 FROM `item`, `contact`
859                                 WHERE `item`.`uid` = %d AND `verb` = '%s' AND `item`.`contact-id` = %d
860                                         AND ((`item`.`author-link` IN ('%s', '%s')) OR (`item`.`owner-link` IN ('%s', '%s')))
861                                         AND `contact`.`id`=`item`.`contact-id`
862                                         AND `type`!='activity'
863                                         AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''
864                                 ORDER BY `created` DESC
865                                 LIMIT 1",
866                                 intval(api_user()),
867                                 dbesc(ACTIVITY_POST),
868                                 intval($user_info['cid']),
869                                 dbesc($user_info['url']),
870                                 dbesc(normalise_link($user_info['url'])),
871                                 dbesc($user_info['url']),
872                                 dbesc(normalise_link($user_info['url']))
873                 );
874                 if (count($lastwall)>0){
875                         $lastwall = $lastwall[0];
876
877                         $in_reply_to_status_id = NULL;
878                         $in_reply_to_user_id = NULL;
879                         $in_reply_to_status_id_str = NULL;
880                         $in_reply_to_user_id_str = NULL;
881                         $in_reply_to_screen_name = NULL;
882                         if ($lastwall['parent']!=$lastwall['id']) {
883                                 $reply = q("SELECT `item`.`id`, `item`.`contact-id` as `reply_uid`, `contact`.`nick` as `reply_author`, `item`.`author-link` AS `item-author`
884                                                 FROM `item`,`contact` WHERE `contact`.`id`=`item`.`contact-id` AND `item`.`id` = %d", intval($lastwall['parent']));
885                                 if (count($reply)>0) {
886                                         $in_reply_to_status_id = intval($lastwall['parent']);
887                                         $in_reply_to_status_id_str = (string) intval($lastwall['parent']);
888
889                                         $r = q("SELECT * FROM unique_contacts WHERE `url` = '%s'", dbesc(normalise_link($reply[0]['item-author'])));
890                                         if ($r) {
891                                                 if ($r[0]['nick'] == "")
892                                                         $r[0]['nick'] = api_get_nick($r[0]["url"]);
893
894                                                 $in_reply_to_screen_name = (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']);
895                                                 $in_reply_to_user_id = intval($r[0]['id']);
896                                                 $in_reply_to_user_id_str = (string) intval($r[0]['id']);
897                                         }
898                                 }
899                         }
900                         $user_info['status'] = array(
901                                 'text' => trim(html2plain(bbcode(api_clean_plain_items($lastwall['body']), false, false, 2, true), 0)),
902                                 'truncated' => false,
903                                 'created_at' => api_date($lastwall['created']),
904                                 'in_reply_to_status_id' => $in_reply_to_status_id,
905                                 'in_reply_to_status_id_str' => $in_reply_to_status_id_str,
906                                 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
907                                 'id' => intval($lastwall['contact-id']),
908                                 'id_str' => (string) $lastwall['contact-id'],
909                                 'in_reply_to_user_id' => $in_reply_to_user_id,
910                                 'in_reply_to_user_id_str' => $in_reply_to_user_id_str,
911                                 'in_reply_to_screen_name' => $in_reply_to_screen_name,
912                                 'geo' => NULL,
913                                 'favorited' => false,
914                                 'statusnet_html'                => trim(bbcode($lastwall['body'], false, false)),
915                                 'statusnet_conversation_id'     => $lastwall['parent'],
916                         );
917
918                         if ($lastwall['title'] != "")
919                                 $user_info['statusnet_html'] = "<h4>".bbcode($lastwall['title'])."</h4>\n".$user_info['statusnet_html'];
920
921                         $entities = api_get_entitities($user_info['text'], $lastwall['body']);
922                         if (count($entities) > 0)
923                                 $user_info['entities'] = $entities;
924
925                         if (($lastwall['item_network'] != "") AND ($user_info["status"]["source"] == 'web'))
926                                 $user_info["status"]["source"] = network_to_name($lastwall['item_network']);
927                         if (($lastwall['item_network'] != "") AND (network_to_name($lastwall['item_network']) != $user_info["status"]["source"]))
928                                 $user_info["status"]["source"] = trim($user_info["status"]["source"].' ('.network_to_name($lastwall['item_network']).')');
929
930                 }
931
932                 // "uid" and "self" are only needed for some internal stuff, so remove it from here
933                 unset($user_info["uid"]);
934                 unset($user_info["self"]);
935
936                 return  api_apply_template("user", $type, array('$user' => $user_info));
937
938         }
939         api_register_func('api/users/show','api_users_show');
940
941
942         function api_users_search(&$a, $type) {
943                 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
944
945                 $userlist = array();
946
947                 if (isset($_GET["q"])) {
948                         $r = q("SELECT id FROM unique_contacts WHERE name='%s'", dbesc($_GET["q"]));
949                         if (!count($r))
950                                 $r = q("SELECT id FROM unique_contacts WHERE nick='%s'", dbesc($_GET["q"]));
951
952                         if (count($r)) {
953                                 foreach ($r AS $user) {
954                                         $user_info = api_get_user($a, $user["id"]);
955                                         //echo print_r($user_info, true)."\n";
956                                         $userdata = api_apply_template("user", $type, array('user' => $user_info));
957                                         $userlist[] = $userdata["user"];
958                                 }
959                                 $userlist = array("users" => $userlist);
960                         } else
961                                 die(api_error($a, $type, t("User not found.")));
962                 } else
963                         die(api_error($a, $type, t("User not found.")));
964
965                 return ($userlist);
966         }
967
968         api_register_func('api/users/search','api_users_search');
969
970         /**
971          *
972          * http://developer.twitter.com/doc/get/statuses/home_timeline
973          *
974          * TODO: Optional parameters
975          * TODO: Add reply info
976          */
977         function api_statuses_home_timeline(&$a, $type){
978                 if (api_user()===false) return false;
979
980                 unset($_REQUEST["user_id"]);
981                 unset($_GET["user_id"]);
982
983                 unset($_REQUEST["screen_name"]);
984                 unset($_GET["screen_name"]);
985
986                 $user_info = api_get_user($a);
987                 // get last newtork messages
988
989
990                 // params
991                 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
992                 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
993                 if ($page<0) $page=0;
994                 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
995                 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
996                 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
997                 $exclude_replies = (x($_REQUEST,'exclude_replies')?1:0);
998                 $conversation_id = (x($_REQUEST,'conversation_id')?$_REQUEST['conversation_id']:0);
999
1000                 $start = $page*$count;
1001
1002                 $sql_extra = '';
1003                 if ($max_id > 0)
1004                         $sql_extra .= ' AND `item`.`id` <= '.intval($max_id);
1005                 if ($exclude_replies > 0)
1006                         $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
1007                 if ($conversation_id > 0)
1008                         $sql_extra .= ' AND `item`.`parent` = '.intval($conversation_id);
1009
1010                 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1011                         `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1012                         `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1013                         `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1014                         FROM `item`, `contact`
1015                         WHERE `item`.`uid` = %d AND `verb` = '%s'
1016                         AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1017                         AND `contact`.`id` = `item`.`contact-id`
1018                         AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1019                         $sql_extra
1020                         AND `item`.`id`>%d
1021                         ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1022                         intval(api_user()),
1023                         dbesc(ACTIVITY_POST),
1024                         intval($since_id),
1025                         intval($start), intval($count)
1026                 );
1027
1028                 $ret = api_format_items($r,$user_info);
1029
1030                 // We aren't going to try to figure out at the item, group, and page
1031                 // level which items you've seen and which you haven't. If you're looking
1032                 // at the network timeline just mark everything seen. 
1033
1034                 $r = q("UPDATE `item` SET `unseen` = 0 
1035                         WHERE `unseen` = 1 AND `uid` = %d",
1036                         //intval($user_info['uid'])
1037                         intval(api_user())
1038                 );
1039
1040
1041                 $data = array('$statuses' => $ret);
1042                 switch($type){
1043                         case "atom":
1044                         case "rss":
1045                                 $data = api_rss_extra($a, $data, $user_info);
1046                                 break;
1047                         case "as":
1048                                 $as = api_format_as($a, $ret, $user_info);
1049                                 $as['title'] = $a->config['sitename']." Home Timeline";
1050                                 $as['link']['url'] = $a->get_baseurl()."/".$user_info["screen_name"]."/all";
1051                                 return($as);
1052                                 break;
1053                 }
1054
1055                 return  api_apply_template("timeline", $type, $data);
1056         }
1057         api_register_func('api/statuses/home_timeline','api_statuses_home_timeline', true);
1058         api_register_func('api/statuses/friends_timeline','api_statuses_home_timeline', true);
1059
1060         function api_statuses_public_timeline(&$a, $type){
1061                 if (api_user()===false) return false;
1062
1063                 $user_info = api_get_user($a);
1064                 // get last newtork messages
1065
1066
1067                 // params
1068                 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1069                 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1070                 if ($page<0) $page=0;
1071                 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1072                 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1073                 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1074                 $exclude_replies = (x($_REQUEST,'exclude_replies')?1:0);
1075                 $conversation_id = (x($_REQUEST,'conversation_id')?$_REQUEST['conversation_id']:0);
1076
1077                 $start = $page*$count;
1078
1079                 if ($max_id > 0)
1080                         $sql_extra = 'AND `item`.`id` <= '.intval($max_id);
1081                 if ($exclude_replies > 0)
1082                         $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
1083                 if ($conversation_id > 0)
1084                         $sql_extra .= ' AND `item`.`parent` = '.intval($conversation_id);
1085
1086                 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1087                         `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1088                         `contact`.`network`, `contact`.`thumb`, `contact`.`self`, `contact`.`writable`,
1089                         `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`,
1090                         `user`.`nickname`, `user`.`hidewall`
1091                         FROM `item` STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
1092                         STRAIGHT_JOIN `user` ON `user`.`uid` = `item`.`uid`
1093                         WHERE `verb` = '%s' AND `item`.`visible` = 1 AND `item`.`deleted` = 0 and `item`.`moderated` = 0
1094                         AND `item`.`allow_cid` = ''  AND `item`.`allow_gid` = ''
1095                         AND `item`.`deny_cid`  = '' AND `item`.`deny_gid`  = ''
1096                         AND `item`.`private` = 0 AND `item`.`wall` = 1 AND `user`.`hidewall` = 0
1097                         AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1098                         $sql_extra
1099                         AND `item`.`id`>%d
1100                         ORDER BY `item`.`id` DESC LIMIT %d, %d ",
1101                         dbesc(ACTIVITY_POST),
1102                         intval($since_id),
1103                         intval($start),
1104                         intval($count));
1105
1106                 $ret = api_format_items($r,$user_info);
1107
1108
1109                 $data = array('$statuses' => $ret);
1110                 switch($type){
1111                         case "atom":
1112                         case "rss":
1113                                 $data = api_rss_extra($a, $data, $user_info);
1114                                 break;
1115                         case "as":
1116                                 $as = api_format_as($a, $ret, $user_info);
1117                                 $as['title'] = $a->config['sitename']." Public Timeline";
1118                                 $as['link']['url'] = $a->get_baseurl()."/";
1119                                 return($as);
1120                                 break;
1121                 }
1122
1123                 return  api_apply_template("timeline", $type, $data);
1124         }
1125         api_register_func('api/statuses/public_timeline','api_statuses_public_timeline', true);
1126
1127         /**
1128          * 
1129          */
1130         function api_statuses_show(&$a, $type){
1131                 if (api_user()===false) return false;
1132
1133                 $user_info = api_get_user($a);
1134
1135                 // params
1136                 $id = intval($a->argv[3]);
1137
1138                 if ($id == 0)
1139                         $id = intval($_REQUEST["id"]);
1140
1141                 // Hotot workaround
1142                 if ($id == 0)
1143                         $id = intval($a->argv[4]);
1144
1145                 logger('API: api_statuses_show: '.$id);
1146
1147                 $conversation = (x($_REQUEST,'conversation')?1:0);
1148
1149                 $sql_extra = '';
1150                 if ($conversation)
1151                         $sql_extra .= " AND `item`.`parent` = %d ORDER BY `received` ASC ";
1152                 else
1153                         $sql_extra .= " AND `item`.`id` = %d";
1154
1155                 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1156                         `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1157                         `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1158                         `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1159                         FROM `item`, `contact`
1160                         WHERE `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1161                         AND `contact`.`id` = `item`.`contact-id` AND `item`.`uid` = %d AND `item`.`verb` = '%s'
1162                         AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1163                         $sql_extra",
1164                         intval(api_user()),
1165                         dbesc(ACTIVITY_POST),
1166                         intval($id)
1167                 );
1168
1169                 if (!$r)
1170                         die(api_error($a, $type, t("There is no status with this id.")));
1171
1172                 $ret = api_format_items($r,$user_info);
1173
1174                 if ($conversation) {
1175                         $data = array('$statuses' => $ret);
1176                         return api_apply_template("timeline", $type, $data);
1177                 } else {
1178                         $data = array('$status' => $ret[0]);
1179                         /*switch($type){
1180                                 case "atom":
1181                                 case "rss":
1182                                         $data = api_rss_extra($a, $data, $user_info);
1183                         }*/
1184                         return  api_apply_template("status", $type, $data);
1185                 }
1186         }
1187         api_register_func('api/statuses/show','api_statuses_show', true);
1188
1189
1190         /**
1191          *
1192          */
1193         function api_conversation_show(&$a, $type){
1194                 if (api_user()===false) return false;
1195
1196                 $user_info = api_get_user($a);
1197
1198                 // params
1199                 $id = intval($a->argv[3]);
1200                 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1201                 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1202                 if ($page<0) $page=0;
1203                 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1204                 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1205
1206                 $start = $page*$count;
1207
1208                 if ($id == 0)
1209                         $id = intval($_REQUEST["id"]);
1210
1211                 // Hotot workaround
1212                 if ($id == 0)
1213                         $id = intval($a->argv[4]);
1214
1215                 logger('API: api_conversation_show: '.$id);
1216
1217                 $sql_extra = '';
1218
1219                 if ($max_id > 0)
1220                         $sql_extra = ' AND `item`.`id` <= '.intval($max_id);
1221
1222                 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1223                         `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1224                         `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1225                         `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1226                         FROM `item` INNER JOIN (SELECT `uri`,`parent` FROM `item` WHERE `id` = %d) AS `temp1`
1227                         ON (`item`.`thr-parent` = `temp1`.`uri` AND `item`.`parent` = `temp1`.`parent`), `contact`
1228                         WHERE `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1229                         AND `item`.`uid` = %d AND `item`.`verb` = '%s' AND `contact`.`id` = `item`.`contact-id`
1230                         AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1231                         AND `item`.`id`>%d $sql_extra
1232                         ORDER BY `item`.`id` DESC LIMIT %d ,%d",
1233                         intval($id), intval(api_user()),
1234                         dbesc(ACTIVITY_POST),
1235                         intval($since_id),
1236                         intval($start), intval($count)
1237                 );
1238
1239                 if (!$r)
1240                         die(api_error($a, $type, t("There is no conversation with this id.")));
1241
1242                 $ret = api_format_items($r,$user_info);
1243
1244                 $data = array('$statuses' => $ret);
1245                 return api_apply_template("timeline", $type, $data);
1246         }
1247         api_register_func('api/conversation/show','api_conversation_show', true);
1248
1249
1250         /**
1251          *
1252          */
1253         function api_statuses_repeat(&$a, $type){
1254                 global $called_api;
1255
1256                 if (api_user()===false) return false;
1257
1258                 $user_info = api_get_user($a);
1259
1260                 // params
1261                 $id = intval($a->argv[3]);
1262
1263                 if ($id == 0)
1264                         $id = intval($_REQUEST["id"]);
1265
1266                 // Hotot workaround
1267                 if ($id == 0)
1268                         $id = intval($a->argv[4]);
1269
1270                 logger('API: api_statuses_repeat: '.$id);
1271
1272                 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`, `contact`.`nick` as `reply_author`,
1273                         `contact`.`name`, `contact`.`photo` as `reply_photo`, `contact`.`url` as `reply_url`, `contact`.`rel`,
1274                         `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1275                         `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1276                         FROM `item`, `contact`
1277                         WHERE `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1278                         AND `contact`.`id` = `item`.`contact-id`
1279                         AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1280                         $sql_extra
1281                         AND `item`.`id`=%d",
1282                         intval($id)
1283                 );
1284
1285                 if ($r[0]['body'] != "") {
1286                         if (!intval(get_config('system','old_share'))) {
1287                                 if (strpos($r[0]['body'], "[/share]") !== false) {
1288                                         $pos = strpos($r[0]['body'], "[share");
1289                                         $post = substr($r[0]['body'], $pos);
1290                                 } else {
1291                                         $post = "[share author='".str_replace("'", "&#039;", $r[0]['author-name']).
1292                                                         "' profile='".$r[0]['author-link'].
1293                                                         "' avatar='".$r[0]['author-avatar'].
1294                                                         "' link='".$r[0]['plink']."']";
1295                                         $post .= $r[0]['body'];
1296                                         $post .= "[/share]";
1297                                 }
1298                                 $_REQUEST['body'] = $post;
1299                         } else
1300                                 $_REQUEST['body'] = html_entity_decode("&#x2672; ", ENT_QUOTES, 'UTF-8')."[url=".$r[0]['reply_url']."]".$r[0]['reply_author']."[/url] \n".$r[0]['body'];
1301
1302                         $_REQUEST['profile_uid'] = api_user();
1303                         $_REQUEST['type'] = 'wall';
1304                         $_REQUEST['api_source'] = true;
1305
1306                         if (!isset($_REQUEST["source"]) OR ($_REQUEST["source"] == ""))
1307                                 $_REQUEST["source"] = "api";
1308
1309                         require_once('mod/item.php');
1310                         item_post($a);
1311                 }
1312
1313                 // this should output the last post (the one we just posted).
1314                 $called_api = null;
1315                 return(api_status_show($a,$type));
1316         }
1317         api_register_func('api/statuses/retweet','api_statuses_repeat', true);
1318
1319         /**
1320          *
1321          */
1322         function api_statuses_destroy(&$a, $type){
1323                 if (api_user()===false) return false;
1324
1325                 $user_info = api_get_user($a);
1326
1327                 // params
1328                 $id = intval($a->argv[3]);
1329
1330                 if ($id == 0)
1331                         $id = intval($_REQUEST["id"]);
1332
1333                 // Hotot workaround
1334                 if ($id == 0)
1335                         $id = intval($a->argv[4]);
1336
1337                 logger('API: api_statuses_destroy: '.$id);
1338
1339                 $ret = api_statuses_show($a, $type);
1340
1341                 require_once('include/items.php');
1342                 drop_item($id, false);
1343
1344                 return($ret);
1345         }
1346         api_register_func('api/statuses/destroy','api_statuses_destroy', true);
1347
1348         /**
1349          * 
1350          * http://developer.twitter.com/doc/get/statuses/mentions
1351          * 
1352          */
1353         function api_statuses_mentions(&$a, $type){
1354                 if (api_user()===false) return false;
1355
1356                 unset($_REQUEST["user_id"]);
1357                 unset($_GET["user_id"]);
1358
1359                 unset($_REQUEST["screen_name"]);
1360                 unset($_GET["screen_name"]);
1361
1362                 $user_info = api_get_user($a);
1363                 // get last newtork messages
1364
1365
1366                 // params
1367                 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1368                 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1369                 if ($page<0) $page=0;
1370                 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1371                 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1372                 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1373
1374                 $start = $page*$count;
1375
1376                 // Ugly code - should be changed
1377                 $myurl = $a->get_baseurl() . '/profile/'. $a->user['nickname'];
1378                 $myurl = substr($myurl,strpos($myurl,'://')+3);
1379                 //$myurl = str_replace(array('www.','.'),array('','\\.'),$myurl);
1380                 $myurl = str_replace('www.','',$myurl);
1381                 $diasp_url = str_replace('/profile/','/u/',$myurl);
1382
1383                 if ($max_id > 0)
1384                         $sql_extra = ' AND `item`.`id` <= '.intval($max_id);
1385
1386                 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1387                         `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1388                         `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1389                         `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1390                         FROM `item`, `contact`
1391                         WHERE `item`.`uid` = %d AND `verb` = '%s'
1392                         AND NOT (`item`.`author-link` IN ('https://%s', 'http://%s'))
1393                         AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1394                         AND `contact`.`id` = `item`.`contact-id`
1395                         AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1396                         AND `item`.`parent` IN (SELECT `iid` from thread where uid = %d AND `mention`)
1397                         $sql_extra
1398                         AND `item`.`id`>%d
1399                         ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1400                         intval(api_user()),
1401                         dbesc(ACTIVITY_POST),
1402                         dbesc(protect_sprintf($myurl)),
1403                         dbesc(protect_sprintf($myurl)),
1404                         intval(api_user()),
1405                         intval($since_id),
1406                         intval($start), intval($count)
1407                 );
1408
1409                 $ret = api_format_items($r,$user_info);
1410
1411
1412                 $data = array('$statuses' => $ret);
1413                 switch($type){
1414                         case "atom":
1415                         case "rss":
1416                                 $data = api_rss_extra($a, $data, $user_info);
1417                                 break;
1418                         case "as":
1419                                 $as = api_format_as($a, $ret, $user_info);
1420                                 $as["title"] = $a->config['sitename']." Mentions";
1421                                 $as['link']['url'] = $a->get_baseurl()."/";
1422                                 return($as);
1423                                 break;
1424                 }
1425
1426                 return  api_apply_template("timeline", $type, $data);
1427         }
1428         api_register_func('api/statuses/mentions','api_statuses_mentions', true);
1429         api_register_func('api/statuses/replies','api_statuses_mentions', true);
1430
1431
1432         function api_statuses_user_timeline(&$a, $type){
1433                 if (api_user()===false) return false;
1434
1435                 $user_info = api_get_user($a);
1436                 // get last network messages
1437
1438                 logger("api_statuses_user_timeline: api_user: ". api_user() .
1439                            "\nuser_info: ".print_r($user_info, true) .
1440                            "\n_REQUEST:  ".print_r($_REQUEST, true),
1441                            LOGGER_DEBUG);
1442
1443                 // params
1444                 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1445                 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1446                 if ($page<0) $page=0;
1447                 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1448                 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1449                 $exclude_replies = (x($_REQUEST,'exclude_replies')?1:0);
1450                 $conversation_id = (x($_REQUEST,'conversation_id')?$_REQUEST['conversation_id']:0);
1451
1452                 $start = $page*$count;
1453
1454                 $sql_extra = '';
1455                 if ($user_info['self']==1)
1456                         $sql_extra .= " AND `item`.`wall` = 1 ";
1457
1458                 if ($exclude_replies > 0)
1459                         $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
1460                 if ($conversation_id > 0)
1461                         $sql_extra .= ' AND `item`.`parent` = '.intval($conversation_id);
1462
1463                 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1464                         `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1465                         `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1466                         `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1467                         FROM `item`, `contact`
1468                         WHERE `item`.`uid` = %d AND `verb` = '%s'
1469                         AND `item`.`contact-id` = %d
1470                         AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1471                         AND `contact`.`id` = `item`.`contact-id`
1472                         AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1473                         $sql_extra
1474                         AND `item`.`id`>%d
1475                         ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1476                         intval(api_user()),
1477                         dbesc(ACTIVITY_POST),
1478                         intval($user_info['cid']),
1479                         intval($since_id),
1480                         intval($start), intval($count)
1481                 );
1482
1483                 $ret = api_format_items($r,$user_info, true);
1484
1485                 $data = array('$statuses' => $ret);
1486                 switch($type){
1487                         case "atom":
1488                         case "rss":
1489                                 $data = api_rss_extra($a, $data, $user_info);
1490                 }
1491
1492                 return  api_apply_template("timeline", $type, $data);
1493         }
1494
1495         api_register_func('api/statuses/user_timeline','api_statuses_user_timeline', true);
1496
1497
1498         function api_favorites(&$a, $type){
1499                 global $called_api;
1500
1501                 if (api_user()===false) return false;
1502
1503                 $called_api= array();
1504
1505                 $user_info = api_get_user($a);
1506
1507                 // in friendica starred item are private
1508                 // return favorites only for self
1509                 logger('api_favorites: self:' . $user_info['self']);
1510
1511                 if ($user_info['self']==0) {
1512                         $ret = array();
1513                 } else {
1514                         $sql_extra = "";
1515
1516                         // params
1517                         $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1518                         $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1519                         $count = (x($_GET,'count')?$_GET['count']:20);
1520                         $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1521                         if ($page<0) $page=0;
1522
1523                         $start = $page*$count;
1524
1525                         if ($max_id > 0)
1526                                 $sql_extra .= ' AND `item`.`id` <= '.intval($max_id);
1527
1528                         $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1529                                 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1530                                 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1531                                 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1532                                 FROM `item`, `contact`
1533                                 WHERE `item`.`uid` = %d AND `verb` = '%s'
1534                                 AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1535                                 AND `item`.`starred` = 1
1536                                 AND `contact`.`id` = `item`.`contact-id`
1537                                 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1538                                 $sql_extra
1539                                 AND `item`.`id`>%d
1540                                 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1541                                 intval(api_user()),
1542                                 dbesc(ACTIVITY_POST),
1543                                 intval($since_id),
1544                                 intval($start), intval($count)
1545                         );
1546
1547                         $ret = api_format_items($r,$user_info);
1548
1549                 }
1550
1551                 $data = array('$statuses' => $ret);
1552                 switch($type){
1553                         case "atom":
1554                         case "rss":
1555                                 $data = api_rss_extra($a, $data, $user_info);
1556                 }
1557
1558                 return  api_apply_template("timeline", $type, $data);
1559         }
1560
1561         api_register_func('api/favorites','api_favorites', true);
1562
1563         function api_format_as($a, $ret, $user_info) {
1564
1565                 $as = array();
1566                 $as['title'] = $a->config['sitename']." Public Timeline";
1567                 $items = array();
1568                 foreach ($ret as $item) {
1569                         $singleitem["actor"]["displayName"] = $item["user"]["name"];
1570                         $singleitem["actor"]["id"] = $item["user"]["contact_url"];
1571                         $avatar[0]["url"] = $item["user"]["profile_image_url"];
1572                         $avatar[0]["rel"] = "avatar";
1573                         $avatar[0]["type"] = "";
1574                         $avatar[0]["width"] = 96;
1575                         $avatar[0]["height"] = 96;
1576                         $avatar[1]["url"] = $item["user"]["profile_image_url"];
1577                         $avatar[1]["rel"] = "avatar";
1578                         $avatar[1]["type"] = "";
1579                         $avatar[1]["width"] = 48;
1580                         $avatar[1]["height"] = 48;
1581                         $avatar[2]["url"] = $item["user"]["profile_image_url"];
1582                         $avatar[2]["rel"] = "avatar";
1583                         $avatar[2]["type"] = "";
1584                         $avatar[2]["width"] = 24;
1585                         $avatar[2]["height"] = 24;
1586                         $singleitem["actor"]["avatarLinks"] = $avatar;
1587
1588                         $singleitem["actor"]["image"]["url"] = $item["user"]["profile_image_url"];
1589                         $singleitem["actor"]["image"]["rel"] = "avatar";
1590                         $singleitem["actor"]["image"]["type"] = "";
1591                         $singleitem["actor"]["image"]["width"] = 96;
1592                         $singleitem["actor"]["image"]["height"] = 96;
1593                         $singleitem["actor"]["type"] = "person";
1594                         $singleitem["actor"]["url"] = $item["person"]["contact_url"];
1595                         $singleitem["actor"]["statusnet:profile_info"]["local_id"] = $item["user"]["id"];
1596                         $singleitem["actor"]["statusnet:profile_info"]["following"] = $item["user"]["following"] ? "true" : "false";
1597                         $singleitem["actor"]["statusnet:profile_info"]["blocking"] = "false";
1598                         $singleitem["actor"]["contact"]["preferredUsername"] = $item["user"]["screen_name"];
1599                         $singleitem["actor"]["contact"]["displayName"] = $item["user"]["name"];
1600                         $singleitem["actor"]["contact"]["addresses"] = "";
1601
1602                         $singleitem["body"] = $item["text"];
1603                         $singleitem["object"]["displayName"] = $item["text"];
1604                         $singleitem["object"]["id"] = $item["url"];
1605                         $singleitem["object"]["type"] = "note";
1606                         $singleitem["object"]["url"] = $item["url"];
1607                         //$singleitem["context"] =;
1608                         $singleitem["postedTime"] = date("c", strtotime($item["published"]));
1609                         $singleitem["provider"]["objectType"] = "service";
1610                         $singleitem["provider"]["displayName"] = "Test";
1611                         $singleitem["provider"]["url"] = "http://test.tld";
1612                         $singleitem["title"] = $item["text"];
1613                         $singleitem["verb"] = "post";
1614                         $singleitem["statusnet:notice_info"]["local_id"] = $item["id"];
1615                         $singleitem["statusnet:notice_info"]["source"] = $item["source"];
1616                         $singleitem["statusnet:notice_info"]["favorite"] = "false";
1617                         $singleitem["statusnet:notice_info"]["repeated"] = "false";
1618                         //$singleitem["original"] = $item;
1619                         $items[] = $singleitem;
1620                 }
1621                 $as['items'] = $items;
1622                 $as['link']['url'] = $a->get_baseurl()."/".$user_info["screen_name"]."/all";
1623                 $as['link']['rel'] = "alternate";
1624                 $as['link']['type'] = "text/html";
1625                 return($as);
1626         }
1627
1628         function api_format_messages($item, $recipient, $sender) {
1629                 // standard meta information
1630                 $ret=Array(
1631                                 'id'                    => $item['id'],
1632                                 'sender_id'             => $sender['id'] ,
1633                                 'text'                  => "",
1634                                 'recipient_id'          => $recipient['id'],
1635                                 'created_at'            => api_date($item['created']),
1636                                 'sender_screen_name'    => $sender['screen_name'],
1637                                 'recipient_screen_name' => $recipient['screen_name'],
1638                                 'sender'                => $sender,
1639                                 'recipient'             => $recipient,
1640                 );
1641
1642                 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1643                 unset($ret["sender"]["uid"]);
1644                 unset($ret["sender"]["self"]);
1645                 unset($ret["recipient"]["uid"]);
1646                 unset($ret["recipient"]["self"]);
1647
1648                 //don't send title to regular StatusNET requests to avoid confusing these apps
1649                 if (x($_GET, 'getText')) {
1650                         $ret['title'] = $item['title'] ;
1651                         if ($_GET["getText"] == "html") {
1652                                 $ret['text'] = bbcode($item['body'], false, false);
1653                         }
1654                         elseif ($_GET["getText"] == "plain") {
1655                                 //$ret['text'] = html2plain(bbcode($item['body'], false, false, true), 0);
1656                                 $ret['text'] = trim(html2plain(bbcode(api_clean_plain_items($item['body']), false, false, 2, true), 0));
1657                         }
1658                 }
1659                 else {
1660                         $ret['text'] = $item['title']."\n".html2plain(bbcode(api_clean_plain_items($item['body']), false, false, 2, true), 0);
1661                 }
1662                 if (isset($_GET["getUserObjects"]) && $_GET["getUserObjects"] == "false") {
1663                         unset($ret['sender']);
1664                         unset($ret['recipient']);
1665                 }
1666
1667                 return $ret;
1668         }
1669
1670         function api_get_entitities(&$text, $bbcode) {
1671                 /*
1672                 To-Do:
1673                 * Links at the first character of the post
1674                 */
1675
1676                 $a = get_app();
1677
1678                 $include_entities = strtolower(x($_REQUEST,'include_entities')?$_REQUEST['include_entities']:"false");
1679
1680                 if ($include_entities != "true") {
1681                         require_once("mod/proxy.php");
1682
1683                         preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
1684
1685                         foreach ($images[1] AS $image) {
1686                                 $replace = proxy_url($image);
1687                                 $text = str_replace($image, $replace, $text);
1688                         }
1689                         return array();
1690                 }
1691
1692                 $bbcode = bb_CleanPictureLinks($bbcode);
1693
1694                 // Change pure links in text to bbcode uris
1695                 $bbcode = preg_replace("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", '$1[url=$2]$2[/url]', $bbcode);
1696
1697                 $entities = array();
1698                 $entities["hashtags"] = array();
1699                 $entities["symbols"] = array();
1700                 $entities["urls"] = array();
1701                 $entities["user_mentions"] = array();
1702
1703                 $URLSearchString = "^\[\]";
1704
1705                 $bbcode = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'#$2',$bbcode);
1706
1707                 $bbcode = preg_replace("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism",'[url=$1]$2[/url]',$bbcode);
1708                 //$bbcode = preg_replace("/\[url\](.*?)\[\/url\]/ism",'[url=$1]$1[/url]',$bbcode);
1709                 $bbcode = preg_replace("/\[video\](.*?)\[\/video\]/ism",'[url=$1]$1[/url]',$bbcode);
1710
1711                 $bbcode = preg_replace("/\[youtube\]([A-Za-z0-9\-_=]+)(.*?)\[\/youtube\]/ism",
1712                                         '[url=https://www.youtube.com/watch?v=$1]https://www.youtube.com/watch?v=$1[/url]', $bbcode);
1713                 $bbcode = preg_replace("/\[youtube\](.*?)\[\/youtube\]/ism",'[url=$1]$1[/url]',$bbcode);
1714
1715                 $bbcode = preg_replace("/\[vimeo\]([0-9]+)(.*?)\[\/vimeo\]/ism",
1716                                         '[url=https://vimeo.com/$1]https://vimeo.com/$1[/url]', $bbcode);
1717                 $bbcode = preg_replace("/\[vimeo\](.*?)\[\/vimeo\]/ism",'[url=$1]$1[/url]',$bbcode);
1718
1719                 $bbcode = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $bbcode);
1720
1721                 //preg_match_all("/\[url\]([$URLSearchString]*)\[\/url\]/ism", $bbcode, $urls1);
1722                 preg_match_all("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $bbcode, $urls);
1723
1724                 $ordered_urls = array();
1725                 foreach ($urls[1] AS $id=>$url) {
1726                         //$start = strpos($text, $url, $offset);
1727                         $start = iconv_strpos($text, $url, 0, "UTF-8");
1728                         if (!($start === false))
1729                                 $ordered_urls[$start] = array("url" => $url, "title" => $urls[2][$id]);
1730                 }
1731
1732                 ksort($ordered_urls);
1733
1734                 $offset = 0;
1735                 //foreach ($urls[1] AS $id=>$url) {
1736                 foreach ($ordered_urls AS $url) {
1737                         if ((substr($url["title"], 0, 7) != "http://") AND (substr($url["title"], 0, 8) != "https://") AND
1738                                 !strpos($url["title"], "http://") AND !strpos($url["title"], "https://"))
1739                                 $display_url = $url["title"];
1740                         else {
1741                                 $display_url = str_replace(array("http://www.", "https://www."), array("", ""), $url["url"]);
1742                                 $display_url = str_replace(array("http://", "https://"), array("", ""), $display_url);
1743
1744                                 if (strlen($display_url) > 26)
1745                                         $display_url = substr($display_url, 0, 25)."…";
1746                         }
1747
1748                         //$start = strpos($text, $url, $offset);
1749                         $start = iconv_strpos($text, $url["url"], $offset, "UTF-8");
1750                         if (!($start === false)) {
1751                                 $entities["urls"][] = array("url" => $url["url"],
1752                                                                 "expanded_url" => $url["url"],
1753                                                                 "display_url" => $display_url,
1754                                                                 "indices" => array($start, $start+strlen($url["url"])));
1755                                 $offset = $start + 1;
1756                         }
1757                 }
1758
1759                 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
1760                 $ordered_images = array();
1761                 foreach ($images[1] AS $image) {
1762                         //$start = strpos($text, $url, $offset);
1763                         $start = iconv_strpos($text, $image, 0, "UTF-8");
1764                         if (!($start === false))
1765                                 $ordered_images[$start] = $image;
1766                 }
1767                 //$entities["media"] = array();
1768                 $offset = 0;
1769
1770                 foreach ($ordered_images AS $url) {
1771                         $display_url = str_replace(array("http://www.", "https://www."), array("", ""), $url);
1772                         $display_url = str_replace(array("http://", "https://"), array("", ""), $display_url);
1773
1774                         if (strlen($display_url) > 26)
1775                                 $display_url = substr($display_url, 0, 25)."…";
1776
1777                         $start = iconv_strpos($text, $url, $offset, "UTF-8");
1778                         if (!($start === false)) {
1779                                 require_once("include/Photo.php");
1780                                 $image = get_photo_info($url);
1781                                 if ($image) {
1782                                         // If image cache is activated, then use the following sizes:
1783                                         // thumb  (150), small (340), medium (600) and large (1024)
1784                                         if (!get_config("system", "proxy_disabled")) {
1785                                                 require_once("mod/proxy.php");
1786                                                 $media_url = proxy_url($url);
1787
1788                                                 $sizes = array();
1789                                                 $scale = scale_image($image[0], $image[1], 150);
1790                                                 $sizes["thumb"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
1791
1792                                                 if (($image[0] > 150) OR ($image[1] > 150)) {
1793                                                         $scale = scale_image($image[0], $image[1], 340);
1794                                                         $sizes["small"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
1795                                                 }
1796
1797                                                 $scale = scale_image($image[0], $image[1], 600);
1798                                                 $sizes["medium"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
1799
1800                                                 if (($image[0] > 600) OR ($image[1] > 600)) {
1801                                                         $scale = scale_image($image[0], $image[1], 1024);
1802                                                         $sizes["large"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
1803                                                 }
1804                                         } else {
1805                                                 $media_url = $url;
1806                                                 $sizes["medium"] = array("w" => $image[0], "h" => $image[1], "resize" => "fit");
1807                                         }
1808
1809                                         $entities["media"][] = array(
1810                                                                 "id" => $start+1,
1811                                                                 "id_str" => (string)$start+1,
1812                                                                 "indices" => array($start, $start+strlen($url)),
1813                                                                 "media_url" => normalise_link($media_url),
1814                                                                 "media_url_https" => $media_url,
1815                                                                 "url" => $url,
1816                                                                 "display_url" => $display_url,
1817                                                                 "expanded_url" => $url,
1818                                                                 "type" => "photo",
1819                                                                 "sizes" => $sizes);
1820                                 }
1821                                 $offset = $start + 1;
1822                         }
1823                 }
1824
1825                 return($entities);
1826         }
1827
1828         function api_format_items($r,$user_info, $filter_user = false) {
1829
1830                 $a = get_app();
1831                 $ret = Array();
1832
1833                 foreach($r as $item) {
1834                         api_share_as_retweet($a, api_user(), $item);
1835
1836                         localize_item($item);
1837                         $status_user = api_item_get_user($a,$item);
1838
1839                         // Look if the posts are matching if they should be filtered by user id
1840                         if ($filter_user AND ($status_user["id"] != $user_info["id"]))
1841                                 continue;
1842
1843                         if ($item['thr-parent'] != $item['uri']) {
1844                                 $r = q("SELECT id FROM item WHERE uid=%d AND uri='%s' LIMIT 1",
1845                                         intval(api_user()),
1846                                         dbesc($item['thr-parent']));
1847                                 if ($r)
1848                                         $in_reply_to_status_id = intval($r[0]['id']);
1849                                 else
1850                                         $in_reply_to_status_id = intval($item['parent']);
1851
1852                                 $in_reply_to_status_id_str = (string) intval($item['parent']);
1853
1854                                 $in_reply_to_screen_name = NULL;
1855                                 $in_reply_to_user_id = NULL;
1856                                 $in_reply_to_user_id_str = NULL;
1857
1858                                 $r = q("SELECT `author-link` FROM item WHERE uid=%d AND id=%d LIMIT 1",
1859                                         intval(api_user()),
1860                                         intval($in_reply_to_status_id));
1861                                 if ($r) {
1862                                         $r = q("SELECT * FROM unique_contacts WHERE `url` = '%s'", dbesc(normalise_link($r[0]['author-link'])));
1863
1864                                         if ($r) {
1865                                                 if ($r[0]['nick'] == "")
1866                                                         $r[0]['nick'] = api_get_nick($r[0]["url"]);
1867
1868                                                 $in_reply_to_screen_name = (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']);
1869                                                 $in_reply_to_user_id = intval($r[0]['id']);
1870                                                 $in_reply_to_user_id_str = (string) intval($r[0]['id']);
1871                                         }
1872                                 }
1873                         } else {
1874                                 $in_reply_to_screen_name = NULL;
1875                                 $in_reply_to_user_id = NULL;
1876                                 $in_reply_to_status_id = NULL;
1877                                 $in_reply_to_user_id_str = NULL;
1878                                 $in_reply_to_status_id_str = NULL;
1879                         }
1880
1881                         // Workaround for ostatus messages where the title is identically to the body
1882                         //$statusbody = trim(html2plain(bbcode(api_clean_plain_items($item['body']), false, false, 5, true), 0));
1883                         $html = bbcode(api_clean_plain_items($item['body']), false, false, 2, true);
1884                         $statusbody = trim(html2plain($html, 0));
1885
1886                         $statustitle = trim($item['title']);
1887
1888                         if (($statustitle != '') and (strpos($statusbody, $statustitle) !== false))
1889                                 $statustext = trim($statusbody);
1890                         else
1891                                 $statustext = trim($statustitle."\n\n".$statusbody);
1892
1893                         if (($item["network"] == NETWORK_FEED) and (strlen($statustext)> 1000))
1894                                 $statustext = substr($statustext, 0, 1000)."... \n".$item["plink"];
1895
1896                         $status = array(
1897                                 'text'          => $statustext,
1898                                 'truncated' => False,
1899                                 'created_at'=> api_date($item['created']),
1900                                 'in_reply_to_status_id' => $in_reply_to_status_id,
1901                                 'in_reply_to_status_id_str' => $in_reply_to_status_id_str,
1902                                 'source'    => (($item['app']) ? $item['app'] : 'web'),
1903                                 'id'            => intval($item['id']),
1904                                 'id_str'        => (string) intval($item['id']),
1905                                 'in_reply_to_user_id' => $in_reply_to_user_id,
1906                                 'in_reply_to_user_id_str' => $in_reply_to_user_id_str,
1907                                 'in_reply_to_screen_name' => $in_reply_to_screen_name,
1908                                 'geo' => NULL,
1909                                 'favorited' => $item['starred'] ? true : false,
1910                                 //'attachments' => array(),
1911                                 'user' =>  $status_user ,
1912                                 //'entities' => NULL,
1913                                 'statusnet_html'                => trim(bbcode($item['body'], false, false)),
1914                                 'statusnet_conversation_id'     => $item['parent'],
1915                         );
1916
1917                         if ($item['title'] != "")
1918                                 $status['statusnet_html'] = "<h4>".bbcode($item['title'])."</h4>\n".$status['statusnet_html'];
1919
1920                         $entities = api_get_entitities($status['text'], $item['body']);
1921                         if (count($entities) > 0)
1922                                 $status['entities'] = $entities;
1923
1924                         if (($item['item_network'] != "") AND ($status["source"] == 'web'))
1925                                 $status["source"] = network_to_name($item['item_network']);
1926                         else if (($item['item_network'] != "") AND (network_to_name($item['item_network']) != $status["source"]))
1927                                 $status["source"] = trim($status["source"].' ('.network_to_name($item['item_network']).')');
1928
1929
1930                         // Retweets are only valid for top postings
1931                         // It doesn't work reliable with the link if its a feed
1932                         $IsRetweet = ($item['owner-link'] != $item['author-link']);
1933                         if ($IsRetweet)
1934                                 $IsRetweet = (($item['owner-name'] != $item['author-name']) OR ($item['owner-avatar'] != $item['author-avatar']));
1935
1936                         if ($IsRetweet AND ($item["id"] == $item["parent"])) {
1937                                 $retweeted_status = $status;
1938                                 $retweeted_status["user"] = api_get_user($a,$item["author-link"]);
1939
1940                                 $status["retweeted_status"] = $retweeted_status;
1941                         }
1942
1943                         // "uid" and "self" are only needed for some internal stuff, so remove it from here
1944                         unset($status["user"]["uid"]);
1945                         unset($status["user"]["self"]);
1946
1947                         // 'geo' => array('type' => 'Point',
1948                         //                   'coordinates' => array((float) $notice->lat,
1949                         //                                          (float) $notice->lon));
1950
1951                         $ret[] = $status;
1952                 };
1953                 return $ret;
1954         }
1955
1956
1957         function api_account_rate_limit_status(&$a,$type) {
1958
1959                 $hash = array(
1960                           'reset_time_in_seconds' => strtotime('now + 1 hour'),
1961                           'remaining_hits' => (string) 150,
1962                           'hourly_limit' => (string) 150,
1963                           'reset_time' => api_date(datetime_convert('UTC','UTC','now + 1 hour',ATOM_TIME)),
1964                 );
1965                 if ($type == "xml")
1966                         $hash['resettime_in_seconds'] = $hash['reset_time_in_seconds'];
1967
1968                 return api_apply_template('ratelimit', $type, array('$hash' => $hash));
1969
1970         }
1971         api_register_func('api/account/rate_limit_status','api_account_rate_limit_status',true);
1972
1973         function api_help_test(&$a,$type) {
1974
1975                 if ($type == 'xml')
1976                         $ok = "true";
1977                 else
1978                         $ok = "ok";
1979
1980                 return api_apply_template('test', $type, array("$ok" => $ok));
1981
1982         }
1983         api_register_func('api/help/test','api_help_test',false);
1984
1985         function api_lists(&$a,$type) {
1986
1987                 $ret = array();
1988                 return array($ret);
1989         }
1990         api_register_func('api/lists','api_lists',true);
1991
1992         function api_lists_list(&$a,$type) {
1993
1994                 $ret = array();
1995                 return array($ret);
1996         }
1997         api_register_func('api/lists/list','api_lists_list',true);
1998
1999         /**
2000          *  https://dev.twitter.com/docs/api/1/get/statuses/friends
2001          *  This function is deprecated by Twitter
2002          *  returns: json, xml
2003          **/
2004         function api_statuses_f(&$a, $type, $qtype) {
2005                 if (api_user()===false) return false;
2006                 $user_info = api_get_user($a);
2007
2008                 if (x($_GET,'cursor') && $_GET['cursor']=='undefined'){
2009                         /* this is to stop Hotot to load friends multiple times
2010                         *  I'm not sure if I'm missing return something or
2011                         *  is a bug in hotot. Workaround, meantime
2012                         */
2013
2014                         /*$ret=Array();
2015                         return array('$users' => $ret);*/
2016                         return false;
2017                 }
2018
2019                 if($qtype == 'friends')
2020                         $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
2021                 if($qtype == 'followers')
2022                         $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
2023
2024                 // friends and followers only for self
2025                 if ($user_info['self'] == 0)
2026                         $sql_extra = " AND false ";
2027
2028                 $r = q("SELECT `nurl` FROM `contact` WHERE `uid` = %d AND `self` = 0 AND `blocked` = 0 AND `pending` = 0 $sql_extra",
2029                         intval(api_user())
2030                 );
2031
2032                 $ret = array();
2033                 foreach($r as $cid){
2034                         $user = api_get_user($a, $cid['nurl']);
2035                         // "uid" and "self" are only needed for some internal stuff, so remove it from here
2036                         unset($user["uid"]);
2037                         unset($user["self"]);
2038
2039                         if ($user)
2040                                 $ret[] = $user;
2041                 }
2042
2043                 return array('$users' => $ret);
2044
2045         }
2046         function api_statuses_friends(&$a, $type){
2047                 $data =  api_statuses_f($a,$type,"friends");
2048                 if ($data===false) return false;
2049                 return  api_apply_template("friends", $type, $data);
2050         }
2051         function api_statuses_followers(&$a, $type){
2052                 $data = api_statuses_f($a,$type,"followers");
2053                 if ($data===false) return false;
2054                 return  api_apply_template("friends", $type, $data);
2055         }
2056         api_register_func('api/statuses/friends','api_statuses_friends',true);
2057         api_register_func('api/statuses/followers','api_statuses_followers',true);
2058
2059
2060
2061
2062
2063
2064         function api_statusnet_config(&$a,$type) {
2065                 $name = $a->config['sitename'];
2066                 $server = $a->get_hostname();
2067                 $logo = $a->get_baseurl() . '/images/friendica-64.png';
2068                 $email = $a->config['admin_email'];
2069                 $closed = (($a->config['register_policy'] == REGISTER_CLOSED) ? 'true' : 'false');
2070                 $private = (($a->config['system']['block_public']) ? 'true' : 'false');
2071                 $textlimit = (string) (($a->config['max_import_size']) ? $a->config['max_import_size'] : 200000);
2072                 if($a->config['api_import_size'])
2073                         $texlimit = string($a->config['api_import_size']);
2074                 $ssl = (($a->config['system']['have_ssl']) ? 'true' : 'false');
2075                 $sslserver = (($ssl === 'true') ? str_replace('http:','https:',$a->get_baseurl()) : '');
2076
2077                 $config = array(
2078                         'site' => array('name' => $name,'server' => $server, 'theme' => 'default', 'path' => '',
2079                                 'logo' => $logo, 'fancy' => true, 'language' => 'en', 'email' => $email, 'broughtby' => '',
2080                                 'broughtbyurl' => '', 'timezone' => 'UTC', 'closed' => $closed, 'inviteonly' => false,
2081                                 'private' => $private, 'textlimit' => $textlimit, 'sslserver' => $sslserver, 'ssl' => $ssl,
2082                                 'shorturllength' => '30',
2083                                 'friendica' => array(
2084                                                 'FRIENDICA_PLATFORM' => FRIENDICA_PLATFORM,
2085                                                 'FRIENDICA_VERSION' => FRIENDICA_VERSION,
2086                                                 'DFRN_PROTOCOL_VERSION' => DFRN_PROTOCOL_VERSION,
2087                                                 'DB_UPDATE_VERSION' => DB_UPDATE_VERSION
2088                                                 )
2089                         ),
2090                 );
2091
2092                 return api_apply_template('config', $type, array('$config' => $config));
2093
2094         }
2095         api_register_func('api/statusnet/config','api_statusnet_config',false);
2096
2097         function api_statusnet_version(&$a,$type) {
2098
2099                 // liar
2100
2101                 if($type === 'xml') {
2102                         header("Content-type: application/xml");
2103                         echo '<?xml version="1.0" encoding="UTF-8"?>' . "\r\n" . '<version>0.9.7</version>' . "\r\n";
2104                         killme();
2105                 }
2106                 elseif($type === 'json') {
2107                         header("Content-type: application/json");
2108                         echo '"0.9.7"';
2109                         killme();
2110                 }
2111         }
2112         api_register_func('api/statusnet/version','api_statusnet_version',false);
2113
2114
2115         function api_ff_ids(&$a,$type,$qtype) {
2116                 if(! api_user())
2117                         return false;
2118
2119                 $user_info = api_get_user($a);
2120
2121                 if($qtype == 'friends')
2122                         $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
2123                 if($qtype == 'followers')
2124                         $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
2125
2126                 if (!$user_info["self"])
2127                         $sql_extra = " AND false ";
2128
2129                 $stringify_ids = (x($_REQUEST,'stringify_ids')?$_REQUEST['stringify_ids']:false);
2130
2131                 $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",
2132                         intval(api_user())
2133                 );
2134
2135                 if(is_array($r)) {
2136
2137                         if($type === 'xml') {
2138                                 header("Content-type: application/xml");
2139                                 echo '<?xml version="1.0" encoding="UTF-8"?>' . "\r\n" . '<ids>' . "\r\n";
2140                                 foreach($r as $rr)
2141                                         echo '<id>' . $rr['id'] . '</id>' . "\r\n";
2142                                 echo '</ids>' . "\r\n";
2143                                 killme();
2144                         }
2145                         elseif($type === 'json') {
2146                                 $ret = array();
2147                                 header("Content-type: application/json");
2148                                 foreach($r as $rr)
2149                                         if ($stringify_ids)
2150                                                 $ret[] = $rr['id'];
2151                                         else
2152                                                 $ret[] = intval($rr['id']);
2153
2154                                 echo json_encode($ret);
2155                                 killme();
2156                         }
2157                 }
2158         }
2159
2160         function api_friends_ids(&$a,$type) {
2161                 api_ff_ids($a,$type,'friends');
2162         }
2163         function api_followers_ids(&$a,$type) {
2164                 api_ff_ids($a,$type,'followers');
2165         }
2166         api_register_func('api/friends/ids','api_friends_ids',true);
2167         api_register_func('api/followers/ids','api_followers_ids',true);
2168
2169
2170         function api_direct_messages_new(&$a, $type) {
2171                 if (api_user()===false) return false;
2172
2173                 if (!x($_POST, "text") OR (!x($_POST,"screen_name") AND !x($_POST,"user_id"))) return;
2174
2175                 $sender = api_get_user($a);
2176
2177                 require_once("include/message.php");
2178
2179                 if ($_POST['screen_name']) {
2180                         $r = q("SELECT `id`, `nurl`, `network` FROM `contact` WHERE `uid`=%d AND `nick`='%s'",
2181                                         intval(api_user()),
2182                                         dbesc($_POST['screen_name']));
2183
2184                         // Selecting the id by priority, friendica first
2185                         api_best_nickname($r);
2186
2187                         $recipient = api_get_user($a, $r[0]['nurl']);
2188                 } else
2189                         $recipient = api_get_user($a, $_POST['user_id']);
2190
2191                 $replyto = '';
2192                 $sub     = '';
2193                 if (x($_REQUEST,'replyto')) {
2194                         $r = q('SELECT `parent-uri`, `title` FROM `mail` WHERE `uid`=%d AND `id`=%d',
2195                                         intval(api_user()),
2196                                         intval($_REQUEST['replyto']));
2197                         $replyto = $r[0]['parent-uri'];
2198                         $sub     = $r[0]['title'];
2199                 }
2200                 else {
2201                         if (x($_REQUEST,'title')) {
2202                                 $sub = $_REQUEST['title'];
2203                         }
2204                         else {
2205                                 $sub = ((strlen($_POST['text'])>10)?substr($_POST['text'],0,10)."...":$_POST['text']);
2206                         }
2207                 }
2208
2209                 $id = send_message($recipient['cid'], $_POST['text'], $sub, $replyto);
2210
2211                 if ($id>-1) {
2212                         $r = q("SELECT * FROM `mail` WHERE id=%d", intval($id));
2213                         $ret = api_format_messages($r[0], $recipient, $sender);
2214
2215                 } else {
2216                         $ret = array("error"=>$id);
2217                 }
2218
2219                 $data = Array('$messages'=>$ret);
2220
2221                 switch($type){
2222                         case "atom":
2223                         case "rss":
2224                                 $data = api_rss_extra($a, $data, $user_info);
2225                 }
2226
2227                 return  api_apply_template("direct_messages", $type, $data);
2228
2229         }
2230         api_register_func('api/direct_messages/new','api_direct_messages_new',true);
2231
2232         function api_direct_messages_box(&$a, $type, $box) {
2233                 if (api_user()===false) return false;
2234
2235                 unset($_REQUEST["user_id"]);
2236                 unset($_GET["user_id"]);
2237
2238                 unset($_REQUEST["screen_name"]);
2239                 unset($_GET["screen_name"]);
2240
2241                 $user_info = api_get_user($a);
2242
2243                 // params
2244                 $count = (x($_GET,'count')?$_GET['count']:20);
2245                 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
2246                 if ($page<0) $page=0;
2247
2248                 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
2249                 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
2250
2251                 $start = $page*$count;
2252
2253                 //$profile_url = $a->get_baseurl() . '/profile/' . $a->user['nickname'];
2254                 $profile_url = $user_info["url"];
2255
2256                 if ($box=="sentbox") {
2257                         $sql_extra = "`mail`.`from-url`='".dbesc( $profile_url )."'";
2258                 }
2259                 elseif ($box=="conversation") {
2260                         $sql_extra = "`mail`.`parent-uri`='".dbesc( $_GET["uri"] )  ."'";
2261                 }
2262                 elseif ($box=="all") {
2263                         $sql_extra = "true";
2264                 }
2265                 elseif ($box=="inbox") {
2266                         $sql_extra = "`mail`.`from-url`!='".dbesc( $profile_url )."'";
2267                 }
2268
2269                 if ($max_id > 0)
2270                         $sql_extra .= ' AND `mail`.`id` <= '.intval($max_id);
2271
2272                 $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",
2273                                 intval(api_user()),
2274                                 intval($since_id),
2275                                 intval($start), intval($count)
2276                 );
2277
2278                 $ret = Array();
2279                 foreach($r as $item) {
2280                         if ($box == "inbox" || $item['from-url'] != $profile_url){
2281                                 $recipient = $user_info;
2282                                 $sender = api_get_user($a,normalise_link($item['contact-url']));
2283                         }
2284                         elseif ($box == "sentbox" || $item['from-url'] != $profile_url){
2285                                 $recipient = api_get_user($a,normalise_link($item['contact-url']));
2286                                 $sender = $user_info;
2287
2288                         }
2289
2290                         $ret[]=api_format_messages($item, $recipient, $sender);
2291                 }
2292
2293
2294                 $data = array('$messages' => $ret);
2295                 switch($type){
2296                         case "atom":
2297                         case "rss":
2298                                 $data = api_rss_extra($a, $data, $user_info);
2299                 }
2300
2301                 return  api_apply_template("direct_messages", $type, $data);
2302
2303         }
2304
2305         function api_direct_messages_sentbox(&$a, $type){
2306                 return api_direct_messages_box($a, $type, "sentbox");
2307         }
2308         function api_direct_messages_inbox(&$a, $type){
2309                 return api_direct_messages_box($a, $type, "inbox");
2310         }
2311         function api_direct_messages_all(&$a, $type){
2312                 return api_direct_messages_box($a, $type, "all");
2313         }
2314         function api_direct_messages_conversation(&$a, $type){
2315                 return api_direct_messages_box($a, $type, "conversation");
2316         }
2317         api_register_func('api/direct_messages/conversation','api_direct_messages_conversation',true);
2318         api_register_func('api/direct_messages/all','api_direct_messages_all',true);
2319         api_register_func('api/direct_messages/sent','api_direct_messages_sentbox',true);
2320         api_register_func('api/direct_messages','api_direct_messages_inbox',true);
2321
2322
2323
2324         function api_oauth_request_token(&$a, $type){
2325                 try{
2326                         $oauth = new FKOAuth1();
2327                         $r = $oauth->fetch_request_token(OAuthRequest::from_request());
2328                 }catch(Exception $e){
2329                         echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage()); killme();
2330                 }
2331                 echo $r;
2332                 killme();
2333         }
2334         function api_oauth_access_token(&$a, $type){
2335                 try{
2336                         $oauth = new FKOAuth1();
2337                         $r = $oauth->fetch_access_token(OAuthRequest::from_request());
2338                 }catch(Exception $e){
2339                         echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage()); killme();
2340                 }
2341                 echo $r;
2342                 killme();
2343         }
2344
2345         api_register_func('api/oauth/request_token', 'api_oauth_request_token', false);
2346         api_register_func('api/oauth/access_token', 'api_oauth_access_token', false);
2347
2348
2349         function api_fr_photos_list(&$a,$type) {
2350                 if (api_user()===false) return false;
2351                 $r = q("select distinct `resource-id` from photo where uid = %d and album != 'Contact Photos' ",
2352                         intval(local_user())
2353                 );
2354                 if($r) {
2355                         $ret = array();
2356                         foreach($r as $rr)
2357                                 $ret[] = $rr['resource-id'];
2358                         header("Content-type: application/json");
2359                         echo json_encode($ret);
2360                 }
2361                 killme();
2362         }
2363
2364         function api_fr_photo_detail(&$a,$type) {
2365                 if (api_user()===false) return false;
2366                 if(! $_REQUEST['photo_id']) return false;
2367                 $scale = ((array_key_exists('scale',$_REQUEST)) ? intval($_REQUEST['scale']) : 0);
2368                 $r = q("select * from photo where uid = %d and `resource-id` = '%s' and scale = %d limit 1",
2369                         intval(local_user()),
2370                         dbesc($_REQUEST['photo_id']),
2371                         intval($scale)
2372                 );
2373                 if($r) {
2374                         header("Content-type: application/json");
2375                         $r[0]['data'] = base64_encode($r[0]['data']);
2376                         echo json_encode($r[0]);
2377                 }
2378
2379                 killme();       
2380         }
2381
2382         api_register_func('api/friendica/photos/list', 'api_fr_photos_list', true);
2383         api_register_func('api/friendica/photo', 'api_fr_photo_detail', true);
2384
2385
2386
2387
2388
2389
2390 function api_share_as_retweet($a, $uid, &$item) {
2391         $body = trim($item["body"]);
2392
2393         // Skip if it isn't a pure repeated messages
2394         // Does it start with a share?
2395         if (strpos($body, "[share") > 0)
2396                 return(false);
2397
2398         // Does it end with a share?
2399         if (strlen($body) > (strrpos($body, "[/share]") + 8))
2400                 return(false);
2401
2402         $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$1",$body);
2403         // Skip if there is no shared message in there
2404         if ($body == $attributes)
2405                 return(false);
2406
2407         $author = "";
2408         preg_match("/author='(.*?)'/ism", $attributes, $matches);
2409         if ($matches[1] != "")
2410                 $author = html_entity_decode($matches[1],ENT_QUOTES,'UTF-8');
2411
2412         preg_match('/author="(.*?)"/ism', $attributes, $matches);
2413         if ($matches[1] != "")
2414                 $author = $matches[1];
2415
2416         $profile = "";
2417         preg_match("/profile='(.*?)'/ism", $attributes, $matches);
2418         if ($matches[1] != "")
2419                 $profile = $matches[1];
2420
2421         preg_match('/profile="(.*?)"/ism', $attributes, $matches);
2422         if ($matches[1] != "")
2423                 $profile = $matches[1];
2424
2425         $avatar = "";
2426         preg_match("/avatar='(.*?)'/ism", $attributes, $matches);
2427         if ($matches[1] != "")
2428                 $avatar = $matches[1];
2429
2430         preg_match('/avatar="(.*?)"/ism', $attributes, $matches);
2431         if ($matches[1] != "")
2432                 $avatar = $matches[1];
2433
2434         $shared_body = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$2",$body);
2435
2436         if (($shared_body == "") OR ($profile == "") OR ($author == "") OR ($avatar == ""))
2437                 return(false);
2438
2439         $item["body"] = $shared_body;
2440         $item["author-name"] = $author;
2441         $item["author-link"] = $profile;
2442         $item["author-avatar"] = $avatar;
2443
2444         return(true);
2445
2446 }
2447
2448 function api_get_nick($profile) {
2449 /* To-Do:
2450  - remove trailing jung from profile url
2451  - pump.io check has to check the website
2452 */
2453
2454         $nick = "";
2455
2456         $friendica = preg_replace("=https?://(.*)/profile/(.*)=ism", "$2", $profile);
2457         if ($friendica != $profile)
2458                 $nick = $friendica;
2459
2460         if (!$nick == "") {
2461                 $diaspora = preg_replace("=https?://(.*)/u/(.*)=ism", "$2", $profile);
2462                 if ($diaspora != $profile)
2463                         $nick = $diaspora;
2464         }
2465
2466         if (!$nick == "") {
2467                 $twitter = preg_replace("=https?://twitter.com/(.*)=ism", "$1", $profile);
2468                 if ($twitter != $profile)
2469                         $nick = $twitter;
2470         }
2471
2472
2473         if (!$nick == "") {
2474                 $StatusnetHost = preg_replace("=https?://(.*)/user/(.*)=ism", "$1", $profile);
2475                 if ($StatusnetHost != $profile) {
2476                         $StatusnetUser = preg_replace("=https?://(.*)/user/(.*)=ism", "$2", $profile);
2477                         if ($StatusnetUser != $profile) {
2478                                 $UserData = fetch_url("http://".$StatusnetHost."/api/users/show.json?user_id=".$StatusnetUser);
2479                                 $user = json_decode($UserData);
2480                                 if ($user)
2481                                         $nick = $user->screen_name;
2482                         }
2483                 }
2484         }
2485
2486         // To-Do: look at the page if its really a pumpio site
2487         //if (!$nick == "") {
2488         //      $pumpio = preg_replace("=https?://(.*)/(.*)/=ism", "$2", $profile."/");
2489         //      if ($pumpio != $profile)
2490         //              $nick = $pumpio;
2491                 //      <div class="media" id="profile-block" data-profile-id="acct:kabniel@microca.st">
2492
2493         //}
2494
2495         if ($nick != "") {
2496                 q("UPDATE unique_contacts SET nick = '%s' WHERE url = '%s'",
2497                         dbesc($nick), dbesc(normalise_link($profile)));
2498                 return($nick);
2499         }
2500
2501         return(false);
2502 }
2503
2504 function api_clean_plain_items($Text) {
2505         $include_entities = strtolower(x($_REQUEST,'include_entities')?$_REQUEST['include_entities']:"false");
2506
2507         $Text = bb_CleanPictureLinks($Text);
2508
2509         $URLSearchString = "^\[\]";
2510
2511         $Text = preg_replace("/([!#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'$1$3',$Text);
2512
2513         if ($include_entities == "true") {
2514                 $Text = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'[url=$1]$1[/url]',$Text);
2515         }
2516
2517         $Text = preg_replace_callback("((.*?)\[class=(.*?)\](.*?)\[\/class\])ism","api_cleanup_share",$Text);
2518         return($Text);
2519 }
2520
2521 function api_cleanup_share($shared) {
2522         if ($shared[2] != "type-link")
2523                 return($shared[0]);
2524
2525         if (!preg_match_all("/\[bookmark\=([^\]]*)\](.*?)\[\/bookmark\]/ism",$shared[3], $bookmark))
2526                 return($shared[0]);
2527
2528         $title = "";
2529         $link = "";
2530
2531         if (isset($bookmark[2][0]))
2532                 $title = $bookmark[2][0];
2533
2534         if (isset($bookmark[1][0]))
2535                 $link = $bookmark[1][0];
2536
2537         if (strpos($shared[1],$title) !== false)
2538                 $title = "";
2539
2540         if (strpos($shared[1],$link) !== false)
2541                 $link = "";
2542
2543         $text = trim($shared[1]);
2544
2545         //if (strlen($text) < strlen($title))
2546         if (($text == "") AND ($title != ""))
2547                 $text .= "\n\n".trim($title);
2548
2549         if ($link != "")
2550                 $text .= "\n".trim($link);
2551
2552         return(trim($text));
2553 }
2554
2555 function api_best_nickname(&$contacts) {
2556         $best_contact = array();
2557
2558         if (count($contact) == 0)
2559                 return;
2560
2561         foreach ($contacts AS $contact)
2562                 if ($contact["network"] == "") {
2563                         $contact["network"] = "dfrn";
2564                         $best_contact = array($contact);
2565                 }
2566
2567         if (sizeof($best_contact) == 0)
2568                 foreach ($contacts AS $contact)
2569                         if ($contact["network"] == "dfrn")
2570                                 $best_contact = array($contact);
2571
2572         if (sizeof($best_contact) == 0)
2573                 foreach ($contacts AS $contact)
2574                         if ($contact["network"] == "dspr")
2575                                 $best_contact = array($contact);
2576
2577         if (sizeof($best_contact) == 0)
2578                 foreach ($contacts AS $contact)
2579                         if ($contact["network"] == "stat")
2580                                 $best_contact = array($contact);
2581
2582         if (sizeof($best_contact) == 0)
2583                 foreach ($contacts AS $contact)
2584                         if ($contact["network"] == "pump")
2585                                 $best_contact = array($contact);
2586
2587         if (sizeof($best_contact) == 0)
2588                 foreach ($contacts AS $contact)
2589                         if ($contact["network"] == "twit")
2590                                 $best_contact = array($contact);
2591
2592         if (sizeof($best_contact) == 1)
2593                 $contacts = $best_contact;
2594         else
2595                 $contacts = array($contacts[0]);
2596 }
2597
2598 /*
2599 Not implemented by now:
2600 favorites
2601 favorites/create
2602 favorites/destroy
2603 statuses/retweets_of_me
2604 friendships/create
2605 friendships/destroy
2606 friendships/exists
2607 friendships/show
2608 account/update_location
2609 account/update_profile_background_image
2610 account/update_profile_image
2611 blocks/create
2612 blocks/destroy
2613
2614 Not implemented in status.net:
2615 statuses/retweeted_to_me
2616 statuses/retweeted_by_me
2617 direct_messages/destroy
2618 account/end_session
2619 account/update_delivery_device
2620 notifications/follow
2621 notifications/leave
2622 blocks/exists
2623 blocks/blocking
2624 lists
2625 */