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