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