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