3 - Automatically detect if incoming data is HTML or BBCode
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");
19 // It is not sufficient to use local_user() to check whether someone is allowed to use the API,
20 // because this will open CSRF holes (just embed an image with src=friendicasite.com/api/statuses/update?status=CSRF
21 // into a page, and visitors will post something without noticing it).
22 // Instead, use this function.
23 if ($_SESSION["allow_api"])
29 function api_source() {
30 if (requestdata('source'))
31 return (requestdata('source'));
33 // Support for known clients that doesn't send a source name
34 if (strstr($_SERVER['HTTP_USER_AGENT'], "Twidere"))
37 logger("Unrecognized user-agent ".$_SERVER['HTTP_USER_AGENT'], LOGGER_DEBUG);
42 function api_date($str){
43 //Wed May 23 06:01:13 +0000 2007
44 return datetime_convert('UTC', 'UTC', $str, "D M d H:i:s +0000 Y" );
48 function api_register_func($path, $func, $auth=false){
50 $API[$path] = array('func'=>$func, 'auth'=>$auth);
52 // Workaround for hotot
53 $path = str_replace("api/", "api/1.1/", $path);
54 $API[$path] = array('func'=>$func, 'auth'=>$auth);
61 function api_login(&$a){
64 $oauth = new FKOAuth1();
65 list($consumer,$token) = $oauth->verify_request(OAuthRequest::from_request());
66 if (!is_null($token)){
67 $oauth->loginUser($token->uid);
68 call_hooks('logged_in', $a->user);
71 echo __file__.__line__.__function__."<pre>"; var_dump($consumer, $token); die();
73 logger(__file__.__line__.__function__."\n".$e);
74 //die(__file__.__line__.__function__."<pre>".$e); die();
79 // workaround for HTTP-auth in CGI mode
80 if(x($_SERVER,'REDIRECT_REMOTE_USER')) {
81 $userpass = base64_decode(substr($_SERVER["REDIRECT_REMOTE_USER"],6)) ;
82 if(strlen($userpass)) {
83 list($name, $password) = explode(':', $userpass);
84 $_SERVER['PHP_AUTH_USER'] = $name;
85 $_SERVER['PHP_AUTH_PW'] = $password;
89 if (!isset($_SERVER['PHP_AUTH_USER'])) {
90 logger('API_login: ' . print_r($_SERVER,true), LOGGER_DEBUG);
91 header('WWW-Authenticate: Basic realm="Friendica"');
92 header('HTTP/1.0 401 Unauthorized');
93 die((api_error($a, 'json', "This api requires login")));
95 //die('This api requires login');
98 $user = $_SERVER['PHP_AUTH_USER'];
99 $password = $_SERVER['PHP_AUTH_PW'];
100 $encrypted = hash('whirlpool',trim($password));
104 * next code from mod/auth.php. needs better solution
109 'username' => trim($user),
110 'password' => trim($password),
111 'authenticated' => 0,
112 'user_record' => null
117 * A plugin indicates successful login by setting 'authenticated' to non-zero value and returning a user record
118 * Plugins should never set 'authenticated' except to indicate success - as hooks may be chained
119 * and later plugins should not interfere with an earlier one that succeeded.
123 call_hooks('authenticate', $addon_auth);
125 if(($addon_auth['authenticated']) && (count($addon_auth['user_record']))) {
126 $record = $addon_auth['user_record'];
129 // process normal login request
131 $r = q("SELECT * FROM `user` WHERE ( `email` = '%s' OR `nickname` = '%s' )
132 AND `password` = '%s' AND `blocked` = 0 AND `account_expired` = 0 AND `account_removed` = 0 AND `verified` = 1 LIMIT 1",
141 if((! $record) || (! count($record))) {
142 logger('API_login failure: ' . print_r($_SERVER,true), LOGGER_DEBUG);
143 header('WWW-Authenticate: Basic realm="Friendica"');
144 header('HTTP/1.0 401 Unauthorized');
145 die('This api requires login');
148 require_once('include/security.php');
149 authenticate_success($record); $_SESSION["allow_api"] = true;
151 call_hooks('logged_in', $a->user);
155 /**************************
156 * MAIN API ENTRY POINT *
157 **************************/
158 function api_call(&$a){
159 GLOBAL $API, $called_api;
163 foreach ($API as $p=>$info){
164 if (strpos($a->query_string, $p)===0){
165 $called_api= explode("/",$p);
166 //unset($_SERVER['PHP_AUTH_USER']);
167 if ($info['auth']===true && api_user()===false) {
171 load_contact_links(api_user());
173 logger('API call for ' . $a->user['username'] . ': ' . $a->query_string);
174 logger('API parameters: ' . print_r($_REQUEST,true));
176 if (strpos($a->query_string, ".xml")>0) $type="xml";
177 if (strpos($a->query_string, ".json")>0) $type="json";
178 if (strpos($a->query_string, ".rss")>0) $type="rss";
179 if (strpos($a->query_string, ".atom")>0) $type="atom";
180 if (strpos($a->query_string, ".as")>0) $type="as";
182 $r = call_user_func($info['func'], $a, $type);
183 if ($r===false) return;
187 $r = mb_convert_encoding($r, "UTF-8",mb_detect_encoding($r));
188 header ("Content-Type: text/xml");
189 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
192 header ("Content-Type: application/json");
194 $json = json_encode($rr);
195 if ($_GET['callback'])
196 $json = $_GET['callback']."(".$json.")";
200 header ("Content-Type: application/rss+xml");
201 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
204 header ("Content-Type: application/atom+xml");
205 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
208 //header ("Content-Type: application/json");
210 // return json_encode($rr);
211 return json_encode($r);
215 //echo "<pre>"; var_dump($r); die();
218 header("HTTP/1.1 404 Not Found");
219 logger('API call not implemented: '.$a->query_string." - ".print_r($_REQUEST,true));
220 return(api_error($a, $type, "not implemented"));
224 function api_error(&$a, $type, $error) {
225 # TODO: https://dev.twitter.com/overview/api/response-codes
226 $r = "<status><error>".$error."</error><request>".$a->query_string."</request></status>";
229 header ("Content-Type: text/xml");
230 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
233 header ("Content-Type: application/json");
234 return json_encode(array('error' => $error, 'request' => $a->query_string));
237 header ("Content-Type: application/rss+xml");
238 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
241 header ("Content-Type: application/atom+xml");
242 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
250 function api_rss_extra(&$a, $arr, $user_info){
251 if (is_null($user_info)) $user_info = api_get_user($a);
252 $arr['$user'] = $user_info;
253 $arr['$rss'] = array(
254 'alternate' => $user_info['url'],
255 'self' => $a->get_baseurl(). "/". $a->query_string,
256 'base' => $a->get_baseurl(),
257 'updated' => api_date(null),
258 'atom_updated' => datetime_convert('UTC','UTC','now',ATOM_TIME),
259 'language' => $user_info['language'],
260 'logo' => $a->get_baseurl()."/images/friendica-32.png",
268 * Unique contact to contact url.
270 function api_unique_id_to_url($id){
271 $r = q("SELECT url FROM unique_contacts WHERE id=%d LIMIT 1",
274 return ($r[0]["url"]);
280 * Returns user info array.
282 function api_get_user(&$a, $contact_id = Null, $type = "json"){
289 logger("api_get_user: Fetching user data for user ".$contact_id, LOGGER_DEBUG);
291 // Searching for contact URL
292 if(!is_null($contact_id) AND (intval($contact_id) == 0)){
293 $user = dbesc(normalise_link($contact_id));
295 $extra_query = "AND `contact`.`nurl` = '%s' ";
296 if (api_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(api_user());
299 // Searching for unique contact id
300 if(!is_null($contact_id) AND (intval($contact_id) != 0)){
301 $user = dbesc(api_unique_id_to_url($contact_id));
304 die(api_error($a, $type, t("User not found.")));
307 $extra_query = "AND `contact`.`nurl` = '%s' ";
308 if (api_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(api_user());
311 if(is_null($user) && x($_GET, 'user_id')) {
312 $user = dbesc(api_unique_id_to_url($_GET['user_id']));
315 die(api_error($a, $type, t("User not found.")));
318 $extra_query = "AND `contact`.`nurl` = '%s' ";
319 if (api_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(api_user());
321 if(is_null($user) && x($_GET, 'screen_name')) {
322 $user = dbesc($_GET['screen_name']);
324 $extra_query = "AND `contact`.`nick` = '%s' ";
325 if (api_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(api_user());
328 if (is_null($user) AND ($a->argc > (count($called_api)-1)) AND (count($called_api) > 0)){
329 $argid = count($called_api);
330 list($user, $null) = explode(".",$a->argv[$argid]);
331 if(is_numeric($user)){
332 $user = dbesc(api_unique_id_to_url($user));
338 $extra_query = "AND `contact`.`nurl` = '%s' ";
339 if (api_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(api_user());
341 $user = dbesc($user);
343 $extra_query = "AND `contact`.`nick` = '%s' ";
344 if (api_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(api_user());
348 logger("api_get_user: user ".$user, LOGGER_DEBUG);
351 if (api_user()===false) {
352 api_login($a); return False;
354 $user = $_SESSION['uid'];
355 $extra_query = "AND `contact`.`uid` = %d AND `contact`.`self` = 1 ";
360 logger('api_user: ' . $extra_query . ', user: ' . $user);
362 $uinfo = q("SELECT *, `contact`.`id` as `cid` FROM `contact`
368 // Selecting the id by priority, friendica first
369 api_best_nickname($uinfo);
371 // if the contact wasn't found, fetch it from the unique contacts
372 if (count($uinfo)==0) {
376 $r = q("SELECT * FROM unique_contacts WHERE url='%s' LIMIT 1", $url);
378 $r = q("SELECT * FROM unique_contacts WHERE nick='%s' LIMIT 1", $nick);
381 // If no nick where given, extract it from the address
382 if (($r[0]['nick'] == "") OR ($r[0]['name'] == $r[0]['nick']))
383 $r[0]['nick'] = api_get_nick($r[0]["url"]);
387 'id_str' => (string) $r[0]["id"],
388 'name' => $r[0]["name"],
389 'screen_name' => (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']),
391 'description' => NULL,
392 'profile_image_url' => $r[0]["avatar"],
393 'profile_image_url_https' => $r[0]["avatar"],
394 'url' => $r[0]["url"],
395 'protected' => false,
396 'followers_count' => 0,
397 'friends_count' => 0,
398 'created_at' => api_date(0),
399 'favourites_count' => 0,
401 'time_zone' => 'UTC',
402 'statuses_count' => 0,
403 'following' => false,
405 'statusnet_blocking' => false,
406 'notifications' => false,
407 'statusnet_profile_url' => $r[0]["url"],
416 die(api_error($a, $type, t("User not found.")));
420 if($uinfo[0]['self']) {
421 $usr = q("select * from user where uid = %d limit 1",
424 $profile = q("select * from profile where uid = %d and `is-default` = 1 limit 1",
428 //AND `allow_cid`='' AND `allow_gid`='' AND `deny_cid`='' AND `deny_gid`=''",
429 // count public wall messages
430 $r = q("SELECT count(*) as `count` FROM `item`
433 intval($uinfo[0]['uid'])
435 $countitms = $r[0]['count'];
438 //AND `allow_cid`='' AND `allow_gid`='' AND `deny_cid`='' AND `deny_gid`=''",
439 $r = q("SELECT count(*) as `count` FROM `item`
440 WHERE `contact-id` = %d",
441 intval($uinfo[0]['id'])
443 $countitms = $r[0]['count'];
447 $r = q("SELECT count(*) as `count` FROM `contact`
448 WHERE `uid` = %d AND `rel` IN ( %d, %d )
449 AND `self`=0 AND `blocked`=0 AND `pending`=0 AND `hidden`=0",
450 intval($uinfo[0]['uid']),
451 intval(CONTACT_IS_SHARING),
452 intval(CONTACT_IS_FRIEND)
454 $countfriends = $r[0]['count'];
456 $r = q("SELECT count(*) as `count` FROM `contact`
457 WHERE `uid` = %d AND `rel` IN ( %d, %d )
458 AND `self`=0 AND `blocked`=0 AND `pending`=0 AND `hidden`=0",
459 intval($uinfo[0]['uid']),
460 intval(CONTACT_IS_FOLLOWER),
461 intval(CONTACT_IS_FRIEND)
463 $countfollowers = $r[0]['count'];
465 $r = q("SELECT count(*) as `count` FROM item where starred = 1 and uid = %d and deleted = 0",
466 intval($uinfo[0]['uid'])
468 $starred = $r[0]['count'];
471 if(! $uinfo[0]['self']) {
477 // Add a nick if it isn't present there
478 if (($uinfo[0]['nick'] == "") OR ($uinfo[0]['name'] == $uinfo[0]['nick'])) {
479 $uinfo[0]['nick'] = api_get_nick($uinfo[0]["url"]);
482 // Fetching unique id
483 $r = q("SELECT id FROM unique_contacts WHERE url='%s' LIMIT 1", dbesc(normalise_link($uinfo[0]['url'])));
485 // If not there, then add it
486 if (count($r) == 0) {
487 q("INSERT INTO unique_contacts (url, name, nick, avatar) VALUES ('%s', '%s', '%s', '%s')",
488 dbesc(normalise_link($uinfo[0]['url'])), dbesc($uinfo[0]['name']),dbesc($uinfo[0]['nick']), dbesc($uinfo[0]['micro']));
490 $r = q("SELECT id FROM unique_contacts WHERE url='%s' LIMIT 1", dbesc(normalise_link($uinfo[0]['url'])));
493 require_once('include/contact_selectors.php');
494 $network_name = network_to_name($uinfo[0]['network']);
497 'id' => intval($r[0]['id']),
498 'id_str' => (string) intval($r[0]['id']),
499 'name' => (($uinfo[0]['name']) ? $uinfo[0]['name'] : $uinfo[0]['nick']),
500 'screen_name' => (($uinfo[0]['nick']) ? $uinfo[0]['nick'] : $uinfo[0]['name']),
501 'location' => ($usr) ? $usr[0]['default-location'] : $network_name,
502 'description' => (($profile) ? $profile[0]['pdesc'] : NULL),
503 'profile_image_url' => $uinfo[0]['micro'],
504 'profile_image_url_https' => $uinfo[0]['micro'],
505 'url' => $uinfo[0]['url'],
506 'protected' => false,
507 'followers_count' => intval($countfollowers),
508 'friends_count' => intval($countfriends),
509 'created_at' => api_date($uinfo[0]['created']),
510 'favourites_count' => intval($starred),
512 'time_zone' => 'UTC',
513 'statuses_count' => intval($countitms),
514 'following' => (($uinfo[0]['rel'] == CONTACT_IS_FOLLOWER) OR ($uinfo[0]['rel'] == CONTACT_IS_FRIEND)),
516 'statusnet_blocking' => false,
517 'notifications' => false,
518 'statusnet_profile_url' => $a->get_baseurl()."/contacts/".$uinfo[0]['cid'],
519 'uid' => intval($uinfo[0]['uid']),
520 'cid' => intval($uinfo[0]['cid']),
521 'self' => $uinfo[0]['self'],
522 'network' => $uinfo[0]['network'],
529 function api_item_get_user(&$a, $item) {
531 $author = q("SELECT * FROM unique_contacts WHERE url='%s' LIMIT 1",
532 dbesc(normalise_link($item['author-link'])));
534 if (count($author) == 0) {
535 q("INSERT INTO unique_contacts (url, name, avatar) VALUES ('%s', '%s', '%s')",
536 dbesc(normalise_link($item["author-link"])), dbesc($item["author-name"]), dbesc($item["author-avatar"]));
538 $author = q("SELECT id FROM unique_contacts WHERE url='%s' LIMIT 1",
539 dbesc(normalise_link($item['author-link'])));
540 } else if ($item["author-link"].$item["author-name"] != $author[0]["url"].$author[0]["name"]) {
541 q("UPDATE unique_contacts SET name = '%s', avatar = '%s' WHERE url = '%s'",
542 dbesc($item["author-name"]), dbesc($item["author-avatar"]), dbesc(normalise_link($item["author-link"])));
545 $owner = q("SELECT id FROM unique_contacts WHERE url='%s' LIMIT 1",
546 dbesc(normalise_link($item['owner-link'])));
548 if (count($owner) == 0) {
549 q("INSERT INTO unique_contacts (url, name, avatar) VALUES ('%s', '%s', '%s')",
550 dbesc(normalise_link($item["owner-link"])), dbesc($item["owner-name"]), dbesc($item["owner-avatar"]));
552 $owner = q("SELECT id FROM unique_contacts WHERE url='%s' LIMIT 1",
553 dbesc(normalise_link($item['owner-link'])));
554 } else if ($item["owner-link"].$item["owner-name"] != $owner[0]["url"].$owner[0]["name"]) {
555 q("UPDATE unique_contacts SET name = '%s', avatar = '%s' WHERE url = '%s'",
556 dbesc($item["owner-name"]), dbesc($item["owner-avatar"]), dbesc(normalise_link($item["owner-link"])));
559 // Comments in threads may appear as wall-to-wall postings.
560 // So only take the owner at the top posting.
561 if ($item["id"] == $item["parent"])
562 $status_user = api_get_user($a,$item["owner-link"]);
564 $status_user = api_get_user($a,$item["author-link"]);
566 $status_user["protected"] = (($item["allow_cid"] != "") OR
567 ($item["allow_gid"] != "") OR
568 ($item["deny_cid"] != "") OR
569 ($item["deny_gid"] != "") OR
572 return ($status_user);
577 * load api $templatename for $type and replace $data array
579 function api_apply_template($templatename, $type, $data){
587 $data = array_xmlify($data);
588 $tpl = get_markup_template("api_".$templatename."_".$type.".tpl");
590 header ("Content-Type: text/xml");
591 echo '<?xml version="1.0" encoding="UTF-8"?>'."\n".'<status><error>not implemented</error></status>';
594 $ret = replace_macros($tpl, $data);
609 * Returns an HTTP 200 OK response code and a representation of the requesting user if authentication was successful;
610 * returns a 401 status code and an error message if not.
611 * http://developer.twitter.com/doc/get/account/verify_credentials
613 function api_account_verify_credentials(&$a, $type){
614 if (api_user()===false) return false;
616 unset($_REQUEST["user_id"]);
617 unset($_GET["user_id"]);
619 unset($_REQUEST["screen_name"]);
620 unset($_GET["screen_name"]);
622 $skip_status = (x($_REQUEST,'skip_status')?$_REQUEST['skip_status']:false);
624 $user_info = api_get_user($a);
626 // "verified" isn't used here in the standard
627 unset($user_info["verified"]);
629 // - Adding last status
631 $user_info["status"] = api_status_show($a,"raw");
632 if (!count($user_info["status"]))
633 unset($user_info["status"]);
635 unset($user_info["status"]["user"]);
638 // "uid" and "self" are only needed for some internal stuff, so remove it from here
639 unset($user_info["uid"]);
640 unset($user_info["self"]);
642 return api_apply_template("user", $type, array('$user' => $user_info));
645 api_register_func('api/account/verify_credentials','api_account_verify_credentials', true);
649 * get data from $_POST or $_GET
651 function requestdata($k){
652 if (isset($_POST[$k])){
655 if (isset($_GET[$k])){
661 /*Waitman Gobble Mod*/
662 function api_statuses_mediap(&$a, $type) {
663 if (api_user()===false) {
664 logger('api_statuses_update: no user');
667 $user_info = api_get_user($a);
669 $_REQUEST['type'] = 'wall';
670 $_REQUEST['profile_uid'] = api_user();
671 $_REQUEST['api_source'] = true;
672 $txt = requestdata('status');
673 //$txt = urldecode(requestdata('status'));
675 require_once('library/HTMLPurifier.auto.php');
676 require_once('include/html2bbcode.php');
678 if((strpos($txt,'<') !== false) || (strpos($txt,'>') !== false)) {
679 $txt = html2bb_video($txt);
680 $config = HTMLPurifier_Config::createDefault();
681 $config->set('Cache.DefinitionImpl', null);
682 $purifier = new HTMLPurifier($config);
683 $txt = $purifier->purify($txt);
685 $txt = html2bbcode($txt);
687 $a->argv[1]=$user_info['screen_name']; //should be set to username?
689 $_REQUEST['hush']='yeah'; //tell wall_upload function to return img info instead of echo
690 require_once('mod/wall_upload.php');
691 $bebop = wall_upload_post($a);
693 //now that we have the img url in bbcode we can add it to the status and insert the wall item.
694 $_REQUEST['body']=$txt."\n\n".$bebop;
695 require_once('mod/item.php');
698 // this should output the last post (the one we just posted).
699 return api_status_show($a,$type);
701 api_register_func('api/statuses/mediap','api_statuses_mediap', true);
702 /*Waitman Gobble Mod*/
705 function api_statuses_update(&$a, $type) {
706 if (api_user()===false) {
707 logger('api_statuses_update: no user');
711 $user_info = api_get_user($a);
713 // convert $_POST array items to the form we use for web posts.
715 // logger('api_post: ' . print_r($_POST,true));
717 if(requestdata('htmlstatus')) {
718 require_once('library/HTMLPurifier.auto.php');
719 require_once('include/html2bbcode.php');
721 $txt = requestdata('htmlstatus');
722 if((strpos($txt,'<') !== false) || (strpos($txt,'>') !== false)) {
724 $txt = html2bb_video($txt);
726 $config = HTMLPurifier_Config::createDefault();
727 $config->set('Cache.DefinitionImpl', null);
730 $purifier = new HTMLPurifier($config);
731 $txt = $purifier->purify($txt);
733 $_REQUEST['body'] = html2bbcode($txt);
738 $_REQUEST['body'] = requestdata('status');
740 $_REQUEST['title'] = requestdata('title');
742 $parent = requestdata('in_reply_to_status_id');
743 if(ctype_digit($parent))
744 $_REQUEST['parent'] = $parent;
746 $_REQUEST['parent_uri'] = $parent;
748 if(requestdata('lat') && requestdata('long'))
749 $_REQUEST['coord'] = sprintf("%s %s",requestdata('lat'),requestdata('long'));
750 $_REQUEST['profile_uid'] = api_user();
753 $_REQUEST['type'] = 'net-comment';
755 // Check for throttling (maximum posts per day, week and month)
756 $throttle_day = get_config('system','throttle_limit_day');
757 if ($throttle_day > 0) {
758 $datefrom = date("Y-m-d H:i:s", time() - 24*60*60);
760 $r = q("SELECT COUNT(*) AS `posts_day` FROM `item` WHERE `uid`=%d AND `wall`
761 AND `created` > '%s' AND `id` = `parent`",
762 intval(api_user()), dbesc($datefrom));
765 $posts_day = $r[0]["posts_day"];
769 if ($posts_day > $throttle_day) {
770 logger('Daily posting limit reached for user '.api_user(), LOGGER_DEBUG);
771 die(api_error($a, $type, sprintf(t("Daily posting limit of %d posts reached. The post was rejected."), $throttle_day)));
775 $throttle_week = get_config('system','throttle_limit_week');
776 if ($throttle_week > 0) {
777 $datefrom = date("Y-m-d H:i:s", time() - 24*60*60*7);
779 $r = q("SELECT COUNT(*) AS `posts_week` FROM `item` WHERE `uid`=%d AND `wall`
780 AND `created` > '%s' AND `id` = `parent`",
781 intval(api_user()), dbesc($datefrom));
784 $posts_week = $r[0]["posts_week"];
788 if ($posts_week > $throttle_week) {
789 logger('Weekly posting limit reached for user '.api_user(), LOGGER_DEBUG);
790 die(api_error($a, $type, sprintf(t("Weekly posting limit of %d posts reached. The post was rejected."), $throttle_week)));
794 $throttle_month = get_config('system','throttle_limit_month');
795 if ($throttle_month > 0) {
796 $datefrom = date("Y-m-d H:i:s", time() - 24*60*60*30);
798 $r = q("SELECT COUNT(*) AS `posts_month` FROM `item` WHERE `uid`=%d AND `wall`
799 AND `created` > '%s' AND `id` = `parent`",
800 intval(api_user()), dbesc($datefrom));
803 $posts_month = $r[0]["posts_month"];
807 if ($posts_month > $throttle_month) {
808 logger('Monthly posting limit reached for user '.api_user(), LOGGER_DEBUG);
809 die(api_error($a, $type, sprintf(t("Monthly posting limit of %d posts reached. The post was rejected."), $throttle_month)));
813 $_REQUEST['type'] = 'wall';
814 if(x($_FILES,'media')) {
815 // upload the image if we have one
816 $_REQUEST['hush']='yeah'; //tell wall_upload function to return img info instead of echo
817 require_once('mod/wall_upload.php');
818 $media = wall_upload_post($a);
820 $_REQUEST['body'] .= "\n\n".$media;
824 // set this so that the item_post() function is quiet and doesn't redirect or emit json
826 $_REQUEST['api_source'] = true;
828 if (!x($_REQUEST, "source"))
829 $_REQUEST["source"] = api_source();
831 // call out normal post function
833 require_once('mod/item.php');
836 // this should output the last post (the one we just posted).
837 return api_status_show($a,$type);
839 api_register_func('api/statuses/update','api_statuses_update', true);
840 api_register_func('api/statuses/update_with_media','api_statuses_update', true);
843 function api_status_show(&$a, $type){
844 $user_info = api_get_user($a);
846 logger('api_status_show: user_info: '.print_r($user_info, true), LOGGER_DEBUG);
848 // get last public wall message
849 $lastwall = q("SELECT `item`.*, `i`.`contact-id` as `reply_uid`, `i`.`author-link` AS `item-author`
850 FROM `item`, `item` as `i`
851 WHERE `item`.`contact-id` = %d AND `item`.`uid` = %d
852 AND ((`item`.`author-link` IN ('%s', '%s')) OR (`item`.`owner-link` IN ('%s', '%s')))
853 AND `i`.`id` = `item`.`parent`
854 AND `item`.`type`!='activity'
855 AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''
856 ORDER BY `item`.`created` DESC
858 intval($user_info['cid']),
860 dbesc($user_info['url']),
861 dbesc(normalise_link($user_info['url'])),
862 dbesc($user_info['url']),
863 dbesc(normalise_link($user_info['url']))
866 if (count($lastwall)>0){
867 $lastwall = $lastwall[0];
869 $in_reply_to_status_id = NULL;
870 $in_reply_to_user_id = NULL;
871 $in_reply_to_status_id_str = NULL;
872 $in_reply_to_user_id_str = NULL;
873 $in_reply_to_screen_name = NULL;
874 if (intval($lastwall['parent']) != intval($lastwall['id'])) {
875 $in_reply_to_status_id= intval($lastwall['parent']);
876 $in_reply_to_status_id_str = (string) intval($lastwall['parent']);
878 $r = q("SELECT * FROM unique_contacts WHERE `url` = '%s'", dbesc(normalise_link($lastwall['item-author'])));
880 if ($r[0]['nick'] == "")
881 $r[0]['nick'] = api_get_nick($r[0]["url"]);
883 $in_reply_to_screen_name = (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']);
884 $in_reply_to_user_id = intval($r[0]['id']);
885 $in_reply_to_user_id_str = (string) intval($r[0]['id']);
889 // There seems to be situation, where both fields are identical:
890 // https://github.com/friendica/friendica/issues/1010
891 // This is a bugfix for that.
892 if (intval($in_reply_to_status_id) == intval($lastwall['id'])) {
893 logger('api_status_show: this message should never appear: id: '.$lastwall['id'].' similar to reply-to: '.$in_reply_to_status_id, LOGGER_DEBUG);
894 $in_reply_to_status_id = NULL;
895 $in_reply_to_user_id = NULL;
896 $in_reply_to_status_id_str = NULL;
897 $in_reply_to_user_id_str = NULL;
898 $in_reply_to_screen_name = NULL;
901 $converted = api_convert_item($item);
903 $status_info = array(
904 'text' => $converted["text"],
905 'truncated' => false,
906 'created_at' => api_date($lastwall['created']),
907 'in_reply_to_status_id' => $in_reply_to_status_id,
908 'in_reply_to_status_id_str' => $in_reply_to_status_id_str,
909 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
910 'id' => intval($lastwall['id']),
911 'id_str' => (string) $lastwall['id'],
912 'in_reply_to_user_id' => $in_reply_to_user_id,
913 'in_reply_to_user_id_str' => $in_reply_to_user_id_str,
914 'in_reply_to_screen_name' => $in_reply_to_screen_name,
916 'favorited' => $lastwall['starred'] ? true : false,
917 'user' => $user_info,
918 'statusnet_html' => $converted["html"],
919 'statusnet_conversation_id' => $lastwall['parent'],
922 if (count($converted["attachments"]) > 0)
923 $status_info["attachments"] = $converted["attachments"];
925 if (count($converted["entities"]) > 0)
926 $status_info["entities"] = $converted["entities"];
928 if (($lastwall['item_network'] != "") AND ($status["source"] == 'web'))
929 $status_info["source"] = network_to_name($lastwall['item_network']);
930 elseif (($lastwall['item_network'] != "") AND (network_to_name($lastwall['item_network']) != $status_info["source"]))
931 $status_info["source"] = trim($status_info["source"].' ('.network_to_name($lastwall['item_network']).')');
933 // "uid" and "self" are only needed for some internal stuff, so remove it from here
934 unset($status_info["user"]["uid"]);
935 unset($status_info["user"]["self"]);
939 return($status_info);
941 return api_apply_template("status", $type, array('$status' => $status_info));
950 * Returns extended information of a given user, specified by ID or screen name as per the required id parameter.
951 * The author's most recent status will be returned inline.
952 * http://developer.twitter.com/doc/get/users/show
954 function api_users_show(&$a, $type){
955 $user_info = api_get_user($a);
957 $lastwall = q("SELECT `item`.*
958 FROM `item`, `contact`
959 WHERE `item`.`uid` = %d AND `verb` = '%s' AND `item`.`contact-id` = %d
960 AND ((`item`.`author-link` IN ('%s', '%s')) OR (`item`.`owner-link` IN ('%s', '%s')))
961 AND `contact`.`id`=`item`.`contact-id`
962 AND `type`!='activity'
963 AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''
964 ORDER BY `created` DESC
967 dbesc(ACTIVITY_POST),
968 intval($user_info['cid']),
969 dbesc($user_info['url']),
970 dbesc(normalise_link($user_info['url'])),
971 dbesc($user_info['url']),
972 dbesc(normalise_link($user_info['url']))
974 if (count($lastwall)>0){
975 $lastwall = $lastwall[0];
977 $in_reply_to_status_id = NULL;
978 $in_reply_to_user_id = NULL;
979 $in_reply_to_status_id_str = NULL;
980 $in_reply_to_user_id_str = NULL;
981 $in_reply_to_screen_name = NULL;
982 if ($lastwall['parent']!=$lastwall['id']) {
983 $reply = q("SELECT `item`.`id`, `item`.`contact-id` as `reply_uid`, `contact`.`nick` as `reply_author`, `item`.`author-link` AS `item-author`
984 FROM `item`,`contact` WHERE `contact`.`id`=`item`.`contact-id` AND `item`.`id` = %d", intval($lastwall['parent']));
985 if (count($reply)>0) {
986 $in_reply_to_status_id = intval($lastwall['parent']);
987 $in_reply_to_status_id_str = (string) intval($lastwall['parent']);
989 $r = q("SELECT * FROM unique_contacts WHERE `url` = '%s'", dbesc(normalise_link($reply[0]['item-author'])));
991 if ($r[0]['nick'] == "")
992 $r[0]['nick'] = api_get_nick($r[0]["url"]);
994 $in_reply_to_screen_name = (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']);
995 $in_reply_to_user_id = intval($r[0]['id']);
996 $in_reply_to_user_id_str = (string) intval($r[0]['id']);
1001 $converted = api_convert_item($item);
1003 $user_info['status'] = array(
1004 'text' => $converted["text"],
1005 'truncated' => false,
1006 'created_at' => api_date($lastwall['created']),
1007 'in_reply_to_status_id' => $in_reply_to_status_id,
1008 'in_reply_to_status_id_str' => $in_reply_to_status_id_str,
1009 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
1010 'id' => intval($lastwall['contact-id']),
1011 'id_str' => (string) $lastwall['contact-id'],
1012 'in_reply_to_user_id' => $in_reply_to_user_id,
1013 'in_reply_to_user_id_str' => $in_reply_to_user_id_str,
1014 'in_reply_to_screen_name' => $in_reply_to_screen_name,
1016 'favorited' => $lastwall['starred'] ? true : false,
1017 'statusnet_html' => $converted["html"],
1018 'statusnet_conversation_id' => $lastwall['parent'],
1021 if (count($converted["attachments"]) > 0)
1022 $user_info["status"]["attachments"] = $converted["attachments"];
1024 if (count($converted["entities"]) > 0)
1025 $user_info["status"]["entities"] = $converted["entities"];
1027 if (($lastwall['item_network'] != "") AND ($user_info["status"]["source"] == 'web'))
1028 $user_info["status"]["source"] = network_to_name($lastwall['item_network']);
1029 if (($lastwall['item_network'] != "") AND (network_to_name($lastwall['item_network']) != $user_info["status"]["source"]))
1030 $user_info["status"]["source"] = trim($user_info["status"]["source"].' ('.network_to_name($lastwall['item_network']).')');
1034 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1035 unset($user_info["uid"]);
1036 unset($user_info["self"]);
1038 return api_apply_template("user", $type, array('$user' => $user_info));
1041 api_register_func('api/users/show','api_users_show');
1044 function api_users_search(&$a, $type) {
1045 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1047 $userlist = array();
1049 if (isset($_GET["q"])) {
1050 $r = q("SELECT id FROM unique_contacts WHERE name='%s'", dbesc($_GET["q"]));
1052 $r = q("SELECT id FROM unique_contacts WHERE nick='%s'", dbesc($_GET["q"]));
1055 foreach ($r AS $user) {
1056 $user_info = api_get_user($a, $user["id"]);
1057 //echo print_r($user_info, true)."\n";
1058 $userdata = api_apply_template("user", $type, array('user' => $user_info));
1059 $userlist[] = $userdata["user"];
1061 $userlist = array("users" => $userlist);
1063 die(api_error($a, $type, t("User not found.")));
1065 die(api_error($a, $type, t("User not found.")));
1070 api_register_func('api/users/search','api_users_search');
1074 * http://developer.twitter.com/doc/get/statuses/home_timeline
1076 * TODO: Optional parameters
1077 * TODO: Add reply info
1079 function api_statuses_home_timeline(&$a, $type){
1080 if (api_user()===false) return false;
1082 unset($_REQUEST["user_id"]);
1083 unset($_GET["user_id"]);
1085 unset($_REQUEST["screen_name"]);
1086 unset($_GET["screen_name"]);
1088 $user_info = api_get_user($a);
1089 // get last newtork messages
1093 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1094 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1095 if ($page<0) $page=0;
1096 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1097 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1098 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1099 $exclude_replies = (x($_REQUEST,'exclude_replies')?1:0);
1100 $conversation_id = (x($_REQUEST,'conversation_id')?$_REQUEST['conversation_id']:0);
1102 $start = $page*$count;
1106 $sql_extra .= ' AND `item`.`id` <= '.intval($max_id);
1107 if ($exclude_replies > 0)
1108 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
1109 if ($conversation_id > 0)
1110 $sql_extra .= ' AND `item`.`parent` = '.intval($conversation_id);
1112 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1113 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1114 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1115 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1116 FROM `item`, `contact`
1117 WHERE `item`.`uid` = %d AND `verb` = '%s'
1118 AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1119 AND `contact`.`id` = `item`.`contact-id`
1120 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1123 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1125 dbesc(ACTIVITY_POST),
1127 intval($start), intval($count)
1130 $ret = api_format_items($r,$user_info);
1132 // We aren't going to try to figure out at the item, group, and page
1133 // level which items you've seen and which you haven't. If you're looking
1134 // at the network timeline just mark everything seen.
1136 $r = q("UPDATE `item` SET `unseen` = 0
1137 WHERE `unseen` = 1 AND `uid` = %d",
1138 //intval($user_info['uid'])
1143 $data = array('$statuses' => $ret);
1147 $data = api_rss_extra($a, $data, $user_info);
1150 $as = api_format_as($a, $ret, $user_info);
1151 $as['title'] = $a->config['sitename']." Home Timeline";
1152 $as['link']['url'] = $a->get_baseurl()."/".$user_info["screen_name"]."/all";
1157 return api_apply_template("timeline", $type, $data);
1159 api_register_func('api/statuses/home_timeline','api_statuses_home_timeline', true);
1160 api_register_func('api/statuses/friends_timeline','api_statuses_home_timeline', true);
1162 function api_statuses_public_timeline(&$a, $type){
1163 if (api_user()===false) return false;
1165 $user_info = api_get_user($a);
1166 // get last newtork messages
1170 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1171 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1172 if ($page<0) $page=0;
1173 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1174 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1175 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1176 $exclude_replies = (x($_REQUEST,'exclude_replies')?1:0);
1177 $conversation_id = (x($_REQUEST,'conversation_id')?$_REQUEST['conversation_id']:0);
1179 $start = $page*$count;
1182 $sql_extra = 'AND `item`.`id` <= '.intval($max_id);
1183 if ($exclude_replies > 0)
1184 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
1185 if ($conversation_id > 0)
1186 $sql_extra .= ' AND `item`.`parent` = '.intval($conversation_id);
1188 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1189 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1190 `contact`.`network`, `contact`.`thumb`, `contact`.`self`, `contact`.`writable`,
1191 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`,
1192 `user`.`nickname`, `user`.`hidewall`
1193 FROM `item` STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
1194 STRAIGHT_JOIN `user` ON `user`.`uid` = `item`.`uid`
1195 WHERE `verb` = '%s' AND `item`.`visible` = 1 AND `item`.`deleted` = 0 and `item`.`moderated` = 0
1196 AND `item`.`allow_cid` = '' AND `item`.`allow_gid` = ''
1197 AND `item`.`deny_cid` = '' AND `item`.`deny_gid` = ''
1198 AND `item`.`private` = 0 AND `item`.`wall` = 1 AND `user`.`hidewall` = 0
1199 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1202 ORDER BY `item`.`id` DESC LIMIT %d, %d ",
1203 dbesc(ACTIVITY_POST),
1208 $ret = api_format_items($r,$user_info);
1211 $data = array('$statuses' => $ret);
1215 $data = api_rss_extra($a, $data, $user_info);
1218 $as = api_format_as($a, $ret, $user_info);
1219 $as['title'] = $a->config['sitename']." Public Timeline";
1220 $as['link']['url'] = $a->get_baseurl()."/";
1225 return api_apply_template("timeline", $type, $data);
1227 api_register_func('api/statuses/public_timeline','api_statuses_public_timeline', true);
1232 function api_statuses_show(&$a, $type){
1233 if (api_user()===false) return false;
1235 $user_info = api_get_user($a);
1238 $id = intval($a->argv[3]);
1241 $id = intval($_REQUEST["id"]);
1245 $id = intval($a->argv[4]);
1247 logger('API: api_statuses_show: '.$id);
1249 $conversation = (x($_REQUEST,'conversation')?1:0);
1253 $sql_extra .= " AND `item`.`parent` = %d ORDER BY `received` ASC ";
1255 $sql_extra .= " AND `item`.`id` = %d";
1257 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1258 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1259 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1260 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1261 FROM `item`, `contact`
1262 WHERE `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1263 AND `contact`.`id` = `item`.`contact-id` AND `item`.`uid` = %d AND `item`.`verb` = '%s'
1264 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1267 dbesc(ACTIVITY_POST),
1272 die(api_error($a, $type, t("There is no status with this id.")));
1274 $ret = api_format_items($r,$user_info);
1276 if ($conversation) {
1277 $data = array('$statuses' => $ret);
1278 return api_apply_template("timeline", $type, $data);
1280 $data = array('$status' => $ret[0]);
1284 $data = api_rss_extra($a, $data, $user_info);
1286 return api_apply_template("status", $type, $data);
1289 api_register_func('api/statuses/show','api_statuses_show', true);
1295 function api_conversation_show(&$a, $type){
1296 if (api_user()===false) return false;
1298 $user_info = api_get_user($a);
1301 $id = intval($a->argv[3]);
1302 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1303 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1304 if ($page<0) $page=0;
1305 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1306 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1308 $start = $page*$count;
1311 $id = intval($_REQUEST["id"]);
1315 $id = intval($a->argv[4]);
1317 logger('API: api_conversation_show: '.$id);
1322 $sql_extra = ' AND `item`.`id` <= '.intval($max_id);
1324 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1325 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1326 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1327 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1328 FROM `item` INNER JOIN (SELECT `uri`,`parent` FROM `item` WHERE `id` = %d) AS `temp1`
1329 ON (`item`.`thr-parent` = `temp1`.`uri` AND `item`.`parent` = `temp1`.`parent`), `contact`
1330 WHERE `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1331 AND `item`.`uid` = %d AND `item`.`verb` = '%s' AND `contact`.`id` = `item`.`contact-id`
1332 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1333 AND `item`.`id`>%d $sql_extra
1334 ORDER BY `item`.`id` DESC LIMIT %d ,%d",
1335 intval($id), intval(api_user()),
1336 dbesc(ACTIVITY_POST),
1338 intval($start), intval($count)
1342 die(api_error($a, $type, t("There is no conversation with this id.")));
1344 $ret = api_format_items($r,$user_info);
1346 $data = array('$statuses' => $ret);
1347 return api_apply_template("timeline", $type, $data);
1349 api_register_func('api/conversation/show','api_conversation_show', true);
1355 function api_statuses_repeat(&$a, $type){
1358 if (api_user()===false) return false;
1360 $user_info = api_get_user($a);
1363 $id = intval($a->argv[3]);
1366 $id = intval($_REQUEST["id"]);
1370 $id = intval($a->argv[4]);
1372 logger('API: api_statuses_repeat: '.$id);
1374 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`, `contact`.`nick` as `reply_author`,
1375 `contact`.`name`, `contact`.`photo` as `reply_photo`, `contact`.`url` as `reply_url`, `contact`.`rel`,
1376 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1377 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1378 FROM `item`, `contact`
1379 WHERE `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1380 AND `contact`.`id` = `item`.`contact-id`
1381 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1383 AND `item`.`id`=%d",
1387 if ($r[0]['body'] != "") {
1388 if (!intval(get_config('system','old_share'))) {
1389 if (strpos($r[0]['body'], "[/share]") !== false) {
1390 $pos = strpos($r[0]['body'], "[share");
1391 $post = substr($r[0]['body'], $pos);
1393 $post = "[share author='".str_replace("'", "'", $r[0]['author-name']).
1394 "' profile='".$r[0]['author-link'].
1395 "' avatar='".$r[0]['author-avatar'].
1396 "' link='".$r[0]['plink']."']";
1397 $post .= $r[0]['body'];
1398 $post .= "[/share]";
1400 $_REQUEST['body'] = $post;
1402 $_REQUEST['body'] = html_entity_decode("♲ ", ENT_QUOTES, 'UTF-8')."[url=".$r[0]['reply_url']."]".$r[0]['reply_author']."[/url] \n".$r[0]['body'];
1404 $_REQUEST['profile_uid'] = api_user();
1405 $_REQUEST['type'] = 'wall';
1406 $_REQUEST['api_source'] = true;
1408 if (!x($_REQUEST, "source"))
1409 $_REQUEST["source"] = api_source();
1411 require_once('mod/item.php');
1415 // this should output the last post (the one we just posted).
1417 return(api_status_show($a,$type));
1419 api_register_func('api/statuses/retweet','api_statuses_repeat', true);
1424 function api_statuses_destroy(&$a, $type){
1425 if (api_user()===false) return false;
1427 $user_info = api_get_user($a);
1430 $id = intval($a->argv[3]);
1433 $id = intval($_REQUEST["id"]);
1437 $id = intval($a->argv[4]);
1439 logger('API: api_statuses_destroy: '.$id);
1441 $ret = api_statuses_show($a, $type);
1443 require_once('include/items.php');
1444 drop_item($id, false);
1448 api_register_func('api/statuses/destroy','api_statuses_destroy', true);
1452 * http://developer.twitter.com/doc/get/statuses/mentions
1455 function api_statuses_mentions(&$a, $type){
1456 if (api_user()===false) return false;
1458 unset($_REQUEST["user_id"]);
1459 unset($_GET["user_id"]);
1461 unset($_REQUEST["screen_name"]);
1462 unset($_GET["screen_name"]);
1464 $user_info = api_get_user($a);
1465 // get last newtork messages
1469 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1470 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1471 if ($page<0) $page=0;
1472 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1473 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1474 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1476 $start = $page*$count;
1478 // Ugly code - should be changed
1479 $myurl = $a->get_baseurl() . '/profile/'. $a->user['nickname'];
1480 $myurl = substr($myurl,strpos($myurl,'://')+3);
1481 //$myurl = str_replace(array('www.','.'),array('','\\.'),$myurl);
1482 $myurl = str_replace('www.','',$myurl);
1483 $diasp_url = str_replace('/profile/','/u/',$myurl);
1486 $sql_extra = ' AND `item`.`id` <= '.intval($max_id);
1488 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1489 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1490 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1491 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1492 FROM `item`, `contact`
1493 WHERE `item`.`uid` = %d AND `verb` = '%s'
1494 AND NOT (`item`.`author-link` IN ('https://%s', 'http://%s'))
1495 AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1496 AND `contact`.`id` = `item`.`contact-id`
1497 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1498 AND `item`.`parent` IN (SELECT `iid` from thread where uid = %d AND `mention` AND !`ignored`)
1501 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1503 dbesc(ACTIVITY_POST),
1504 dbesc(protect_sprintf($myurl)),
1505 dbesc(protect_sprintf($myurl)),
1508 intval($start), intval($count)
1511 $ret = api_format_items($r,$user_info);
1514 $data = array('$statuses' => $ret);
1518 $data = api_rss_extra($a, $data, $user_info);
1521 $as = api_format_as($a, $ret, $user_info);
1522 $as["title"] = $a->config['sitename']." Mentions";
1523 $as['link']['url'] = $a->get_baseurl()."/";
1528 return api_apply_template("timeline", $type, $data);
1530 api_register_func('api/statuses/mentions','api_statuses_mentions', true);
1531 api_register_func('api/statuses/replies','api_statuses_mentions', true);
1534 function api_statuses_user_timeline(&$a, $type){
1535 if (api_user()===false) return false;
1537 $user_info = api_get_user($a);
1538 // get last network messages
1540 logger("api_statuses_user_timeline: api_user: ". api_user() .
1541 "\nuser_info: ".print_r($user_info, true) .
1542 "\n_REQUEST: ".print_r($_REQUEST, true),
1546 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1547 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1548 if ($page<0) $page=0;
1549 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1550 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1551 $exclude_replies = (x($_REQUEST,'exclude_replies')?1:0);
1552 $conversation_id = (x($_REQUEST,'conversation_id')?$_REQUEST['conversation_id']:0);
1554 $start = $page*$count;
1557 if ($user_info['self']==1)
1558 $sql_extra .= " AND `item`.`wall` = 1 ";
1560 if ($exclude_replies > 0)
1561 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
1562 if ($conversation_id > 0)
1563 $sql_extra .= ' AND `item`.`parent` = '.intval($conversation_id);
1565 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1566 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1567 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1568 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1569 FROM `item`, `contact`
1570 WHERE `item`.`uid` = %d AND `verb` = '%s'
1571 AND `item`.`contact-id` = %d
1572 AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1573 AND `contact`.`id` = `item`.`contact-id`
1574 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1577 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1579 dbesc(ACTIVITY_POST),
1580 intval($user_info['cid']),
1582 intval($start), intval($count)
1585 $ret = api_format_items($r,$user_info, true);
1587 $data = array('$statuses' => $ret);
1591 $data = api_rss_extra($a, $data, $user_info);
1594 return api_apply_template("timeline", $type, $data);
1597 api_register_func('api/statuses/user_timeline','api_statuses_user_timeline', true);
1601 * Star/unstar an item
1602 * param: id : id of the item
1604 * api v1 : https://web.archive.org/web/20131019055350/https://dev.twitter.com/docs/api/1/post/favorites/create/%3Aid
1606 function api_favorites_create_destroy(&$a, $type){
1607 if (api_user()===false) return false;
1609 # for versioned api.
1610 # TODO: we need a better global soluton
1612 if ($a->argv[1]=="1.1") $action_argv_id=3;
1614 if ($a->argc<=$action_argv_id) die(api_error($a, $type, t("Invalid request.")));
1615 $action = str_replace(".".$type,"",$a->argv[$action_argv_id]);
1616 if ($a->argc==$action_argv_id+2) {
1617 $itemid = intval($a->argv[$action_argv_id+1]);
1619 $itemid = intval($_REQUEST['id']);
1622 $item = q("SELECT * FROM item WHERE id=%d AND uid=%d",
1623 $itemid, api_user());
1625 if ($item===false || count($item)==0) die(api_error($a, $type, t("Invalid item.")));
1629 $item[0]['starred']=1;
1632 $item[0]['starred']=0;
1635 die(api_error($a, $type, t("Invalid action. ".$action)));
1637 $r = q("UPDATE item SET starred=%d WHERE id=%d AND uid=%d",
1638 $item[0]['starred'], $itemid, api_user());
1640 q("UPDATE thread SET starred=%d WHERE iid=%d AND uid=%d",
1641 $item[0]['starred'], $itemid, api_user());
1643 if ($r===false) die(api_error($a, $type, t("DB error")));
1646 $user_info = api_get_user($a);
1647 $rets = api_format_items($item,$user_info);
1650 $data = array('$status' => $ret);
1654 $data = api_rss_extra($a, $data, $user_info);
1657 return api_apply_template("status", $type, $data);
1660 api_register_func('api/favorites/create', 'api_favorites_create_destroy', true);
1661 api_register_func('api/favorites/destroy', 'api_favorites_create_destroy', true);
1663 function api_favorites(&$a, $type){
1666 if (api_user()===false) return false;
1668 $called_api= array();
1670 $user_info = api_get_user($a);
1672 // in friendica starred item are private
1673 // return favorites only for self
1674 logger('api_favorites: self:' . $user_info['self']);
1676 if ($user_info['self']==0) {
1682 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1683 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1684 $count = (x($_GET,'count')?$_GET['count']:20);
1685 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1686 if ($page<0) $page=0;
1688 $start = $page*$count;
1691 $sql_extra .= ' AND `item`.`id` <= '.intval($max_id);
1693 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1694 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1695 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1696 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1697 FROM `item`, `contact`
1698 WHERE `item`.`uid` = %d
1699 AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1700 AND `item`.`starred` = 1
1701 AND `contact`.`id` = `item`.`contact-id`
1702 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1705 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1708 intval($start), intval($count)
1711 $ret = api_format_items($r,$user_info);
1715 $data = array('$statuses' => $ret);
1719 $data = api_rss_extra($a, $data, $user_info);
1722 return api_apply_template("timeline", $type, $data);
1725 api_register_func('api/favorites','api_favorites', true);
1730 function api_format_as($a, $ret, $user_info) {
1733 $as['title'] = $a->config['sitename']." Public Timeline";
1735 foreach ($ret as $item) {
1736 $singleitem["actor"]["displayName"] = $item["user"]["name"];
1737 $singleitem["actor"]["id"] = $item["user"]["contact_url"];
1738 $avatar[0]["url"] = $item["user"]["profile_image_url"];
1739 $avatar[0]["rel"] = "avatar";
1740 $avatar[0]["type"] = "";
1741 $avatar[0]["width"] = 96;
1742 $avatar[0]["height"] = 96;
1743 $avatar[1]["url"] = $item["user"]["profile_image_url"];
1744 $avatar[1]["rel"] = "avatar";
1745 $avatar[1]["type"] = "";
1746 $avatar[1]["width"] = 48;
1747 $avatar[1]["height"] = 48;
1748 $avatar[2]["url"] = $item["user"]["profile_image_url"];
1749 $avatar[2]["rel"] = "avatar";
1750 $avatar[2]["type"] = "";
1751 $avatar[2]["width"] = 24;
1752 $avatar[2]["height"] = 24;
1753 $singleitem["actor"]["avatarLinks"] = $avatar;
1755 $singleitem["actor"]["image"]["url"] = $item["user"]["profile_image_url"];
1756 $singleitem["actor"]["image"]["rel"] = "avatar";
1757 $singleitem["actor"]["image"]["type"] = "";
1758 $singleitem["actor"]["image"]["width"] = 96;
1759 $singleitem["actor"]["image"]["height"] = 96;
1760 $singleitem["actor"]["type"] = "person";
1761 $singleitem["actor"]["url"] = $item["person"]["contact_url"];
1762 $singleitem["actor"]["statusnet:profile_info"]["local_id"] = $item["user"]["id"];
1763 $singleitem["actor"]["statusnet:profile_info"]["following"] = $item["user"]["following"] ? "true" : "false";
1764 $singleitem["actor"]["statusnet:profile_info"]["blocking"] = "false";
1765 $singleitem["actor"]["contact"]["preferredUsername"] = $item["user"]["screen_name"];
1766 $singleitem["actor"]["contact"]["displayName"] = $item["user"]["name"];
1767 $singleitem["actor"]["contact"]["addresses"] = "";
1769 $singleitem["body"] = $item["text"];
1770 $singleitem["object"]["displayName"] = $item["text"];
1771 $singleitem["object"]["id"] = $item["url"];
1772 $singleitem["object"]["type"] = "note";
1773 $singleitem["object"]["url"] = $item["url"];
1774 //$singleitem["context"] =;
1775 $singleitem["postedTime"] = date("c", strtotime($item["published"]));
1776 $singleitem["provider"]["objectType"] = "service";
1777 $singleitem["provider"]["displayName"] = "Test";
1778 $singleitem["provider"]["url"] = "http://test.tld";
1779 $singleitem["title"] = $item["text"];
1780 $singleitem["verb"] = "post";
1781 $singleitem["statusnet:notice_info"]["local_id"] = $item["id"];
1782 $singleitem["statusnet:notice_info"]["source"] = $item["source"];
1783 $singleitem["statusnet:notice_info"]["favorite"] = "false";
1784 $singleitem["statusnet:notice_info"]["repeated"] = "false";
1785 //$singleitem["original"] = $item;
1786 $items[] = $singleitem;
1788 $as['items'] = $items;
1789 $as['link']['url'] = $a->get_baseurl()."/".$user_info["screen_name"]."/all";
1790 $as['link']['rel'] = "alternate";
1791 $as['link']['type'] = "text/html";
1795 function api_format_messages($item, $recipient, $sender) {
1796 // standard meta information
1798 'id' => $item['id'],
1799 'sender_id' => $sender['id'] ,
1801 'recipient_id' => $recipient['id'],
1802 'created_at' => api_date($item['created']),
1803 'sender_screen_name' => $sender['screen_name'],
1804 'recipient_screen_name' => $recipient['screen_name'],
1805 'sender' => $sender,
1806 'recipient' => $recipient,
1809 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1810 unset($ret["sender"]["uid"]);
1811 unset($ret["sender"]["self"]);
1812 unset($ret["recipient"]["uid"]);
1813 unset($ret["recipient"]["self"]);
1815 //don't send title to regular StatusNET requests to avoid confusing these apps
1816 if (x($_GET, 'getText')) {
1817 $ret['title'] = $item['title'] ;
1818 if ($_GET["getText"] == "html") {
1819 $ret['text'] = bbcode($item['body'], false, false);
1821 elseif ($_GET["getText"] == "plain") {
1822 //$ret['text'] = html2plain(bbcode($item['body'], false, false, true), 0);
1823 $ret['text'] = trim(html2plain(bbcode(api_clean_plain_items($item['body']), false, false, 2, true), 0));
1827 $ret['text'] = $item['title']."\n".html2plain(bbcode(api_clean_plain_items($item['body']), false, false, 2, true), 0);
1829 if (isset($_GET["getUserObjects"]) && $_GET["getUserObjects"] == "false") {
1830 unset($ret['sender']);
1831 unset($ret['recipient']);
1837 function api_convert_item($item) {
1839 $body = $item['body'];
1840 $attachments = api_get_attachments($body);
1842 // Workaround for ostatus messages where the title is identically to the body
1843 $html = bbcode(api_clean_plain_items($body), false, false, 2, true);
1844 $statusbody = trim(html2plain($html, 0));
1846 // handle data: images
1847 $statusbody = api_format_items_embeded_images($item,$statusbody);
1849 $statustitle = trim($item['title']);
1851 if (($statustitle != '') and (strpos($statusbody, $statustitle) !== false))
1852 $statustext = trim($statusbody);
1854 $statustext = trim($statustitle."\n\n".$statusbody);
1856 if (($item["network"] == NETWORK_FEED) and (strlen($statustext)> 1000))
1857 $statustext = substr($statustext, 0, 1000)."... \n".$item["plink"];
1859 $statushtml = trim(bbcode($body, false, false));
1861 if ($item['title'] != "")
1862 $statushtml = "<h4>".bbcode($item['title'])."</h4>\n".$statushtml;
1864 $entities = api_get_entitities($statustext, $body);
1866 return(array("text" => $statustext, "html" => $statushtml, "attachments" => $attachments, "entities" => $entities));
1869 function api_get_attachments(&$body) {
1872 $text = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $text);
1874 $URLSearchString = "^\[\]";
1875 $ret = preg_match_all("/\[img\]([$URLSearchString]*)\[\/img\]/ism", $text, $images);
1880 require_once("include/Photo.php");
1882 $attachments = array();
1884 foreach ($images[1] AS $image) {
1885 $imagedata = get_photo_info($image);
1888 $attachments[] = array("url" => $image, "mimetype" => $imagedata["mime"], "size" => $imagedata["size"]);
1891 if (strstr($_SERVER['HTTP_USER_AGENT'], "AndStatus"))
1892 foreach ($images[0] AS $orig)
1893 $body = str_replace($orig, "", $body);
1895 return $attachments;
1898 function api_get_entitities(&$text, $bbcode) {
1901 * Links at the first character of the post
1906 $include_entities = strtolower(x($_REQUEST,'include_entities')?$_REQUEST['include_entities']:"false");
1908 if ($include_entities != "true") {
1909 require_once("mod/proxy.php");
1911 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
1913 foreach ($images[1] AS $image) {
1914 $replace = proxy_url($image);
1915 $text = str_replace($image, $replace, $text);
1920 $bbcode = bb_CleanPictureLinks($bbcode);
1922 // Change pure links in text to bbcode uris
1923 $bbcode = preg_replace("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", '$1[url=$2]$2[/url]', $bbcode);
1925 $entities = array();
1926 $entities["hashtags"] = array();
1927 $entities["symbols"] = array();
1928 $entities["urls"] = array();
1929 $entities["user_mentions"] = array();
1931 $URLSearchString = "^\[\]";
1933 $bbcode = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'#$2',$bbcode);
1935 $bbcode = preg_replace("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism",'[url=$1]$2[/url]',$bbcode);
1936 //$bbcode = preg_replace("/\[url\](.*?)\[\/url\]/ism",'[url=$1]$1[/url]',$bbcode);
1937 $bbcode = preg_replace("/\[video\](.*?)\[\/video\]/ism",'[url=$1]$1[/url]',$bbcode);
1939 $bbcode = preg_replace("/\[youtube\]([A-Za-z0-9\-_=]+)(.*?)\[\/youtube\]/ism",
1940 '[url=https://www.youtube.com/watch?v=$1]https://www.youtube.com/watch?v=$1[/url]', $bbcode);
1941 $bbcode = preg_replace("/\[youtube\](.*?)\[\/youtube\]/ism",'[url=$1]$1[/url]',$bbcode);
1943 $bbcode = preg_replace("/\[vimeo\]([0-9]+)(.*?)\[\/vimeo\]/ism",
1944 '[url=https://vimeo.com/$1]https://vimeo.com/$1[/url]', $bbcode);
1945 $bbcode = preg_replace("/\[vimeo\](.*?)\[\/vimeo\]/ism",'[url=$1]$1[/url]',$bbcode);
1947 $bbcode = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $bbcode);
1949 //preg_match_all("/\[url\]([$URLSearchString]*)\[\/url\]/ism", $bbcode, $urls1);
1950 preg_match_all("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $bbcode, $urls);
1952 $ordered_urls = array();
1953 foreach ($urls[1] AS $id=>$url) {
1954 //$start = strpos($text, $url, $offset);
1955 $start = iconv_strpos($text, $url, 0, "UTF-8");
1956 if (!($start === false))
1957 $ordered_urls[$start] = array("url" => $url, "title" => $urls[2][$id]);
1960 ksort($ordered_urls);
1963 //foreach ($urls[1] AS $id=>$url) {
1964 foreach ($ordered_urls AS $url) {
1965 if ((substr($url["title"], 0, 7) != "http://") AND (substr($url["title"], 0, 8) != "https://") AND
1966 !strpos($url["title"], "http://") AND !strpos($url["title"], "https://"))
1967 $display_url = $url["title"];
1969 $display_url = str_replace(array("http://www.", "https://www."), array("", ""), $url["url"]);
1970 $display_url = str_replace(array("http://", "https://"), array("", ""), $display_url);
1972 if (strlen($display_url) > 26)
1973 $display_url = substr($display_url, 0, 25)."…";
1976 //$start = strpos($text, $url, $offset);
1977 $start = iconv_strpos($text, $url["url"], $offset, "UTF-8");
1978 if (!($start === false)) {
1979 $entities["urls"][] = array("url" => $url["url"],
1980 "expanded_url" => $url["url"],
1981 "display_url" => $display_url,
1982 "indices" => array($start, $start+strlen($url["url"])));
1983 $offset = $start + 1;
1987 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
1988 $ordered_images = array();
1989 foreach ($images[1] AS $image) {
1990 //$start = strpos($text, $url, $offset);
1991 $start = iconv_strpos($text, $image, 0, "UTF-8");
1992 if (!($start === false))
1993 $ordered_images[$start] = $image;
1995 //$entities["media"] = array();
1998 foreach ($ordered_images AS $url) {
1999 $display_url = str_replace(array("http://www.", "https://www."), array("", ""), $url);
2000 $display_url = str_replace(array("http://", "https://"), array("", ""), $display_url);
2002 if (strlen($display_url) > 26)
2003 $display_url = substr($display_url, 0, 25)."…";
2005 $start = iconv_strpos($text, $url, $offset, "UTF-8");
2006 if (!($start === false)) {
2007 require_once("include/Photo.php");
2008 $image = get_photo_info($url);
2010 // If image cache is activated, then use the following sizes:
2011 // thumb (150), small (340), medium (600) and large (1024)
2012 if (!get_config("system", "proxy_disabled")) {
2013 require_once("mod/proxy.php");
2014 $media_url = proxy_url($url);
2017 $scale = scale_image($image[0], $image[1], 150);
2018 $sizes["thumb"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2020 if (($image[0] > 150) OR ($image[1] > 150)) {
2021 $scale = scale_image($image[0], $image[1], 340);
2022 $sizes["small"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2025 $scale = scale_image($image[0], $image[1], 600);
2026 $sizes["medium"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2028 if (($image[0] > 600) OR ($image[1] > 600)) {
2029 $scale = scale_image($image[0], $image[1], 1024);
2030 $sizes["large"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2034 $sizes["medium"] = array("w" => $image[0], "h" => $image[1], "resize" => "fit");
2037 $entities["media"][] = array(
2039 "id_str" => (string)$start+1,
2040 "indices" => array($start, $start+strlen($url)),
2041 "media_url" => normalise_link($media_url),
2042 "media_url_https" => $media_url,
2044 "display_url" => $display_url,
2045 "expanded_url" => $url,
2049 $offset = $start + 1;
2055 function api_format_items_embeded_images($item, $text){
2057 $text = preg_replace_callback(
2058 "|data:image/([^;]+)[^=]+=*|m",
2059 function($match) use ($a, $item) {
2060 return $a->get_baseurl()."/display/".$item['guid'];
2066 function api_format_items($r,$user_info, $filter_user = false) {
2071 foreach($r as $item) {
2072 api_share_as_retweet($item);
2074 localize_item($item);
2075 $status_user = api_item_get_user($a,$item);
2077 // Look if the posts are matching if they should be filtered by user id
2078 if ($filter_user AND ($status_user["id"] != $user_info["id"]))
2081 if ($item['thr-parent'] != $item['uri']) {
2082 $r = q("SELECT id FROM item WHERE uid=%d AND uri='%s' LIMIT 1",
2084 dbesc($item['thr-parent']));
2086 $in_reply_to_status_id = intval($r[0]['id']);
2088 $in_reply_to_status_id = intval($item['parent']);
2090 $in_reply_to_status_id_str = (string) intval($item['parent']);
2092 $in_reply_to_screen_name = NULL;
2093 $in_reply_to_user_id = NULL;
2094 $in_reply_to_user_id_str = NULL;
2096 $r = q("SELECT `author-link` FROM item WHERE uid=%d AND id=%d LIMIT 1",
2098 intval($in_reply_to_status_id));
2100 $r = q("SELECT * FROM unique_contacts WHERE `url` = '%s'", dbesc(normalise_link($r[0]['author-link'])));
2103 if ($r[0]['nick'] == "")
2104 $r[0]['nick'] = api_get_nick($r[0]["url"]);
2106 $in_reply_to_screen_name = (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']);
2107 $in_reply_to_user_id = intval($r[0]['id']);
2108 $in_reply_to_user_id_str = (string) intval($r[0]['id']);
2112 $in_reply_to_screen_name = NULL;
2113 $in_reply_to_user_id = NULL;
2114 $in_reply_to_status_id = NULL;
2115 $in_reply_to_user_id_str = NULL;
2116 $in_reply_to_status_id_str = NULL;
2119 $converted = api_convert_item($item);
2122 'text' => $converted["text"],
2123 'truncated' => False,
2124 'created_at'=> api_date($item['created']),
2125 'in_reply_to_status_id' => $in_reply_to_status_id,
2126 'in_reply_to_status_id_str' => $in_reply_to_status_id_str,
2127 'source' => (($item['app']) ? $item['app'] : 'web'),
2128 'id' => intval($item['id']),
2129 'id_str' => (string) intval($item['id']),
2130 'in_reply_to_user_id' => $in_reply_to_user_id,
2131 'in_reply_to_user_id_str' => $in_reply_to_user_id_str,
2132 'in_reply_to_screen_name' => $in_reply_to_screen_name,
2134 'favorited' => $item['starred'] ? true : false,
2135 'user' => $status_user ,
2136 //'entities' => NULL,
2137 'statusnet_html' => $converted["html"],
2138 'statusnet_conversation_id' => $item['parent'],
2141 if (count($converted["attachments"]) > 0)
2142 $status["attachments"] = $converted["attachments"];
2144 if (count($converted["entities"]) > 0)
2145 $status["entities"] = $converted["entities"];
2147 if (($item['item_network'] != "") AND ($status["source"] == 'web'))
2148 $status["source"] = network_to_name($item['item_network']);
2149 else if (($item['item_network'] != "") AND (network_to_name($item['item_network']) != $status["source"]))
2150 $status["source"] = trim($status["source"].' ('.network_to_name($item['item_network']).')');
2153 // Retweets are only valid for top postings
2154 // It doesn't work reliable with the link if its a feed
2155 $IsRetweet = ($item['owner-link'] != $item['author-link']);
2157 $IsRetweet = (($item['owner-name'] != $item['author-name']) OR ($item['owner-avatar'] != $item['author-avatar']));
2159 if ($IsRetweet AND ($item["id"] == $item["parent"])) {
2160 $retweeted_status = $status;
2161 $retweeted_status["user"] = api_get_user($a,$item["author-link"]);
2163 $status["retweeted_status"] = $retweeted_status;
2166 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2167 unset($status["user"]["uid"]);
2168 unset($status["user"]["self"]);
2170 // 'geo' => array('type' => 'Point',
2171 // 'coordinates' => array((float) $notice->lat,
2172 // (float) $notice->lon));
2180 function api_account_rate_limit_status(&$a,$type) {
2183 'reset_time_in_seconds' => strtotime('now + 1 hour'),
2184 'remaining_hits' => (string) 150,
2185 'hourly_limit' => (string) 150,
2186 'reset_time' => api_date(datetime_convert('UTC','UTC','now + 1 hour',ATOM_TIME)),
2189 $hash['resettime_in_seconds'] = $hash['reset_time_in_seconds'];
2191 return api_apply_template('ratelimit', $type, array('$hash' => $hash));
2194 api_register_func('api/account/rate_limit_status','api_account_rate_limit_status',true);
2196 function api_help_test(&$a,$type) {
2203 return api_apply_template('test', $type, array("$ok" => $ok));
2206 api_register_func('api/help/test','api_help_test',false);
2208 function api_lists(&$a,$type) {
2213 api_register_func('api/lists','api_lists',true);
2215 function api_lists_list(&$a,$type) {
2220 api_register_func('api/lists/list','api_lists_list',true);
2223 * https://dev.twitter.com/docs/api/1/get/statuses/friends
2224 * This function is deprecated by Twitter
2225 * returns: json, xml
2227 function api_statuses_f(&$a, $type, $qtype) {
2228 if (api_user()===false) return false;
2229 $user_info = api_get_user($a);
2231 if (x($_GET,'cursor') && $_GET['cursor']=='undefined'){
2232 /* this is to stop Hotot to load friends multiple times
2233 * I'm not sure if I'm missing return something or
2234 * is a bug in hotot. Workaround, meantime
2238 return array('$users' => $ret);*/
2242 if($qtype == 'friends')
2243 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
2244 if($qtype == 'followers')
2245 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
2247 // friends and followers only for self
2248 if ($user_info['self'] == 0)
2249 $sql_extra = " AND false ";
2251 $r = q("SELECT `nurl` FROM `contact` WHERE `uid` = %d AND `self` = 0 AND `blocked` = 0 AND `pending` = 0 $sql_extra",
2256 foreach($r as $cid){
2257 $user = api_get_user($a, $cid['nurl']);
2258 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2259 unset($user["uid"]);
2260 unset($user["self"]);
2266 return array('$users' => $ret);
2269 function api_statuses_friends(&$a, $type){
2270 $data = api_statuses_f($a,$type,"friends");
2271 if ($data===false) return false;
2272 return api_apply_template("friends", $type, $data);
2274 function api_statuses_followers(&$a, $type){
2275 $data = api_statuses_f($a,$type,"followers");
2276 if ($data===false) return false;
2277 return api_apply_template("friends", $type, $data);
2279 api_register_func('api/statuses/friends','api_statuses_friends',true);
2280 api_register_func('api/statuses/followers','api_statuses_followers',true);
2287 function api_statusnet_config(&$a,$type) {
2288 $name = $a->config['sitename'];
2289 $server = $a->get_hostname();
2290 $logo = $a->get_baseurl() . '/images/friendica-64.png';
2291 $email = $a->config['admin_email'];
2292 $closed = (($a->config['register_policy'] == REGISTER_CLOSED) ? 'true' : 'false');
2293 $private = (($a->config['system']['block_public']) ? 'true' : 'false');
2294 $textlimit = (string) (($a->config['max_import_size']) ? $a->config['max_import_size'] : 200000);
2295 if($a->config['api_import_size'])
2296 $texlimit = string($a->config['api_import_size']);
2297 $ssl = (($a->config['system']['have_ssl']) ? 'true' : 'false');
2298 $sslserver = (($ssl === 'true') ? str_replace('http:','https:',$a->get_baseurl()) : '');
2301 'site' => array('name' => $name,'server' => $server, 'theme' => 'default', 'path' => '',
2302 'logo' => $logo, 'fancy' => true, 'language' => 'en', 'email' => $email, 'broughtby' => '',
2303 'broughtbyurl' => '', 'timezone' => 'UTC', 'closed' => $closed, 'inviteonly' => false,
2304 'private' => $private, 'textlimit' => $textlimit, 'sslserver' => $sslserver, 'ssl' => $ssl,
2305 'shorturllength' => '30',
2306 'friendica' => array(
2307 'FRIENDICA_PLATFORM' => FRIENDICA_PLATFORM,
2308 'FRIENDICA_VERSION' => FRIENDICA_VERSION,
2309 'DFRN_PROTOCOL_VERSION' => DFRN_PROTOCOL_VERSION,
2310 'DB_UPDATE_VERSION' => DB_UPDATE_VERSION
2315 return api_apply_template('config', $type, array('$config' => $config));
2318 api_register_func('api/statusnet/config','api_statusnet_config',false);
2320 function api_statusnet_version(&$a,$type) {
2324 if($type === 'xml') {
2325 header("Content-type: application/xml");
2326 echo '<?xml version="1.0" encoding="UTF-8"?>' . "\r\n" . '<version>0.9.7</version>' . "\r\n";
2329 elseif($type === 'json') {
2330 header("Content-type: application/json");
2335 api_register_func('api/statusnet/version','api_statusnet_version',false);
2338 function api_ff_ids(&$a,$type,$qtype) {
2342 $user_info = api_get_user($a);
2344 if($qtype == 'friends')
2345 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
2346 if($qtype == 'followers')
2347 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
2349 if (!$user_info["self"])
2350 $sql_extra = " AND false ";
2352 $stringify_ids = (x($_REQUEST,'stringify_ids')?$_REQUEST['stringify_ids']:false);
2354 $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",
2360 if($type === 'xml') {
2361 header("Content-type: application/xml");
2362 echo '<?xml version="1.0" encoding="UTF-8"?>' . "\r\n" . '<ids>' . "\r\n";
2364 echo '<id>' . $rr['id'] . '</id>' . "\r\n";
2365 echo '</ids>' . "\r\n";
2368 elseif($type === 'json') {
2370 header("Content-type: application/json");
2375 $ret[] = intval($rr['id']);
2377 echo json_encode($ret);
2383 function api_friends_ids(&$a,$type) {
2384 api_ff_ids($a,$type,'friends');
2386 function api_followers_ids(&$a,$type) {
2387 api_ff_ids($a,$type,'followers');
2389 api_register_func('api/friends/ids','api_friends_ids',true);
2390 api_register_func('api/followers/ids','api_followers_ids',true);
2393 function api_direct_messages_new(&$a, $type) {
2394 if (api_user()===false) return false;
2396 if (!x($_POST, "text") OR (!x($_POST,"screen_name") AND !x($_POST,"user_id"))) return;
2398 $sender = api_get_user($a);
2400 require_once("include/message.php");
2402 if ($_POST['screen_name']) {
2403 $r = q("SELECT `id`, `nurl`, `network` FROM `contact` WHERE `uid`=%d AND `nick`='%s'",
2405 dbesc($_POST['screen_name']));
2407 // Selecting the id by priority, friendica first
2408 api_best_nickname($r);
2410 $recipient = api_get_user($a, $r[0]['nurl']);
2412 $recipient = api_get_user($a, $_POST['user_id']);
2416 if (x($_REQUEST,'replyto')) {
2417 $r = q('SELECT `parent-uri`, `title` FROM `mail` WHERE `uid`=%d AND `id`=%d',
2419 intval($_REQUEST['replyto']));
2420 $replyto = $r[0]['parent-uri'];
2421 $sub = $r[0]['title'];
2424 if (x($_REQUEST,'title')) {
2425 $sub = $_REQUEST['title'];
2428 $sub = ((strlen($_POST['text'])>10)?substr($_POST['text'],0,10)."...":$_POST['text']);
2432 $id = send_message($recipient['cid'], $_POST['text'], $sub, $replyto);
2435 $r = q("SELECT * FROM `mail` WHERE id=%d", intval($id));
2436 $ret = api_format_messages($r[0], $recipient, $sender);
2439 $ret = array("error"=>$id);
2442 $data = Array('$messages'=>$ret);
2447 $data = api_rss_extra($a, $data, $user_info);
2450 return api_apply_template("direct_messages", $type, $data);
2453 api_register_func('api/direct_messages/new','api_direct_messages_new',true);
2455 function api_direct_messages_box(&$a, $type, $box) {
2456 if (api_user()===false) return false;
2460 $count = (x($_GET,'count')?$_GET['count']:20);
2461 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
2462 if ($page<0) $page=0;
2464 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
2465 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
2467 $user_id = (x($_REQUEST,'user_id')?$_REQUEST['user_id']:"");
2468 $screen_name = (x($_REQUEST,'screen_name')?$_REQUEST['screen_name']:"");
2471 unset($_REQUEST["user_id"]);
2472 unset($_GET["user_id"]);
2474 unset($_REQUEST["screen_name"]);
2475 unset($_GET["screen_name"]);
2477 $user_info = api_get_user($a);
2478 //$profile_url = $a->get_baseurl() . '/profile/' . $a->user['nickname'];
2479 $profile_url = $user_info["url"];
2483 $start = $page*$count;
2486 if ($box=="sentbox") {
2487 $sql_extra = "`mail`.`from-url`='".dbesc( $profile_url )."'";
2489 elseif ($box=="conversation") {
2490 $sql_extra = "`mail`.`parent-uri`='".dbesc( $_GET["uri"] ) ."'";
2492 elseif ($box=="all") {
2493 $sql_extra = "true";
2495 elseif ($box=="inbox") {
2496 $sql_extra = "`mail`.`from-url`!='".dbesc( $profile_url )."'";
2500 $sql_extra .= ' AND `mail`.`id` <= '.intval($max_id);
2502 if ($user_id !="") {
2503 $sql_extra .= ' AND `mail`.`contact-id` = ' . intval($user_id);
2505 elseif($screen_name !=""){
2506 $sql_extra .= " AND `contact`.`nick` = '" . dbesc($screen_name). "'";
2509 $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",
2512 intval($start), intval($count)
2517 foreach($r as $item) {
2518 if ($box == "inbox" || $item['from-url'] != $profile_url){
2519 $recipient = $user_info;
2520 $sender = api_get_user($a,normalise_link($item['contact-url']));
2522 elseif ($box == "sentbox" || $item['from-url'] == $profile_url){
2523 $recipient = api_get_user($a,normalise_link($item['contact-url']));
2524 $sender = $user_info;
2527 $ret[]=api_format_messages($item, $recipient, $sender);
2531 $data = array('$messages' => $ret);
2535 $data = api_rss_extra($a, $data, $user_info);
2538 return api_apply_template("direct_messages", $type, $data);
2542 function api_direct_messages_sentbox(&$a, $type){
2543 return api_direct_messages_box($a, $type, "sentbox");
2545 function api_direct_messages_inbox(&$a, $type){
2546 return api_direct_messages_box($a, $type, "inbox");
2548 function api_direct_messages_all(&$a, $type){
2549 return api_direct_messages_box($a, $type, "all");
2551 function api_direct_messages_conversation(&$a, $type){
2552 return api_direct_messages_box($a, $type, "conversation");
2554 api_register_func('api/direct_messages/conversation','api_direct_messages_conversation',true);
2555 api_register_func('api/direct_messages/all','api_direct_messages_all',true);
2556 api_register_func('api/direct_messages/sent','api_direct_messages_sentbox',true);
2557 api_register_func('api/direct_messages','api_direct_messages_inbox',true);
2561 function api_oauth_request_token(&$a, $type){
2563 $oauth = new FKOAuth1();
2564 $r = $oauth->fetch_request_token(OAuthRequest::from_request());
2565 }catch(Exception $e){
2566 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage()); killme();
2571 function api_oauth_access_token(&$a, $type){
2573 $oauth = new FKOAuth1();
2574 $r = $oauth->fetch_access_token(OAuthRequest::from_request());
2575 }catch(Exception $e){
2576 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage()); killme();
2582 api_register_func('api/oauth/request_token', 'api_oauth_request_token', false);
2583 api_register_func('api/oauth/access_token', 'api_oauth_access_token', false);
2586 function api_fr_photos_list(&$a,$type) {
2587 if (api_user()===false) return false;
2588 $r = q("select distinct `resource-id` from photo where uid = %d and album != 'Contact Photos' ",
2589 intval(local_user())
2594 $ret[] = $rr['resource-id'];
2595 header("Content-type: application/json");
2596 echo json_encode($ret);
2601 function api_fr_photo_detail(&$a,$type) {
2602 if (api_user()===false) return false;
2603 if(! $_REQUEST['photo_id']) return false;
2604 $scale = ((array_key_exists('scale',$_REQUEST)) ? intval($_REQUEST['scale']) : 0);
2605 $r = q("select * from photo where uid = %d and `resource-id` = '%s' and scale = %d limit 1",
2606 intval(local_user()),
2607 dbesc($_REQUEST['photo_id']),
2611 header("Content-type: application/json");
2612 $r[0]['data'] = base64_encode($r[0]['data']);
2613 echo json_encode($r[0]);
2619 api_register_func('api/friendica/photos/list', 'api_fr_photos_list', true);
2620 api_register_func('api/friendica/photo', 'api_fr_photo_detail', true);
2624 function api_share_as_retweet(&$item) {
2625 $body = trim($item["body"]);
2627 // Skip if it isn't a pure repeated messages
2628 // Does it start with a share?
2629 if (strpos($body, "[share") > 0)
2632 // Does it end with a share?
2633 if (strlen($body) > (strrpos($body, "[/share]") + 8))
2636 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$1",$body);
2637 // Skip if there is no shared message in there
2638 if ($body == $attributes)
2642 preg_match("/author='(.*?)'/ism", $attributes, $matches);
2643 if ($matches[1] != "")
2644 $author = html_entity_decode($matches[1],ENT_QUOTES,'UTF-8');
2646 preg_match('/author="(.*?)"/ism', $attributes, $matches);
2647 if ($matches[1] != "")
2648 $author = $matches[1];
2651 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
2652 if ($matches[1] != "")
2653 $profile = $matches[1];
2655 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
2656 if ($matches[1] != "")
2657 $profile = $matches[1];
2660 preg_match("/avatar='(.*?)'/ism", $attributes, $matches);
2661 if ($matches[1] != "")
2662 $avatar = $matches[1];
2664 preg_match('/avatar="(.*?)"/ism', $attributes, $matches);
2665 if ($matches[1] != "")
2666 $avatar = $matches[1];
2669 preg_match("/link='(.*?)'/ism", $attributes, $matches);
2670 if ($matches[1] != "")
2671 $link = $matches[1];
2673 preg_match('/link="(.*?)"/ism', $attributes, $matches);
2674 if ($matches[1] != "")
2675 $link = $matches[1];
2677 $shared_body = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$2",$body);
2679 if (($shared_body == "") OR ($profile == "") OR ($author == "") OR ($avatar == ""))
2682 $item["body"] = $shared_body;
2683 $item["author-name"] = $author;
2684 $item["author-link"] = $profile;
2685 $item["author-avatar"] = $avatar;
2686 $item["plink"] = $link;
2692 function api_get_nick($profile) {
2694 - remove trailing jung from profile url
2695 - pump.io check has to check the website
2700 $friendica = preg_replace("=https?://(.*)/profile/(.*)=ism", "$2", $profile);
2701 if ($friendica != $profile)
2705 $diaspora = preg_replace("=https?://(.*)/u/(.*)=ism", "$2", $profile);
2706 if ($diaspora != $profile)
2711 $twitter = preg_replace("=https?://twitter.com/(.*)=ism", "$1", $profile);
2712 if ($twitter != $profile)
2718 $StatusnetHost = preg_replace("=https?://(.*)/user/(.*)=ism", "$1", $profile);
2719 if ($StatusnetHost != $profile) {
2720 $StatusnetUser = preg_replace("=https?://(.*)/user/(.*)=ism", "$2", $profile);
2721 if ($StatusnetUser != $profile) {
2722 $UserData = fetch_url("http://".$StatusnetHost."/api/users/show.json?user_id=".$StatusnetUser);
2723 $user = json_decode($UserData);
2725 $nick = $user->screen_name;
2730 // To-Do: look at the page if its really a pumpio site
2731 //if (!$nick == "") {
2732 // $pumpio = preg_replace("=https?://(.*)/(.*)/=ism", "$2", $profile."/");
2733 // if ($pumpio != $profile)
2735 // <div class="media" id="profile-block" data-profile-id="acct:kabniel@microca.st">
2740 q("UPDATE unique_contacts SET nick = '%s' WHERE url = '%s'",
2741 dbesc($nick), dbesc(normalise_link($profile)));
2748 function api_clean_plain_items($Text) {
2749 $include_entities = strtolower(x($_REQUEST,'include_entities')?$_REQUEST['include_entities']:"false");
2751 $Text = bb_CleanPictureLinks($Text);
2753 $URLSearchString = "^\[\]";
2755 $Text = preg_replace("/([!#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'$1$3',$Text);
2757 if ($include_entities == "true") {
2758 $Text = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'[url=$1]$1[/url]',$Text);
2761 $Text = preg_replace_callback("((.*?)\[class=(.*?)\](.*?)\[\/class\])ism","api_cleanup_share",$Text);
2765 function api_cleanup_share($shared) {
2766 if ($shared[2] != "type-link")
2769 if (!preg_match_all("/\[bookmark\=([^\]]*)\](.*?)\[\/bookmark\]/ism",$shared[3], $bookmark))
2775 if (isset($bookmark[2][0]))
2776 $title = $bookmark[2][0];
2778 if (isset($bookmark[1][0]))
2779 $link = $bookmark[1][0];
2781 if (strpos($shared[1],$title) !== false)
2784 if (strpos($shared[1],$link) !== false)
2787 $text = trim($shared[1]);
2789 //if (strlen($text) < strlen($title))
2790 if (($text == "") AND ($title != ""))
2791 $text .= "\n\n".trim($title);
2794 $text .= "\n".trim($link);
2796 return(trim($text));
2799 function api_best_nickname(&$contacts) {
2800 $best_contact = array();
2802 if (count($contact) == 0)
2805 foreach ($contacts AS $contact)
2806 if ($contact["network"] == "") {
2807 $contact["network"] = "dfrn";
2808 $best_contact = array($contact);
2811 if (sizeof($best_contact) == 0)
2812 foreach ($contacts AS $contact)
2813 if ($contact["network"] == "dfrn")
2814 $best_contact = array($contact);
2816 if (sizeof($best_contact) == 0)
2817 foreach ($contacts AS $contact)
2818 if ($contact["network"] == "dspr")
2819 $best_contact = array($contact);
2821 if (sizeof($best_contact) == 0)
2822 foreach ($contacts AS $contact)
2823 if ($contact["network"] == "stat")
2824 $best_contact = array($contact);
2826 if (sizeof($best_contact) == 0)
2827 foreach ($contacts AS $contact)
2828 if ($contact["network"] == "pump")
2829 $best_contact = array($contact);
2831 if (sizeof($best_contact) == 0)
2832 foreach ($contacts AS $contact)
2833 if ($contact["network"] == "twit")
2834 $best_contact = array($contact);
2836 if (sizeof($best_contact) == 1)
2837 $contacts = $best_contact;
2839 $contacts = array($contacts[0]);
2843 Not implemented by now:
2844 statuses/retweets_of_me
2849 account/update_location
2850 account/update_profile_background_image
2851 account/update_profile_image
2855 Not implemented in status.net:
2856 statuses/retweeted_to_me
2857 statuses/retweeted_by_me
2858 direct_messages/destroy
2860 account/update_delivery_device
2861 notifications/follow