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