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");
10 require_once("mod/share.php");
11 require_once("include/Photo.php");
22 // It is not sufficient to use local_user() to check whether someone is allowed to use the API,
23 // because this will open CSRF holes (just embed an image with src=friendicasite.com/api/statuses/update?status=CSRF
24 // into a page, and visitors will post something without noticing it).
25 // Instead, use this function.
26 if ($_SESSION["allow_api"])
32 function api_source() {
33 if (requestdata('source'))
34 return (requestdata('source'));
36 // Support for known clients that doesn't send a source name
37 if (strstr($_SERVER['HTTP_USER_AGENT'], "Twidere"))
40 logger("Unrecognized user-agent ".$_SERVER['HTTP_USER_AGENT'], LOGGER_DEBUG);
45 function api_date($str){
46 //Wed May 23 06:01:13 +0000 2007
47 return datetime_convert('UTC', 'UTC', $str, "D M d H:i:s +0000 Y" );
51 function api_register_func($path, $func, $auth=false){
53 $API[$path] = array('func'=>$func, 'auth'=>$auth);
55 // Workaround for hotot
56 $path = str_replace("api/", "api/1.1/", $path);
57 $API[$path] = array('func'=>$func, 'auth'=>$auth);
64 function api_login(&$a){
67 $oauth = new FKOAuth1();
68 list($consumer,$token) = $oauth->verify_request(OAuthRequest::from_request());
69 if (!is_null($token)){
70 $oauth->loginUser($token->uid);
71 call_hooks('logged_in', $a->user);
74 echo __file__.__line__.__function__."<pre>"; var_dump($consumer, $token); die();
76 logger(__file__.__line__.__function__."\n".$e);
77 //die(__file__.__line__.__function__."<pre>".$e); die();
82 // workaround for HTTP-auth in CGI mode
83 if(x($_SERVER,'REDIRECT_REMOTE_USER')) {
84 $userpass = base64_decode(substr($_SERVER["REDIRECT_REMOTE_USER"],6)) ;
85 if(strlen($userpass)) {
86 list($name, $password) = explode(':', $userpass);
87 $_SERVER['PHP_AUTH_USER'] = $name;
88 $_SERVER['PHP_AUTH_PW'] = $password;
92 if (!isset($_SERVER['PHP_AUTH_USER'])) {
93 logger('API_login: ' . print_r($_SERVER,true), LOGGER_DEBUG);
94 header('WWW-Authenticate: Basic realm="Friendica"');
95 header('HTTP/1.0 401 Unauthorized');
96 die((api_error($a, 'json', "This api requires login")));
98 //die('This api requires login');
101 $user = $_SERVER['PHP_AUTH_USER'];
102 $password = $_SERVER['PHP_AUTH_PW'];
103 $encrypted = hash('whirlpool',trim($password));
107 * next code from mod/auth.php. needs better solution
112 'username' => trim($user),
113 'password' => trim($password),
114 'authenticated' => 0,
115 'user_record' => null
120 * A plugin indicates successful login by setting 'authenticated' to non-zero value and returning a user record
121 * Plugins should never set 'authenticated' except to indicate success - as hooks may be chained
122 * and later plugins should not interfere with an earlier one that succeeded.
126 call_hooks('authenticate', $addon_auth);
128 if(($addon_auth['authenticated']) && (count($addon_auth['user_record']))) {
129 $record = $addon_auth['user_record'];
132 // process normal login request
134 $r = q("SELECT * FROM `user` WHERE ( `email` = '%s' OR `nickname` = '%s' )
135 AND `password` = '%s' AND `blocked` = 0 AND `account_expired` = 0 AND `account_removed` = 0 AND `verified` = 1 LIMIT 1",
144 if((! $record) || (! count($record))) {
145 logger('API_login failure: ' . print_r($_SERVER,true), LOGGER_DEBUG);
146 header('WWW-Authenticate: Basic realm="Friendica"');
147 header('HTTP/1.0 401 Unauthorized');
148 die('This api requires login');
151 require_once('include/security.php');
152 authenticate_success($record); $_SESSION["allow_api"] = true;
154 call_hooks('logged_in', $a->user);
158 /**************************
159 * MAIN API ENTRY POINT *
160 **************************/
161 function api_call(&$a){
162 GLOBAL $API, $called_api;
166 foreach ($API as $p=>$info){
167 if (strpos($a->query_string, $p)===0){
168 $called_api= explode("/",$p);
169 //unset($_SERVER['PHP_AUTH_USER']);
170 if ($info['auth']===true && api_user()===false) {
174 load_contact_links(api_user());
176 logger('API call for ' . $a->user['username'] . ': ' . $a->query_string);
177 logger('API parameters: ' . print_r($_REQUEST,true));
179 if (strpos($a->query_string, ".xml")>0) $type="xml";
180 if (strpos($a->query_string, ".json")>0) $type="json";
181 if (strpos($a->query_string, ".rss")>0) $type="rss";
182 if (strpos($a->query_string, ".atom")>0) $type="atom";
183 if (strpos($a->query_string, ".as")>0) $type="as";
185 $r = call_user_func($info['func'], $a, $type);
186 if ($r===false) return;
190 $r = mb_convert_encoding($r, "UTF-8",mb_detect_encoding($r));
191 header ("Content-Type: text/xml");
192 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
195 header ("Content-Type: application/json");
197 $json = json_encode($rr);
198 if ($_GET['callback'])
199 $json = $_GET['callback']."(".$json.")";
203 header ("Content-Type: application/rss+xml");
204 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
207 header ("Content-Type: application/atom+xml");
208 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
211 //header ("Content-Type: application/json");
213 // return json_encode($rr);
214 return json_encode($r);
218 //echo "<pre>"; var_dump($r); die();
221 header("HTTP/1.1 404 Not Found");
222 logger('API call not implemented: '.$a->query_string." - ".print_r($_REQUEST,true));
223 return(api_error($a, $type, "not implemented"));
227 function api_error(&$a, $type, $error) {
228 # TODO: https://dev.twitter.com/overview/api/response-codes
229 $r = "<status><error>".$error."</error><request>".$a->query_string."</request></status>";
232 header ("Content-Type: text/xml");
233 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
236 header ("Content-Type: application/json");
237 return json_encode(array('error' => $error, 'request' => $a->query_string));
240 header ("Content-Type: application/rss+xml");
241 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
244 header ("Content-Type: application/atom+xml");
245 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
253 function api_rss_extra(&$a, $arr, $user_info){
254 if (is_null($user_info)) $user_info = api_get_user($a);
255 $arr['$user'] = $user_info;
256 $arr['$rss'] = array(
257 'alternate' => $user_info['url'],
258 'self' => $a->get_baseurl(). "/". $a->query_string,
259 'base' => $a->get_baseurl(),
260 'updated' => api_date(null),
261 'atom_updated' => datetime_convert('UTC','UTC','now',ATOM_TIME),
262 'language' => $user_info['language'],
263 'logo' => $a->get_baseurl()."/images/friendica-32.png",
271 * Unique contact to contact url.
273 function api_unique_id_to_url($id){
274 $r = q("SELECT url FROM unique_contacts WHERE id=%d LIMIT 1",
277 return ($r[0]["url"]);
283 * Returns user info array.
285 function api_get_user(&$a, $contact_id = Null, $type = "json"){
292 logger("api_get_user: Fetching user data for user ".$contact_id, LOGGER_DEBUG);
294 // Searching for contact URL
295 if(!is_null($contact_id) AND (intval($contact_id) == 0)){
296 $user = dbesc(normalise_link($contact_id));
298 $extra_query = "AND `contact`.`nurl` = '%s' ";
299 if (api_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(api_user());
302 // Searching for unique contact id
303 if(!is_null($contact_id) AND (intval($contact_id) != 0)){
304 $user = dbesc(api_unique_id_to_url($contact_id));
307 die(api_error($a, $type, t("User not found.")));
310 $extra_query = "AND `contact`.`nurl` = '%s' ";
311 if (api_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(api_user());
314 if(is_null($user) && x($_GET, 'user_id')) {
315 $user = dbesc(api_unique_id_to_url($_GET['user_id']));
318 die(api_error($a, $type, t("User not found.")));
321 $extra_query = "AND `contact`.`nurl` = '%s' ";
322 if (api_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(api_user());
324 if(is_null($user) && x($_GET, 'screen_name')) {
325 $user = dbesc($_GET['screen_name']);
327 $extra_query = "AND `contact`.`nick` = '%s' ";
328 if (api_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(api_user());
331 if (is_null($user) AND ($a->argc > (count($called_api)-1)) AND (count($called_api) > 0)){
332 $argid = count($called_api);
333 list($user, $null) = explode(".",$a->argv[$argid]);
334 if(is_numeric($user)){
335 $user = dbesc(api_unique_id_to_url($user));
341 $extra_query = "AND `contact`.`nurl` = '%s' ";
342 if (api_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(api_user());
344 $user = dbesc($user);
346 $extra_query = "AND `contact`.`nick` = '%s' ";
347 if (api_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(api_user());
351 logger("api_get_user: user ".$user, LOGGER_DEBUG);
354 if (api_user()===false) {
355 api_login($a); return False;
357 $user = $_SESSION['uid'];
358 $extra_query = "AND `contact`.`uid` = %d AND `contact`.`self` = 1 ";
363 logger('api_user: ' . $extra_query . ', user: ' . $user);
365 $uinfo = q("SELECT *, `contact`.`id` as `cid` FROM `contact`
371 // Selecting the id by priority, friendica first
372 api_best_nickname($uinfo);
374 // if the contact wasn't found, fetch it from the unique contacts
375 if (count($uinfo)==0) {
379 $r = q("SELECT * FROM unique_contacts WHERE url='%s' LIMIT 1", $url);
381 $r = q("SELECT * FROM unique_contacts WHERE nick='%s' LIMIT 1", $nick);
384 // If no nick where given, extract it from the address
385 if (($r[0]['nick'] == "") OR ($r[0]['name'] == $r[0]['nick']))
386 $r[0]['nick'] = api_get_nick($r[0]["url"]);
390 'id_str' => (string) $r[0]["id"],
391 'name' => $r[0]["name"],
392 'screen_name' => (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']),
394 'description' => NULL,
395 'profile_image_url' => $r[0]["avatar"],
396 'profile_image_url_https' => $r[0]["avatar"],
397 'url' => $r[0]["url"],
398 'protected' => false,
399 'followers_count' => 0,
400 'friends_count' => 0,
401 'created_at' => api_date(0),
402 'favourites_count' => 0,
404 'time_zone' => 'UTC',
405 'statuses_count' => 0,
406 'following' => false,
408 'statusnet_blocking' => false,
409 'notifications' => false,
410 'statusnet_profile_url' => $r[0]["url"],
419 die(api_error($a, $type, t("User not found.")));
423 if($uinfo[0]['self']) {
424 $usr = q("select * from user where uid = %d limit 1",
427 $profile = q("select * from profile where uid = %d and `is-default` = 1 limit 1",
431 //AND `allow_cid`='' AND `allow_gid`='' AND `deny_cid`='' AND `deny_gid`=''",
432 // count public wall messages
433 $r = q("SELECT count(*) as `count` FROM `item`
436 intval($uinfo[0]['uid'])
438 $countitms = $r[0]['count'];
441 //AND `allow_cid`='' AND `allow_gid`='' AND `deny_cid`='' AND `deny_gid`=''",
442 $r = q("SELECT count(*) as `count` FROM `item`
443 WHERE `contact-id` = %d",
444 intval($uinfo[0]['id'])
446 $countitms = $r[0]['count'];
450 $r = q("SELECT count(*) as `count` FROM `contact`
451 WHERE `uid` = %d AND `rel` IN ( %d, %d )
452 AND `self`=0 AND `blocked`=0 AND `pending`=0 AND `hidden`=0",
453 intval($uinfo[0]['uid']),
454 intval(CONTACT_IS_SHARING),
455 intval(CONTACT_IS_FRIEND)
457 $countfriends = $r[0]['count'];
459 $r = q("SELECT count(*) as `count` FROM `contact`
460 WHERE `uid` = %d AND `rel` IN ( %d, %d )
461 AND `self`=0 AND `blocked`=0 AND `pending`=0 AND `hidden`=0",
462 intval($uinfo[0]['uid']),
463 intval(CONTACT_IS_FOLLOWER),
464 intval(CONTACT_IS_FRIEND)
466 $countfollowers = $r[0]['count'];
468 $r = q("SELECT count(*) as `count` FROM item where starred = 1 and uid = %d and deleted = 0",
469 intval($uinfo[0]['uid'])
471 $starred = $r[0]['count'];
474 if(! $uinfo[0]['self']) {
480 // Add a nick if it isn't present there
481 if (($uinfo[0]['nick'] == "") OR ($uinfo[0]['name'] == $uinfo[0]['nick'])) {
482 $uinfo[0]['nick'] = api_get_nick($uinfo[0]["url"]);
485 // Fetching unique id
486 $r = q("SELECT id FROM unique_contacts WHERE url='%s' LIMIT 1", dbesc(normalise_link($uinfo[0]['url'])));
488 // If not there, then add it
489 if (count($r) == 0) {
490 q("INSERT INTO unique_contacts (url, name, nick, avatar) VALUES ('%s', '%s', '%s', '%s')",
491 dbesc(normalise_link($uinfo[0]['url'])), dbesc($uinfo[0]['name']),dbesc($uinfo[0]['nick']), dbesc($uinfo[0]['micro']));
493 $r = q("SELECT id FROM unique_contacts WHERE url='%s' LIMIT 1", dbesc(normalise_link($uinfo[0]['url'])));
496 require_once('include/contact_selectors.php');
497 $network_name = network_to_name($uinfo[0]['network']);
500 'id' => intval($r[0]['id']),
501 'id_str' => (string) intval($r[0]['id']),
502 'name' => (($uinfo[0]['name']) ? $uinfo[0]['name'] : $uinfo[0]['nick']),
503 'screen_name' => (($uinfo[0]['nick']) ? $uinfo[0]['nick'] : $uinfo[0]['name']),
504 'location' => ($usr) ? $usr[0]['default-location'] : $network_name,
505 'description' => (($profile) ? $profile[0]['pdesc'] : NULL),
506 'profile_image_url' => $uinfo[0]['micro'],
507 'profile_image_url_https' => $uinfo[0]['micro'],
508 'url' => $uinfo[0]['url'],
509 'protected' => false,
510 'followers_count' => intval($countfollowers),
511 'friends_count' => intval($countfriends),
512 'created_at' => api_date($uinfo[0]['created']),
513 'favourites_count' => intval($starred),
515 'time_zone' => 'UTC',
516 'statuses_count' => intval($countitms),
517 'following' => (($uinfo[0]['rel'] == CONTACT_IS_FOLLOWER) OR ($uinfo[0]['rel'] == CONTACT_IS_FRIEND)),
519 'statusnet_blocking' => false,
520 'notifications' => false,
521 'statusnet_profile_url' => $a->get_baseurl()."/contacts/".$uinfo[0]['cid'],
522 'uid' => intval($uinfo[0]['uid']),
523 'cid' => intval($uinfo[0]['cid']),
524 'self' => $uinfo[0]['self'],
525 'network' => $uinfo[0]['network'],
532 function api_item_get_user(&$a, $item) {
534 $author = q("SELECT * FROM unique_contacts WHERE url='%s' LIMIT 1",
535 dbesc(normalise_link($item['author-link'])));
537 if (count($author) == 0) {
538 q("INSERT INTO unique_contacts (url, name, avatar) VALUES ('%s', '%s', '%s')",
539 dbesc(normalise_link($item["author-link"])), dbesc($item["author-name"]), dbesc($item["author-avatar"]));
541 $author = q("SELECT id FROM unique_contacts WHERE url='%s' LIMIT 1",
542 dbesc(normalise_link($item['author-link'])));
543 } else if ($item["author-link"].$item["author-name"] != $author[0]["url"].$author[0]["name"]) {
544 q("UPDATE unique_contacts SET name = '%s', avatar = '%s' WHERE url = '%s'",
545 dbesc($item["author-name"]), dbesc($item["author-avatar"]), dbesc(normalise_link($item["author-link"])));
548 $owner = q("SELECT id FROM unique_contacts WHERE url='%s' LIMIT 1",
549 dbesc(normalise_link($item['owner-link'])));
551 if (count($owner) == 0) {
552 q("INSERT INTO unique_contacts (url, name, avatar) VALUES ('%s', '%s', '%s')",
553 dbesc(normalise_link($item["owner-link"])), dbesc($item["owner-name"]), dbesc($item["owner-avatar"]));
555 $owner = q("SELECT id FROM unique_contacts WHERE url='%s' LIMIT 1",
556 dbesc(normalise_link($item['owner-link'])));
557 } else if ($item["owner-link"].$item["owner-name"] != $owner[0]["url"].$owner[0]["name"]) {
558 q("UPDATE unique_contacts SET name = '%s', avatar = '%s' WHERE url = '%s'",
559 dbesc($item["owner-name"]), dbesc($item["owner-avatar"]), dbesc(normalise_link($item["owner-link"])));
562 // Comments in threads may appear as wall-to-wall postings.
563 // So only take the owner at the top posting.
564 if ($item["id"] == $item["parent"])
565 $status_user = api_get_user($a,$item["owner-link"]);
567 $status_user = api_get_user($a,$item["author-link"]);
569 $status_user["protected"] = (($item["allow_cid"] != "") OR
570 ($item["allow_gid"] != "") OR
571 ($item["deny_cid"] != "") OR
572 ($item["deny_gid"] != "") OR
575 return ($status_user);
580 * load api $templatename for $type and replace $data array
582 function api_apply_template($templatename, $type, $data){
590 $data = array_xmlify($data);
591 $tpl = get_markup_template("api_".$templatename."_".$type.".tpl");
593 header ("Content-Type: text/xml");
594 echo '<?xml version="1.0" encoding="UTF-8"?>'."\n".'<status><error>not implemented</error></status>';
597 $ret = replace_macros($tpl, $data);
612 * Returns an HTTP 200 OK response code and a representation of the requesting user if authentication was successful;
613 * returns a 401 status code and an error message if not.
614 * http://developer.twitter.com/doc/get/account/verify_credentials
616 function api_account_verify_credentials(&$a, $type){
617 if (api_user()===false) return false;
619 unset($_REQUEST["user_id"]);
620 unset($_GET["user_id"]);
622 unset($_REQUEST["screen_name"]);
623 unset($_GET["screen_name"]);
625 $skip_status = (x($_REQUEST,'skip_status')?$_REQUEST['skip_status']:false);
627 $user_info = api_get_user($a);
629 // "verified" isn't used here in the standard
630 unset($user_info["verified"]);
632 // - Adding last status
634 $user_info["status"] = api_status_show($a,"raw");
635 if (!count($user_info["status"]))
636 unset($user_info["status"]);
638 unset($user_info["status"]["user"]);
641 // "uid" and "self" are only needed for some internal stuff, so remove it from here
642 unset($user_info["uid"]);
643 unset($user_info["self"]);
645 return api_apply_template("user", $type, array('$user' => $user_info));
648 api_register_func('api/account/verify_credentials','api_account_verify_credentials', true);
652 * get data from $_POST or $_GET
654 function requestdata($k){
655 if (isset($_POST[$k])){
658 if (isset($_GET[$k])){
664 /*Waitman Gobble Mod*/
665 function api_statuses_mediap(&$a, $type) {
666 if (api_user()===false) {
667 logger('api_statuses_update: no user');
670 $user_info = api_get_user($a);
672 $_REQUEST['type'] = 'wall';
673 $_REQUEST['profile_uid'] = api_user();
674 $_REQUEST['api_source'] = true;
675 $txt = requestdata('status');
676 //$txt = urldecode(requestdata('status'));
678 require_once('library/HTMLPurifier.auto.php');
679 require_once('include/html2bbcode.php');
681 if((strpos($txt,'<') !== false) || (strpos($txt,'>') !== false)) {
682 $txt = html2bb_video($txt);
683 $config = HTMLPurifier_Config::createDefault();
684 $config->set('Cache.DefinitionImpl', null);
685 $purifier = new HTMLPurifier($config);
686 $txt = $purifier->purify($txt);
688 $txt = html2bbcode($txt);
690 $a->argv[1]=$user_info['screen_name']; //should be set to username?
692 $_REQUEST['hush']='yeah'; //tell wall_upload function to return img info instead of echo
693 require_once('mod/wall_upload.php');
694 $bebop = wall_upload_post($a);
696 //now that we have the img url in bbcode we can add it to the status and insert the wall item.
697 $_REQUEST['body']=$txt."\n\n".$bebop;
698 require_once('mod/item.php');
701 // this should output the last post (the one we just posted).
702 return api_status_show($a,$type);
704 api_register_func('api/statuses/mediap','api_statuses_mediap', true);
705 /*Waitman Gobble Mod*/
708 function api_statuses_update(&$a, $type) {
709 if (api_user()===false) {
710 logger('api_statuses_update: no user');
714 $user_info = api_get_user($a);
716 // convert $_POST array items to the form we use for web posts.
718 // logger('api_post: ' . print_r($_POST,true));
720 if(requestdata('htmlstatus')) {
721 require_once('library/HTMLPurifier.auto.php');
722 require_once('include/html2bbcode.php');
724 $txt = requestdata('htmlstatus');
725 if((strpos($txt,'<') !== false) || (strpos($txt,'>') !== false)) {
727 $txt = html2bb_video($txt);
729 $config = HTMLPurifier_Config::createDefault();
730 $config->set('Cache.DefinitionImpl', null);
733 $purifier = new HTMLPurifier($config);
734 $txt = $purifier->purify($txt);
736 $_REQUEST['body'] = html2bbcode($txt);
740 $_REQUEST['body'] = requestdata('status');
742 $_REQUEST['title'] = requestdata('title');
744 $parent = requestdata('in_reply_to_status_id');
745 if(ctype_digit($parent))
746 $_REQUEST['parent'] = $parent;
748 $_REQUEST['parent_uri'] = $parent;
750 if(requestdata('lat') && requestdata('long'))
751 $_REQUEST['coord'] = sprintf("%s %s",requestdata('lat'),requestdata('long'));
752 $_REQUEST['profile_uid'] = api_user();
755 $_REQUEST['type'] = 'net-comment';
757 // Check for throttling (maximum posts per day, week and month)
758 $throttle_day = get_config('system','throttle_limit_day');
759 if ($throttle_day > 0) {
760 $datefrom = date("Y-m-d H:i:s", time() - 24*60*60);
762 $r = q("SELECT COUNT(*) AS `posts_day` FROM `item` WHERE `uid`=%d AND `wall`
763 AND `created` > '%s' AND `id` = `parent`",
764 intval(api_user()), dbesc($datefrom));
767 $posts_day = $r[0]["posts_day"];
771 if ($posts_day > $throttle_day) {
772 logger('Daily posting limit reached for user '.api_user(), LOGGER_DEBUG);
773 die(api_error($a, $type, sprintf(t("Daily posting limit of %d posts reached. The post was rejected."), $throttle_day)));
777 $throttle_week = get_config('system','throttle_limit_week');
778 if ($throttle_week > 0) {
779 $datefrom = date("Y-m-d H:i:s", time() - 24*60*60*7);
781 $r = q("SELECT COUNT(*) AS `posts_week` FROM `item` WHERE `uid`=%d AND `wall`
782 AND `created` > '%s' AND `id` = `parent`",
783 intval(api_user()), dbesc($datefrom));
786 $posts_week = $r[0]["posts_week"];
790 if ($posts_week > $throttle_week) {
791 logger('Weekly posting limit reached for user '.api_user(), LOGGER_DEBUG);
792 die(api_error($a, $type, sprintf(t("Weekly posting limit of %d posts reached. The post was rejected."), $throttle_week)));
796 $throttle_month = get_config('system','throttle_limit_month');
797 if ($throttle_month > 0) {
798 $datefrom = date("Y-m-d H:i:s", time() - 24*60*60*30);
800 $r = q("SELECT COUNT(*) AS `posts_month` FROM `item` WHERE `uid`=%d AND `wall`
801 AND `created` > '%s' AND `id` = `parent`",
802 intval(api_user()), dbesc($datefrom));
805 $posts_month = $r[0]["posts_month"];
809 if ($posts_month > $throttle_month) {
810 logger('Monthly posting limit reached for user '.api_user(), LOGGER_DEBUG);
811 die(api_error($a, $type, sprintf(t("Monthly posting limit of %d posts reached. The post was rejected."), $throttle_month)));
815 $_REQUEST['type'] = 'wall';
818 if(x($_FILES,'media')) {
819 // upload the image if we have one
820 $_REQUEST['hush']='yeah'; //tell wall_upload function to return img info instead of echo
821 require_once('mod/wall_upload.php');
822 $media = wall_upload_post($a);
824 $_REQUEST['body'] .= "\n\n".$media;
827 // To-Do: Multiple IDs
828 if (requestdata('media_ids')) {
829 $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",
830 intval(requestdata('media_ids')), api_user());
832 $phototypes = Photo::supportedTypes();
833 $ext = $phototypes[$r[0]['type']];
834 $_REQUEST['body'] .= "\n\n".'[url='.$a->get_baseurl().'/photos/'.$r[0]['nickname'].'/image/'.$r[0]['resource-id'].']';
835 $_REQUEST['body'] .= '[img]'.$a->get_baseurl()."/photo/".$r[0]['resource-id']."-".$r[0]['scale'].".".$ext."[/img][/url]";
839 // set this so that the item_post() function is quiet and doesn't redirect or emit json
841 $_REQUEST['api_source'] = true;
843 if (!x($_REQUEST, "source"))
844 $_REQUEST["source"] = api_source();
846 // call out normal post function
848 require_once('mod/item.php');
851 // this should output the last post (the one we just posted).
852 return api_status_show($a,$type);
854 api_register_func('api/statuses/update','api_statuses_update', true);
855 api_register_func('api/statuses/update_with_media','api_statuses_update', true);
858 function api_media_upload(&$a, $type) {
859 if (api_user()===false) {
864 $user_info = api_get_user($a);
866 if(!x($_FILES,'media')) {
871 require_once('mod/wall_upload.php');
872 $media = wall_upload_post($a, false);
878 $returndata = array();
879 $returndata["media_id"] = $media["id"];
880 $returndata["media_id_string"] = (string)$media["id"];
881 $returndata["size"] = $media["size"];
882 $returndata["image"] = array("w" => $media["width"],
883 "h" => $media["height"],
884 "image_type" => $media["type"]);
886 logger("Media uploaded: ".print_r($returndata, true), LOGGER_DEBUG);
888 return array("media" => $returndata);
891 api_register_func('api/media/upload','api_media_upload', true);
893 function api_status_show(&$a, $type){
894 $user_info = api_get_user($a);
896 logger('api_status_show: user_info: '.print_r($user_info, true), LOGGER_DEBUG);
898 // get last public wall message
899 $lastwall = q("SELECT `item`.*, `i`.`contact-id` as `reply_uid`, `i`.`author-link` AS `item-author`
900 FROM `item`, `item` as `i`
901 WHERE `item`.`contact-id` = %d AND `item`.`uid` = %d
902 AND ((`item`.`author-link` IN ('%s', '%s')) OR (`item`.`owner-link` IN ('%s', '%s')))
903 AND `i`.`id` = `item`.`parent`
904 AND `item`.`type`!='activity'
905 AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''
906 ORDER BY `item`.`created` DESC
908 intval($user_info['cid']),
910 dbesc($user_info['url']),
911 dbesc(normalise_link($user_info['url'])),
912 dbesc($user_info['url']),
913 dbesc(normalise_link($user_info['url']))
916 if (count($lastwall)>0){
917 $lastwall = $lastwall[0];
919 $in_reply_to_status_id = NULL;
920 $in_reply_to_user_id = NULL;
921 $in_reply_to_status_id_str = NULL;
922 $in_reply_to_user_id_str = NULL;
923 $in_reply_to_screen_name = NULL;
924 if (intval($lastwall['parent']) != intval($lastwall['id'])) {
925 $in_reply_to_status_id= intval($lastwall['parent']);
926 $in_reply_to_status_id_str = (string) intval($lastwall['parent']);
928 $r = q("SELECT * FROM unique_contacts WHERE `url` = '%s'", dbesc(normalise_link($lastwall['item-author'])));
930 if ($r[0]['nick'] == "")
931 $r[0]['nick'] = api_get_nick($r[0]["url"]);
933 $in_reply_to_screen_name = (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']);
934 $in_reply_to_user_id = intval($r[0]['id']);
935 $in_reply_to_user_id_str = (string) intval($r[0]['id']);
939 // There seems to be situation, where both fields are identical:
940 // https://github.com/friendica/friendica/issues/1010
941 // This is a bugfix for that.
942 if (intval($in_reply_to_status_id) == intval($lastwall['id'])) {
943 logger('api_status_show: this message should never appear: id: '.$lastwall['id'].' similar to reply-to: '.$in_reply_to_status_id, LOGGER_DEBUG);
944 $in_reply_to_status_id = NULL;
945 $in_reply_to_user_id = NULL;
946 $in_reply_to_status_id_str = NULL;
947 $in_reply_to_user_id_str = NULL;
948 $in_reply_to_screen_name = NULL;
951 $converted = api_convert_item($item);
953 $status_info = array(
954 'text' => $converted["text"],
955 'truncated' => false,
956 'created_at' => api_date($lastwall['created']),
957 'in_reply_to_status_id' => $in_reply_to_status_id,
958 'in_reply_to_status_id_str' => $in_reply_to_status_id_str,
959 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
960 'id' => intval($lastwall['id']),
961 'id_str' => (string) $lastwall['id'],
962 'in_reply_to_user_id' => $in_reply_to_user_id,
963 'in_reply_to_user_id_str' => $in_reply_to_user_id_str,
964 'in_reply_to_screen_name' => $in_reply_to_screen_name,
966 'favorited' => $lastwall['starred'] ? true : false,
967 'user' => $user_info,
968 'statusnet_html' => $converted["html"],
969 'statusnet_conversation_id' => $lastwall['parent'],
972 if (count($converted["attachments"]) > 0)
973 $status_info["attachments"] = $converted["attachments"];
975 if (count($converted["entities"]) > 0)
976 $status_info["entities"] = $converted["entities"];
978 if (($lastwall['item_network'] != "") AND ($status["source"] == 'web'))
979 $status_info["source"] = network_to_name($lastwall['item_network']);
980 elseif (($lastwall['item_network'] != "") AND (network_to_name($lastwall['item_network']) != $status_info["source"]))
981 $status_info["source"] = trim($status_info["source"].' ('.network_to_name($lastwall['item_network']).')');
983 // "uid" and "self" are only needed for some internal stuff, so remove it from here
984 unset($status_info["user"]["uid"]);
985 unset($status_info["user"]["self"]);
989 return($status_info);
991 return api_apply_template("status", $type, array('$status' => $status_info));
1000 * Returns extended information of a given user, specified by ID or screen name as per the required id parameter.
1001 * The author's most recent status will be returned inline.
1002 * http://developer.twitter.com/doc/get/users/show
1004 function api_users_show(&$a, $type){
1005 $user_info = api_get_user($a);
1007 $lastwall = q("SELECT `item`.*
1008 FROM `item`, `contact`
1009 WHERE `item`.`uid` = %d AND `verb` = '%s' AND `item`.`contact-id` = %d
1010 AND ((`item`.`author-link` IN ('%s', '%s')) OR (`item`.`owner-link` IN ('%s', '%s')))
1011 AND `contact`.`id`=`item`.`contact-id`
1012 AND `type`!='activity'
1013 AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''
1014 ORDER BY `created` DESC
1017 dbesc(ACTIVITY_POST),
1018 intval($user_info['cid']),
1019 dbesc($user_info['url']),
1020 dbesc(normalise_link($user_info['url'])),
1021 dbesc($user_info['url']),
1022 dbesc(normalise_link($user_info['url']))
1024 if (count($lastwall)>0){
1025 $lastwall = $lastwall[0];
1027 $in_reply_to_status_id = NULL;
1028 $in_reply_to_user_id = NULL;
1029 $in_reply_to_status_id_str = NULL;
1030 $in_reply_to_user_id_str = NULL;
1031 $in_reply_to_screen_name = NULL;
1032 if ($lastwall['parent']!=$lastwall['id']) {
1033 $reply = q("SELECT `item`.`id`, `item`.`contact-id` as `reply_uid`, `contact`.`nick` as `reply_author`, `item`.`author-link` AS `item-author`
1034 FROM `item`,`contact` WHERE `contact`.`id`=`item`.`contact-id` AND `item`.`id` = %d", intval($lastwall['parent']));
1035 if (count($reply)>0) {
1036 $in_reply_to_status_id = intval($lastwall['parent']);
1037 $in_reply_to_status_id_str = (string) intval($lastwall['parent']);
1039 $r = q("SELECT * FROM unique_contacts WHERE `url` = '%s'", dbesc(normalise_link($reply[0]['item-author'])));
1041 if ($r[0]['nick'] == "")
1042 $r[0]['nick'] = api_get_nick($r[0]["url"]);
1044 $in_reply_to_screen_name = (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']);
1045 $in_reply_to_user_id = intval($r[0]['id']);
1046 $in_reply_to_user_id_str = (string) intval($r[0]['id']);
1051 $converted = api_convert_item($item);
1053 $user_info['status'] = array(
1054 'text' => $converted["text"],
1055 'truncated' => false,
1056 'created_at' => api_date($lastwall['created']),
1057 'in_reply_to_status_id' => $in_reply_to_status_id,
1058 'in_reply_to_status_id_str' => $in_reply_to_status_id_str,
1059 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
1060 'id' => intval($lastwall['contact-id']),
1061 'id_str' => (string) $lastwall['contact-id'],
1062 'in_reply_to_user_id' => $in_reply_to_user_id,
1063 'in_reply_to_user_id_str' => $in_reply_to_user_id_str,
1064 'in_reply_to_screen_name' => $in_reply_to_screen_name,
1066 'favorited' => $lastwall['starred'] ? true : false,
1067 'statusnet_html' => $converted["html"],
1068 'statusnet_conversation_id' => $lastwall['parent'],
1071 if (count($converted["attachments"]) > 0)
1072 $user_info["status"]["attachments"] = $converted["attachments"];
1074 if (count($converted["entities"]) > 0)
1075 $user_info["status"]["entities"] = $converted["entities"];
1077 if (($lastwall['item_network'] != "") AND ($user_info["status"]["source"] == 'web'))
1078 $user_info["status"]["source"] = network_to_name($lastwall['item_network']);
1079 if (($lastwall['item_network'] != "") AND (network_to_name($lastwall['item_network']) != $user_info["status"]["source"]))
1080 $user_info["status"]["source"] = trim($user_info["status"]["source"].' ('.network_to_name($lastwall['item_network']).')');
1084 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1085 unset($user_info["uid"]);
1086 unset($user_info["self"]);
1088 return api_apply_template("user", $type, array('$user' => $user_info));
1091 api_register_func('api/users/show','api_users_show');
1094 function api_users_search(&$a, $type) {
1095 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1097 $userlist = array();
1099 if (isset($_GET["q"])) {
1100 $r = q("SELECT id FROM unique_contacts WHERE name='%s'", dbesc($_GET["q"]));
1102 $r = q("SELECT id FROM unique_contacts WHERE nick='%s'", dbesc($_GET["q"]));
1105 foreach ($r AS $user) {
1106 $user_info = api_get_user($a, $user["id"]);
1107 //echo print_r($user_info, true)."\n";
1108 $userdata = api_apply_template("user", $type, array('user' => $user_info));
1109 $userlist[] = $userdata["user"];
1111 $userlist = array("users" => $userlist);
1113 die(api_error($a, $type, t("User not found.")));
1115 die(api_error($a, $type, t("User not found.")));
1120 api_register_func('api/users/search','api_users_search');
1124 * http://developer.twitter.com/doc/get/statuses/home_timeline
1126 * TODO: Optional parameters
1127 * TODO: Add reply info
1129 function api_statuses_home_timeline(&$a, $type){
1130 if (api_user()===false) return false;
1132 unset($_REQUEST["user_id"]);
1133 unset($_GET["user_id"]);
1135 unset($_REQUEST["screen_name"]);
1136 unset($_GET["screen_name"]);
1138 $user_info = api_get_user($a);
1139 // get last newtork messages
1143 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1144 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1145 if ($page<0) $page=0;
1146 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1147 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1148 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1149 $exclude_replies = (x($_REQUEST,'exclude_replies')?1:0);
1150 $conversation_id = (x($_REQUEST,'conversation_id')?$_REQUEST['conversation_id']:0);
1152 $start = $page*$count;
1156 $sql_extra .= ' AND `item`.`id` <= '.intval($max_id);
1157 if ($exclude_replies > 0)
1158 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
1159 if ($conversation_id > 0)
1160 $sql_extra .= ' AND `item`.`parent` = '.intval($conversation_id);
1162 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1163 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1164 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1165 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1166 FROM `item`, `contact`
1167 WHERE `item`.`uid` = %d AND `verb` = '%s'
1168 AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1169 AND `contact`.`id` = `item`.`contact-id`
1170 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1173 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1175 dbesc(ACTIVITY_POST),
1177 intval($start), intval($count)
1180 $ret = api_format_items($r,$user_info);
1182 // Set all posts from the query above to seen
1184 foreach ($r AS $item)
1185 $idarray[] = intval($item["id"]);
1187 $idlist = implode(",", $idarray);
1189 $r = q("UPDATE `item` SET `unseen` = 0 WHERE `unseen` AND `id` IN (%s)", $idlist);
1192 $data = array('$statuses' => $ret);
1196 $data = api_rss_extra($a, $data, $user_info);
1199 $as = api_format_as($a, $ret, $user_info);
1200 $as['title'] = $a->config['sitename']." Home Timeline";
1201 $as['link']['url'] = $a->get_baseurl()."/".$user_info["screen_name"]."/all";
1206 return api_apply_template("timeline", $type, $data);
1208 api_register_func('api/statuses/home_timeline','api_statuses_home_timeline', true);
1209 api_register_func('api/statuses/friends_timeline','api_statuses_home_timeline', true);
1211 function api_statuses_public_timeline(&$a, $type){
1212 if (api_user()===false) return false;
1214 $user_info = api_get_user($a);
1215 // get last newtork messages
1219 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1220 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1221 if ($page<0) $page=0;
1222 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1223 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1224 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1225 $exclude_replies = (x($_REQUEST,'exclude_replies')?1:0);
1226 $conversation_id = (x($_REQUEST,'conversation_id')?$_REQUEST['conversation_id']:0);
1228 $start = $page*$count;
1231 $sql_extra = 'AND `item`.`id` <= '.intval($max_id);
1232 if ($exclude_replies > 0)
1233 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
1234 if ($conversation_id > 0)
1235 $sql_extra .= ' AND `item`.`parent` = '.intval($conversation_id);
1237 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1238 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1239 `contact`.`network`, `contact`.`thumb`, `contact`.`self`, `contact`.`writable`,
1240 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`,
1241 `user`.`nickname`, `user`.`hidewall`
1242 FROM `item` STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
1243 STRAIGHT_JOIN `user` ON `user`.`uid` = `item`.`uid`
1244 WHERE `verb` = '%s' AND `item`.`visible` = 1 AND `item`.`deleted` = 0 and `item`.`moderated` = 0
1245 AND `item`.`allow_cid` = '' AND `item`.`allow_gid` = ''
1246 AND `item`.`deny_cid` = '' AND `item`.`deny_gid` = ''
1247 AND `item`.`private` = 0 AND `item`.`wall` = 1 AND `user`.`hidewall` = 0
1248 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1251 ORDER BY `item`.`id` DESC LIMIT %d, %d ",
1252 dbesc(ACTIVITY_POST),
1257 $ret = api_format_items($r,$user_info);
1260 $data = array('$statuses' => $ret);
1264 $data = api_rss_extra($a, $data, $user_info);
1267 $as = api_format_as($a, $ret, $user_info);
1268 $as['title'] = $a->config['sitename']." Public Timeline";
1269 $as['link']['url'] = $a->get_baseurl()."/";
1274 return api_apply_template("timeline", $type, $data);
1276 api_register_func('api/statuses/public_timeline','api_statuses_public_timeline', true);
1281 function api_statuses_show(&$a, $type){
1282 if (api_user()===false) return false;
1284 $user_info = api_get_user($a);
1287 $id = intval($a->argv[3]);
1290 $id = intval($_REQUEST["id"]);
1294 $id = intval($a->argv[4]);
1296 logger('API: api_statuses_show: '.$id);
1298 $conversation = (x($_REQUEST,'conversation')?1:0);
1302 $sql_extra .= " AND `item`.`parent` = %d ORDER BY `received` ASC ";
1304 $sql_extra .= " AND `item`.`id` = %d";
1306 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1307 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1308 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1309 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1310 FROM `item`, `contact`
1311 WHERE `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1312 AND `contact`.`id` = `item`.`contact-id` AND `item`.`uid` = %d AND `item`.`verb` = '%s'
1313 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1316 dbesc(ACTIVITY_POST),
1321 die(api_error($a, $type, t("There is no status with this id.")));
1323 $ret = api_format_items($r,$user_info);
1325 if ($conversation) {
1326 $data = array('$statuses' => $ret);
1327 return api_apply_template("timeline", $type, $data);
1329 $data = array('$status' => $ret[0]);
1333 $data = api_rss_extra($a, $data, $user_info);
1335 return api_apply_template("status", $type, $data);
1338 api_register_func('api/statuses/show','api_statuses_show', true);
1344 function api_conversation_show(&$a, $type){
1345 if (api_user()===false) return false;
1347 $user_info = api_get_user($a);
1350 $id = intval($a->argv[3]);
1351 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1352 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1353 if ($page<0) $page=0;
1354 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1355 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1357 $start = $page*$count;
1360 $id = intval($_REQUEST["id"]);
1364 $id = intval($a->argv[4]);
1366 logger('API: api_conversation_show: '.$id);
1371 $sql_extra = ' AND `item`.`id` <= '.intval($max_id);
1373 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1374 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1375 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1376 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1377 FROM `item` INNER JOIN (SELECT `uri`,`parent` FROM `item` WHERE `id` = %d) AS `temp1`
1378 ON (`item`.`thr-parent` = `temp1`.`uri` AND `item`.`parent` = `temp1`.`parent`), `contact`
1379 WHERE `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1380 AND `item`.`uid` = %d AND `item`.`verb` = '%s' AND `contact`.`id` = `item`.`contact-id`
1381 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1382 AND `item`.`id`>%d $sql_extra
1383 ORDER BY `item`.`id` DESC LIMIT %d ,%d",
1384 intval($id), intval(api_user()),
1385 dbesc(ACTIVITY_POST),
1387 intval($start), intval($count)
1391 die(api_error($a, $type, t("There is no conversation with this id.")));
1393 $ret = api_format_items($r,$user_info);
1395 $data = array('$statuses' => $ret);
1396 return api_apply_template("timeline", $type, $data);
1398 api_register_func('api/conversation/show','api_conversation_show', true);
1404 function api_statuses_repeat(&$a, $type){
1407 if (api_user()===false) return false;
1409 $user_info = api_get_user($a);
1412 $id = intval($a->argv[3]);
1415 $id = intval($_REQUEST["id"]);
1419 $id = intval($a->argv[4]);
1421 logger('API: api_statuses_repeat: '.$id);
1423 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`, `contact`.`nick` as `reply_author`,
1424 `contact`.`name`, `contact`.`photo` as `reply_photo`, `contact`.`url` as `reply_url`, `contact`.`rel`,
1425 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1426 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1427 FROM `item`, `contact`
1428 WHERE `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1429 AND `contact`.`id` = `item`.`contact-id`
1430 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1432 AND `item`.`id`=%d",
1436 if ($r[0]['body'] != "") {
1437 if (!intval(get_config('system','old_share'))) {
1438 if (strpos($r[0]['body'], "[/share]") !== false) {
1439 $pos = strpos($r[0]['body'], "[share");
1440 $post = substr($r[0]['body'], $pos);
1442 $post = share_header($r[0]['author-name'], $r[0]['author-link'], $r[0]['author-avatar'], $r[0]['guid'], $r[0]['created'], $r[0]['plink']);
1444 $post .= $r[0]['body'];
1445 $post .= "[/share]";
1447 $_REQUEST['body'] = $post;
1449 $_REQUEST['body'] = html_entity_decode("♲ ", ENT_QUOTES, 'UTF-8')."[url=".$r[0]['reply_url']."]".$r[0]['reply_author']."[/url] \n".$r[0]['body'];
1451 $_REQUEST['profile_uid'] = api_user();
1452 $_REQUEST['type'] = 'wall';
1453 $_REQUEST['api_source'] = true;
1455 if (!x($_REQUEST, "source"))
1456 $_REQUEST["source"] = api_source();
1458 require_once('mod/item.php');
1462 // this should output the last post (the one we just posted).
1464 return(api_status_show($a,$type));
1466 api_register_func('api/statuses/retweet','api_statuses_repeat', true);
1471 function api_statuses_destroy(&$a, $type){
1472 if (api_user()===false) return false;
1474 $user_info = api_get_user($a);
1477 $id = intval($a->argv[3]);
1480 $id = intval($_REQUEST["id"]);
1484 $id = intval($a->argv[4]);
1486 logger('API: api_statuses_destroy: '.$id);
1488 $ret = api_statuses_show($a, $type);
1490 require_once('include/items.php');
1491 drop_item($id, false);
1495 api_register_func('api/statuses/destroy','api_statuses_destroy', true);
1499 * http://developer.twitter.com/doc/get/statuses/mentions
1502 function api_statuses_mentions(&$a, $type){
1503 if (api_user()===false) return false;
1505 unset($_REQUEST["user_id"]);
1506 unset($_GET["user_id"]);
1508 unset($_REQUEST["screen_name"]);
1509 unset($_GET["screen_name"]);
1511 $user_info = api_get_user($a);
1512 // get last newtork messages
1516 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1517 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1518 if ($page<0) $page=0;
1519 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1520 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1521 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1523 $start = $page*$count;
1525 // Ugly code - should be changed
1526 $myurl = $a->get_baseurl() . '/profile/'. $a->user['nickname'];
1527 $myurl = substr($myurl,strpos($myurl,'://')+3);
1528 //$myurl = str_replace(array('www.','.'),array('','\\.'),$myurl);
1529 $myurl = str_replace('www.','',$myurl);
1530 $diasp_url = str_replace('/profile/','/u/',$myurl);
1533 $sql_extra = ' AND `item`.`id` <= '.intval($max_id);
1535 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1536 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1537 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1538 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1539 FROM `item`, `contact`
1540 WHERE `item`.`uid` = %d AND `verb` = '%s'
1541 AND NOT (`item`.`author-link` IN ('https://%s', 'http://%s'))
1542 AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1543 AND `contact`.`id` = `item`.`contact-id`
1544 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1545 AND `item`.`parent` IN (SELECT `iid` from thread where uid = %d AND `mention` AND !`ignored`)
1548 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1550 dbesc(ACTIVITY_POST),
1551 dbesc(protect_sprintf($myurl)),
1552 dbesc(protect_sprintf($myurl)),
1555 intval($start), intval($count)
1558 $ret = api_format_items($r,$user_info);
1561 $data = array('$statuses' => $ret);
1565 $data = api_rss_extra($a, $data, $user_info);
1568 $as = api_format_as($a, $ret, $user_info);
1569 $as["title"] = $a->config['sitename']." Mentions";
1570 $as['link']['url'] = $a->get_baseurl()."/";
1575 return api_apply_template("timeline", $type, $data);
1577 api_register_func('api/statuses/mentions','api_statuses_mentions', true);
1578 api_register_func('api/statuses/replies','api_statuses_mentions', true);
1581 function api_statuses_user_timeline(&$a, $type){
1582 if (api_user()===false) return false;
1584 $user_info = api_get_user($a);
1585 // get last network messages
1587 logger("api_statuses_user_timeline: api_user: ". api_user() .
1588 "\nuser_info: ".print_r($user_info, true) .
1589 "\n_REQUEST: ".print_r($_REQUEST, true),
1593 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1594 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1595 if ($page<0) $page=0;
1596 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1597 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1598 $exclude_replies = (x($_REQUEST,'exclude_replies')?1:0);
1599 $conversation_id = (x($_REQUEST,'conversation_id')?$_REQUEST['conversation_id']:0);
1601 $start = $page*$count;
1604 if ($user_info['self']==1)
1605 $sql_extra .= " AND `item`.`wall` = 1 ";
1607 if ($exclude_replies > 0)
1608 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
1609 if ($conversation_id > 0)
1610 $sql_extra .= ' AND `item`.`parent` = '.intval($conversation_id);
1612 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1613 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1614 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1615 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1616 FROM `item`, `contact`
1617 WHERE `item`.`uid` = %d AND `verb` = '%s'
1618 AND `item`.`contact-id` = %d
1619 AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1620 AND `contact`.`id` = `item`.`contact-id`
1621 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1624 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1626 dbesc(ACTIVITY_POST),
1627 intval($user_info['cid']),
1629 intval($start), intval($count)
1632 $ret = api_format_items($r,$user_info, true);
1634 $data = array('$statuses' => $ret);
1638 $data = api_rss_extra($a, $data, $user_info);
1641 return api_apply_template("timeline", $type, $data);
1644 api_register_func('api/statuses/user_timeline','api_statuses_user_timeline', true);
1648 * Star/unstar an item
1649 * param: id : id of the item
1651 * api v1 : https://web.archive.org/web/20131019055350/https://dev.twitter.com/docs/api/1/post/favorites/create/%3Aid
1653 function api_favorites_create_destroy(&$a, $type){
1654 if (api_user()===false) return false;
1656 # for versioned api.
1657 # TODO: we need a better global soluton
1659 if ($a->argv[1]=="1.1") $action_argv_id=3;
1661 if ($a->argc<=$action_argv_id) die(api_error($a, $type, t("Invalid request.")));
1662 $action = str_replace(".".$type,"",$a->argv[$action_argv_id]);
1663 if ($a->argc==$action_argv_id+2) {
1664 $itemid = intval($a->argv[$action_argv_id+1]);
1666 $itemid = intval($_REQUEST['id']);
1669 $item = q("SELECT * FROM item WHERE id=%d AND uid=%d",
1670 $itemid, api_user());
1672 if ($item===false || count($item)==0) die(api_error($a, $type, t("Invalid item.")));
1676 $item[0]['starred']=1;
1679 $item[0]['starred']=0;
1682 die(api_error($a, $type, t("Invalid action. ".$action)));
1684 $r = q("UPDATE item SET starred=%d WHERE id=%d AND uid=%d",
1685 $item[0]['starred'], $itemid, api_user());
1687 q("UPDATE thread SET starred=%d WHERE iid=%d AND uid=%d",
1688 $item[0]['starred'], $itemid, api_user());
1690 if ($r===false) die(api_error($a, $type, t("DB error")));
1693 $user_info = api_get_user($a);
1694 $rets = api_format_items($item,$user_info);
1697 $data = array('$status' => $ret);
1701 $data = api_rss_extra($a, $data, $user_info);
1704 return api_apply_template("status", $type, $data);
1707 api_register_func('api/favorites/create', 'api_favorites_create_destroy', true);
1708 api_register_func('api/favorites/destroy', 'api_favorites_create_destroy', true);
1710 function api_favorites(&$a, $type){
1713 if (api_user()===false) return false;
1715 $called_api= array();
1717 $user_info = api_get_user($a);
1719 // in friendica starred item are private
1720 // return favorites only for self
1721 logger('api_favorites: self:' . $user_info['self']);
1723 if ($user_info['self']==0) {
1729 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1730 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1731 $count = (x($_GET,'count')?$_GET['count']:20);
1732 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1733 if ($page<0) $page=0;
1735 $start = $page*$count;
1738 $sql_extra .= ' AND `item`.`id` <= '.intval($max_id);
1740 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1741 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1742 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1743 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1744 FROM `item`, `contact`
1745 WHERE `item`.`uid` = %d
1746 AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1747 AND `item`.`starred` = 1
1748 AND `contact`.`id` = `item`.`contact-id`
1749 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1752 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1755 intval($start), intval($count)
1758 $ret = api_format_items($r,$user_info);
1762 $data = array('$statuses' => $ret);
1766 $data = api_rss_extra($a, $data, $user_info);
1769 return api_apply_template("timeline", $type, $data);
1772 api_register_func('api/favorites','api_favorites', true);
1777 function api_format_as($a, $ret, $user_info) {
1780 $as['title'] = $a->config['sitename']." Public Timeline";
1782 foreach ($ret as $item) {
1783 $singleitem["actor"]["displayName"] = $item["user"]["name"];
1784 $singleitem["actor"]["id"] = $item["user"]["contact_url"];
1785 $avatar[0]["url"] = $item["user"]["profile_image_url"];
1786 $avatar[0]["rel"] = "avatar";
1787 $avatar[0]["type"] = "";
1788 $avatar[0]["width"] = 96;
1789 $avatar[0]["height"] = 96;
1790 $avatar[1]["url"] = $item["user"]["profile_image_url"];
1791 $avatar[1]["rel"] = "avatar";
1792 $avatar[1]["type"] = "";
1793 $avatar[1]["width"] = 48;
1794 $avatar[1]["height"] = 48;
1795 $avatar[2]["url"] = $item["user"]["profile_image_url"];
1796 $avatar[2]["rel"] = "avatar";
1797 $avatar[2]["type"] = "";
1798 $avatar[2]["width"] = 24;
1799 $avatar[2]["height"] = 24;
1800 $singleitem["actor"]["avatarLinks"] = $avatar;
1802 $singleitem["actor"]["image"]["url"] = $item["user"]["profile_image_url"];
1803 $singleitem["actor"]["image"]["rel"] = "avatar";
1804 $singleitem["actor"]["image"]["type"] = "";
1805 $singleitem["actor"]["image"]["width"] = 96;
1806 $singleitem["actor"]["image"]["height"] = 96;
1807 $singleitem["actor"]["type"] = "person";
1808 $singleitem["actor"]["url"] = $item["person"]["contact_url"];
1809 $singleitem["actor"]["statusnet:profile_info"]["local_id"] = $item["user"]["id"];
1810 $singleitem["actor"]["statusnet:profile_info"]["following"] = $item["user"]["following"] ? "true" : "false";
1811 $singleitem["actor"]["statusnet:profile_info"]["blocking"] = "false";
1812 $singleitem["actor"]["contact"]["preferredUsername"] = $item["user"]["screen_name"];
1813 $singleitem["actor"]["contact"]["displayName"] = $item["user"]["name"];
1814 $singleitem["actor"]["contact"]["addresses"] = "";
1816 $singleitem["body"] = $item["text"];
1817 $singleitem["object"]["displayName"] = $item["text"];
1818 $singleitem["object"]["id"] = $item["url"];
1819 $singleitem["object"]["type"] = "note";
1820 $singleitem["object"]["url"] = $item["url"];
1821 //$singleitem["context"] =;
1822 $singleitem["postedTime"] = date("c", strtotime($item["published"]));
1823 $singleitem["provider"]["objectType"] = "service";
1824 $singleitem["provider"]["displayName"] = "Test";
1825 $singleitem["provider"]["url"] = "http://test.tld";
1826 $singleitem["title"] = $item["text"];
1827 $singleitem["verb"] = "post";
1828 $singleitem["statusnet:notice_info"]["local_id"] = $item["id"];
1829 $singleitem["statusnet:notice_info"]["source"] = $item["source"];
1830 $singleitem["statusnet:notice_info"]["favorite"] = "false";
1831 $singleitem["statusnet:notice_info"]["repeated"] = "false";
1832 //$singleitem["original"] = $item;
1833 $items[] = $singleitem;
1835 $as['items'] = $items;
1836 $as['link']['url'] = $a->get_baseurl()."/".$user_info["screen_name"]."/all";
1837 $as['link']['rel'] = "alternate";
1838 $as['link']['type'] = "text/html";
1842 function api_format_messages($item, $recipient, $sender) {
1843 // standard meta information
1845 'id' => $item['id'],
1846 'sender_id' => $sender['id'] ,
1848 'recipient_id' => $recipient['id'],
1849 'created_at' => api_date($item['created']),
1850 'sender_screen_name' => $sender['screen_name'],
1851 'recipient_screen_name' => $recipient['screen_name'],
1852 'sender' => $sender,
1853 'recipient' => $recipient,
1856 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1857 unset($ret["sender"]["uid"]);
1858 unset($ret["sender"]["self"]);
1859 unset($ret["recipient"]["uid"]);
1860 unset($ret["recipient"]["self"]);
1862 //don't send title to regular StatusNET requests to avoid confusing these apps
1863 if (x($_GET, 'getText')) {
1864 $ret['title'] = $item['title'] ;
1865 if ($_GET["getText"] == "html") {
1866 $ret['text'] = bbcode($item['body'], false, false);
1868 elseif ($_GET["getText"] == "plain") {
1869 //$ret['text'] = html2plain(bbcode($item['body'], false, false, true), 0);
1870 $ret['text'] = trim(html2plain(bbcode(api_clean_plain_items($item['body']), false, false, 2, true), 0));
1874 $ret['text'] = $item['title']."\n".html2plain(bbcode(api_clean_plain_items($item['body']), false, false, 2, true), 0);
1876 if (isset($_GET["getUserObjects"]) && $_GET["getUserObjects"] == "false") {
1877 unset($ret['sender']);
1878 unset($ret['recipient']);
1884 function api_convert_item($item) {
1886 $body = $item['body'];
1887 $attachments = api_get_attachments($body);
1889 // Workaround for ostatus messages where the title is identically to the body
1890 $html = bbcode(api_clean_plain_items($body), false, false, 2, true);
1891 $statusbody = trim(html2plain($html, 0));
1893 // handle data: images
1894 $statusbody = api_format_items_embeded_images($item,$statusbody);
1896 $statustitle = trim($item['title']);
1898 if (($statustitle != '') and (strpos($statusbody, $statustitle) !== false))
1899 $statustext = trim($statusbody);
1901 $statustext = trim($statustitle."\n\n".$statusbody);
1903 if (($item["network"] == NETWORK_FEED) and (strlen($statustext)> 1000))
1904 $statustext = substr($statustext, 0, 1000)."... \n".$item["plink"];
1906 $statushtml = trim(bbcode($body, false, false));
1908 if ($item['title'] != "")
1909 $statushtml = "<h4>".bbcode($item['title'])."</h4>\n".$statushtml;
1911 $entities = api_get_entitities($statustext, $body);
1913 return(array("text" => $statustext, "html" => $statushtml, "attachments" => $attachments, "entities" => $entities));
1916 function api_get_attachments(&$body) {
1919 $text = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $text);
1921 $URLSearchString = "^\[\]";
1922 $ret = preg_match_all("/\[img\]([$URLSearchString]*)\[\/img\]/ism", $text, $images);
1927 $attachments = array();
1929 foreach ($images[1] AS $image) {
1930 $imagedata = get_photo_info($image);
1933 $attachments[] = array("url" => $image, "mimetype" => $imagedata["mime"], "size" => $imagedata["size"]);
1936 if (strstr($_SERVER['HTTP_USER_AGENT'], "AndStatus"))
1937 foreach ($images[0] AS $orig)
1938 $body = str_replace($orig, "", $body);
1940 return $attachments;
1943 function api_get_entitities(&$text, $bbcode) {
1946 * Links at the first character of the post
1951 $include_entities = strtolower(x($_REQUEST,'include_entities')?$_REQUEST['include_entities']:"false");
1953 if ($include_entities != "true") {
1954 require_once("mod/proxy.php");
1956 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
1958 foreach ($images[1] AS $image) {
1959 $replace = proxy_url($image);
1960 $text = str_replace($image, $replace, $text);
1965 $bbcode = bb_CleanPictureLinks($bbcode);
1967 // Change pure links in text to bbcode uris
1968 $bbcode = preg_replace("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", '$1[url=$2]$2[/url]', $bbcode);
1970 $entities = array();
1971 $entities["hashtags"] = array();
1972 $entities["symbols"] = array();
1973 $entities["urls"] = array();
1974 $entities["user_mentions"] = array();
1976 $URLSearchString = "^\[\]";
1978 $bbcode = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'#$2',$bbcode);
1980 $bbcode = preg_replace("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism",'[url=$1]$2[/url]',$bbcode);
1981 //$bbcode = preg_replace("/\[url\](.*?)\[\/url\]/ism",'[url=$1]$1[/url]',$bbcode);
1982 $bbcode = preg_replace("/\[video\](.*?)\[\/video\]/ism",'[url=$1]$1[/url]',$bbcode);
1984 $bbcode = preg_replace("/\[youtube\]([A-Za-z0-9\-_=]+)(.*?)\[\/youtube\]/ism",
1985 '[url=https://www.youtube.com/watch?v=$1]https://www.youtube.com/watch?v=$1[/url]', $bbcode);
1986 $bbcode = preg_replace("/\[youtube\](.*?)\[\/youtube\]/ism",'[url=$1]$1[/url]',$bbcode);
1988 $bbcode = preg_replace("/\[vimeo\]([0-9]+)(.*?)\[\/vimeo\]/ism",
1989 '[url=https://vimeo.com/$1]https://vimeo.com/$1[/url]', $bbcode);
1990 $bbcode = preg_replace("/\[vimeo\](.*?)\[\/vimeo\]/ism",'[url=$1]$1[/url]',$bbcode);
1992 $bbcode = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $bbcode);
1994 //preg_match_all("/\[url\]([$URLSearchString]*)\[\/url\]/ism", $bbcode, $urls1);
1995 preg_match_all("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $bbcode, $urls);
1997 $ordered_urls = array();
1998 foreach ($urls[1] AS $id=>$url) {
1999 //$start = strpos($text, $url, $offset);
2000 $start = iconv_strpos($text, $url, 0, "UTF-8");
2001 if (!($start === false))
2002 $ordered_urls[$start] = array("url" => $url, "title" => $urls[2][$id]);
2005 ksort($ordered_urls);
2008 //foreach ($urls[1] AS $id=>$url) {
2009 foreach ($ordered_urls AS $url) {
2010 if ((substr($url["title"], 0, 7) != "http://") AND (substr($url["title"], 0, 8) != "https://") AND
2011 !strpos($url["title"], "http://") AND !strpos($url["title"], "https://"))
2012 $display_url = $url["title"];
2014 $display_url = str_replace(array("http://www.", "https://www."), array("", ""), $url["url"]);
2015 $display_url = str_replace(array("http://", "https://"), array("", ""), $display_url);
2017 if (strlen($display_url) > 26)
2018 $display_url = substr($display_url, 0, 25)."…";
2021 //$start = strpos($text, $url, $offset);
2022 $start = iconv_strpos($text, $url["url"], $offset, "UTF-8");
2023 if (!($start === false)) {
2024 $entities["urls"][] = array("url" => $url["url"],
2025 "expanded_url" => $url["url"],
2026 "display_url" => $display_url,
2027 "indices" => array($start, $start+strlen($url["url"])));
2028 $offset = $start + 1;
2032 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2033 $ordered_images = array();
2034 foreach ($images[1] AS $image) {
2035 //$start = strpos($text, $url, $offset);
2036 $start = iconv_strpos($text, $image, 0, "UTF-8");
2037 if (!($start === false))
2038 $ordered_images[$start] = $image;
2040 //$entities["media"] = array();
2043 foreach ($ordered_images AS $url) {
2044 $display_url = str_replace(array("http://www.", "https://www."), array("", ""), $url);
2045 $display_url = str_replace(array("http://", "https://"), array("", ""), $display_url);
2047 if (strlen($display_url) > 26)
2048 $display_url = substr($display_url, 0, 25)."…";
2050 $start = iconv_strpos($text, $url, $offset, "UTF-8");
2051 if (!($start === false)) {
2052 $image = get_photo_info($url);
2054 // If image cache is activated, then use the following sizes:
2055 // thumb (150), small (340), medium (600) and large (1024)
2056 if (!get_config("system", "proxy_disabled")) {
2057 require_once("mod/proxy.php");
2058 $media_url = proxy_url($url);
2061 $scale = scale_image($image[0], $image[1], 150);
2062 $sizes["thumb"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2064 if (($image[0] > 150) OR ($image[1] > 150)) {
2065 $scale = scale_image($image[0], $image[1], 340);
2066 $sizes["small"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2069 $scale = scale_image($image[0], $image[1], 600);
2070 $sizes["medium"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2072 if (($image[0] > 600) OR ($image[1] > 600)) {
2073 $scale = scale_image($image[0], $image[1], 1024);
2074 $sizes["large"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2078 $sizes["medium"] = array("w" => $image[0], "h" => $image[1], "resize" => "fit");
2081 $entities["media"][] = array(
2083 "id_str" => (string)$start+1,
2084 "indices" => array($start, $start+strlen($url)),
2085 "media_url" => normalise_link($media_url),
2086 "media_url_https" => $media_url,
2088 "display_url" => $display_url,
2089 "expanded_url" => $url,
2093 $offset = $start + 1;
2099 function api_format_items_embeded_images($item, $text){
2101 $text = preg_replace_callback(
2102 "|data:image/([^;]+)[^=]+=*|m",
2103 function($match) use ($a, $item) {
2104 return $a->get_baseurl()."/display/".$item['guid'];
2110 function api_format_items($r,$user_info, $filter_user = false) {
2115 foreach($r as $item) {
2116 api_share_as_retweet($item);
2118 localize_item($item);
2119 $status_user = api_item_get_user($a,$item);
2121 // Look if the posts are matching if they should be filtered by user id
2122 if ($filter_user AND ($status_user["id"] != $user_info["id"]))
2125 if ($item['thr-parent'] != $item['uri']) {
2126 $r = q("SELECT id FROM item WHERE uid=%d AND uri='%s' LIMIT 1",
2128 dbesc($item['thr-parent']));
2130 $in_reply_to_status_id = intval($r[0]['id']);
2132 $in_reply_to_status_id = intval($item['parent']);
2134 $in_reply_to_status_id_str = (string) intval($item['parent']);
2136 $in_reply_to_screen_name = NULL;
2137 $in_reply_to_user_id = NULL;
2138 $in_reply_to_user_id_str = NULL;
2140 $r = q("SELECT `author-link` FROM item WHERE uid=%d AND id=%d LIMIT 1",
2142 intval($in_reply_to_status_id));
2144 $r = q("SELECT * FROM unique_contacts WHERE `url` = '%s'", dbesc(normalise_link($r[0]['author-link'])));
2147 if ($r[0]['nick'] == "")
2148 $r[0]['nick'] = api_get_nick($r[0]["url"]);
2150 $in_reply_to_screen_name = (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']);
2151 $in_reply_to_user_id = intval($r[0]['id']);
2152 $in_reply_to_user_id_str = (string) intval($r[0]['id']);
2156 $in_reply_to_screen_name = NULL;
2157 $in_reply_to_user_id = NULL;
2158 $in_reply_to_status_id = NULL;
2159 $in_reply_to_user_id_str = NULL;
2160 $in_reply_to_status_id_str = NULL;
2163 $converted = api_convert_item($item);
2166 'text' => $converted["text"],
2167 'truncated' => False,
2168 'created_at'=> api_date($item['created']),
2169 'in_reply_to_status_id' => $in_reply_to_status_id,
2170 'in_reply_to_status_id_str' => $in_reply_to_status_id_str,
2171 'source' => (($item['app']) ? $item['app'] : 'web'),
2172 'id' => intval($item['id']),
2173 'id_str' => (string) intval($item['id']),
2174 'in_reply_to_user_id' => $in_reply_to_user_id,
2175 'in_reply_to_user_id_str' => $in_reply_to_user_id_str,
2176 'in_reply_to_screen_name' => $in_reply_to_screen_name,
2178 'favorited' => $item['starred'] ? true : false,
2179 'user' => $status_user ,
2180 //'entities' => NULL,
2181 'statusnet_html' => $converted["html"],
2182 'statusnet_conversation_id' => $item['parent'],
2185 if (count($converted["attachments"]) > 0)
2186 $status["attachments"] = $converted["attachments"];
2188 if (count($converted["entities"]) > 0)
2189 $status["entities"] = $converted["entities"];
2191 if (($item['item_network'] != "") AND ($status["source"] == 'web'))
2192 $status["source"] = network_to_name($item['item_network']);
2193 else if (($item['item_network'] != "") AND (network_to_name($item['item_network']) != $status["source"]))
2194 $status["source"] = trim($status["source"].' ('.network_to_name($item['item_network']).')');
2197 // Retweets are only valid for top postings
2198 // It doesn't work reliable with the link if its a feed
2199 $IsRetweet = ($item['owner-link'] != $item['author-link']);
2201 $IsRetweet = (($item['owner-name'] != $item['author-name']) OR ($item['owner-avatar'] != $item['author-avatar']));
2203 if ($IsRetweet AND ($item["id"] == $item["parent"])) {
2204 $retweeted_status = $status;
2205 $retweeted_status["user"] = api_get_user($a,$item["author-link"]);
2207 $status["retweeted_status"] = $retweeted_status;
2210 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2211 unset($status["user"]["uid"]);
2212 unset($status["user"]["self"]);
2214 // 'geo' => array('type' => 'Point',
2215 // 'coordinates' => array((float) $notice->lat,
2216 // (float) $notice->lon));
2224 function api_account_rate_limit_status(&$a,$type) {
2227 'reset_time_in_seconds' => strtotime('now + 1 hour'),
2228 'remaining_hits' => (string) 150,
2229 'hourly_limit' => (string) 150,
2230 'reset_time' => api_date(datetime_convert('UTC','UTC','now + 1 hour',ATOM_TIME)),
2233 $hash['resettime_in_seconds'] = $hash['reset_time_in_seconds'];
2235 return api_apply_template('ratelimit', $type, array('$hash' => $hash));
2238 api_register_func('api/account/rate_limit_status','api_account_rate_limit_status',true);
2240 function api_help_test(&$a,$type) {
2247 return api_apply_template('test', $type, array("$ok" => $ok));
2250 api_register_func('api/help/test','api_help_test',false);
2252 function api_lists(&$a,$type) {
2257 api_register_func('api/lists','api_lists',true);
2259 function api_lists_list(&$a,$type) {
2264 api_register_func('api/lists/list','api_lists_list',true);
2267 * https://dev.twitter.com/docs/api/1/get/statuses/friends
2268 * This function is deprecated by Twitter
2269 * returns: json, xml
2271 function api_statuses_f(&$a, $type, $qtype) {
2272 if (api_user()===false) return false;
2273 $user_info = api_get_user($a);
2275 if (x($_GET,'cursor') && $_GET['cursor']=='undefined'){
2276 /* this is to stop Hotot to load friends multiple times
2277 * I'm not sure if I'm missing return something or
2278 * is a bug in hotot. Workaround, meantime
2282 return array('$users' => $ret);*/
2286 if($qtype == 'friends')
2287 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
2288 if($qtype == 'followers')
2289 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
2291 // friends and followers only for self
2292 if ($user_info['self'] == 0)
2293 $sql_extra = " AND false ";
2295 $r = q("SELECT `nurl` FROM `contact` WHERE `uid` = %d AND `self` = 0 AND `blocked` = 0 AND `pending` = 0 $sql_extra",
2300 foreach($r as $cid){
2301 $user = api_get_user($a, $cid['nurl']);
2302 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2303 unset($user["uid"]);
2304 unset($user["self"]);
2310 return array('$users' => $ret);
2313 function api_statuses_friends(&$a, $type){
2314 $data = api_statuses_f($a,$type,"friends");
2315 if ($data===false) return false;
2316 return api_apply_template("friends", $type, $data);
2318 function api_statuses_followers(&$a, $type){
2319 $data = api_statuses_f($a,$type,"followers");
2320 if ($data===false) return false;
2321 return api_apply_template("friends", $type, $data);
2323 api_register_func('api/statuses/friends','api_statuses_friends',true);
2324 api_register_func('api/statuses/followers','api_statuses_followers',true);
2331 function api_statusnet_config(&$a,$type) {
2332 $name = $a->config['sitename'];
2333 $server = $a->get_hostname();
2334 $logo = $a->get_baseurl() . '/images/friendica-64.png';
2335 $email = $a->config['admin_email'];
2336 $closed = (($a->config['register_policy'] == REGISTER_CLOSED) ? 'true' : 'false');
2337 $private = (($a->config['system']['block_public']) ? 'true' : 'false');
2338 $textlimit = (string) (($a->config['max_import_size']) ? $a->config['max_import_size'] : 200000);
2339 if($a->config['api_import_size'])
2340 $texlimit = string($a->config['api_import_size']);
2341 $ssl = (($a->config['system']['have_ssl']) ? 'true' : 'false');
2342 $sslserver = (($ssl === 'true') ? str_replace('http:','https:',$a->get_baseurl()) : '');
2345 'site' => array('name' => $name,'server' => $server, 'theme' => 'default', 'path' => '',
2346 'logo' => $logo, 'fancy' => true, 'language' => 'en', 'email' => $email, 'broughtby' => '',
2347 'broughtbyurl' => '', 'timezone' => 'UTC', 'closed' => $closed, 'inviteonly' => false,
2348 'private' => $private, 'textlimit' => $textlimit, 'sslserver' => $sslserver, 'ssl' => $ssl,
2349 'shorturllength' => '30',
2350 'friendica' => array(
2351 'FRIENDICA_PLATFORM' => FRIENDICA_PLATFORM,
2352 'FRIENDICA_VERSION' => FRIENDICA_VERSION,
2353 'DFRN_PROTOCOL_VERSION' => DFRN_PROTOCOL_VERSION,
2354 'DB_UPDATE_VERSION' => DB_UPDATE_VERSION
2359 return api_apply_template('config', $type, array('$config' => $config));
2362 api_register_func('api/statusnet/config','api_statusnet_config',false);
2364 function api_statusnet_version(&$a,$type) {
2368 if($type === 'xml') {
2369 header("Content-type: application/xml");
2370 echo '<?xml version="1.0" encoding="UTF-8"?>' . "\r\n" . '<version>0.9.7</version>' . "\r\n";
2373 elseif($type === 'json') {
2374 header("Content-type: application/json");
2379 api_register_func('api/statusnet/version','api_statusnet_version',false);
2382 function api_ff_ids(&$a,$type,$qtype) {
2386 $user_info = api_get_user($a);
2388 if($qtype == 'friends')
2389 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
2390 if($qtype == 'followers')
2391 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
2393 if (!$user_info["self"])
2394 $sql_extra = " AND false ";
2396 $stringify_ids = (x($_REQUEST,'stringify_ids')?$_REQUEST['stringify_ids']:false);
2398 $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",
2404 if($type === 'xml') {
2405 header("Content-type: application/xml");
2406 echo '<?xml version="1.0" encoding="UTF-8"?>' . "\r\n" . '<ids>' . "\r\n";
2408 echo '<id>' . $rr['id'] . '</id>' . "\r\n";
2409 echo '</ids>' . "\r\n";
2412 elseif($type === 'json') {
2414 header("Content-type: application/json");
2419 $ret[] = intval($rr['id']);
2421 echo json_encode($ret);
2427 function api_friends_ids(&$a,$type) {
2428 api_ff_ids($a,$type,'friends');
2430 function api_followers_ids(&$a,$type) {
2431 api_ff_ids($a,$type,'followers');
2433 api_register_func('api/friends/ids','api_friends_ids',true);
2434 api_register_func('api/followers/ids','api_followers_ids',true);
2437 function api_direct_messages_new(&$a, $type) {
2438 if (api_user()===false) return false;
2440 if (!x($_POST, "text") OR (!x($_POST,"screen_name") AND !x($_POST,"user_id"))) return;
2442 $sender = api_get_user($a);
2444 require_once("include/message.php");
2446 if ($_POST['screen_name']) {
2447 $r = q("SELECT `id`, `nurl`, `network` FROM `contact` WHERE `uid`=%d AND `nick`='%s'",
2449 dbesc($_POST['screen_name']));
2451 // Selecting the id by priority, friendica first
2452 api_best_nickname($r);
2454 $recipient = api_get_user($a, $r[0]['nurl']);
2456 $recipient = api_get_user($a, $_POST['user_id']);
2460 if (x($_REQUEST,'replyto')) {
2461 $r = q('SELECT `parent-uri`, `title` FROM `mail` WHERE `uid`=%d AND `id`=%d',
2463 intval($_REQUEST['replyto']));
2464 $replyto = $r[0]['parent-uri'];
2465 $sub = $r[0]['title'];
2468 if (x($_REQUEST,'title')) {
2469 $sub = $_REQUEST['title'];
2472 $sub = ((strlen($_POST['text'])>10)?substr($_POST['text'],0,10)."...":$_POST['text']);
2476 $id = send_message($recipient['cid'], $_POST['text'], $sub, $replyto);
2479 $r = q("SELECT * FROM `mail` WHERE id=%d", intval($id));
2480 $ret = api_format_messages($r[0], $recipient, $sender);
2483 $ret = array("error"=>$id);
2486 $data = Array('$messages'=>$ret);
2491 $data = api_rss_extra($a, $data, $user_info);
2494 return api_apply_template("direct_messages", $type, $data);
2497 api_register_func('api/direct_messages/new','api_direct_messages_new',true);
2499 function api_direct_messages_box(&$a, $type, $box) {
2500 if (api_user()===false) return false;
2504 $count = (x($_GET,'count')?$_GET['count']:20);
2505 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
2506 if ($page<0) $page=0;
2508 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
2509 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
2511 $user_id = (x($_REQUEST,'user_id')?$_REQUEST['user_id']:"");
2512 $screen_name = (x($_REQUEST,'screen_name')?$_REQUEST['screen_name']:"");
2515 unset($_REQUEST["user_id"]);
2516 unset($_GET["user_id"]);
2518 unset($_REQUEST["screen_name"]);
2519 unset($_GET["screen_name"]);
2521 $user_info = api_get_user($a);
2522 //$profile_url = $a->get_baseurl() . '/profile/' . $a->user['nickname'];
2523 $profile_url = $user_info["url"];
2527 $start = $page*$count;
2530 if ($box=="sentbox") {
2531 $sql_extra = "`mail`.`from-url`='".dbesc( $profile_url )."'";
2533 elseif ($box=="conversation") {
2534 $sql_extra = "`mail`.`parent-uri`='".dbesc( $_GET["uri"] ) ."'";
2536 elseif ($box=="all") {
2537 $sql_extra = "true";
2539 elseif ($box=="inbox") {
2540 $sql_extra = "`mail`.`from-url`!='".dbesc( $profile_url )."'";
2544 $sql_extra .= ' AND `mail`.`id` <= '.intval($max_id);
2546 if ($user_id !="") {
2547 $sql_extra .= ' AND `mail`.`contact-id` = ' . intval($user_id);
2549 elseif($screen_name !=""){
2550 $sql_extra .= " AND `contact`.`nick` = '" . dbesc($screen_name). "'";
2553 $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",
2556 intval($start), intval($count)
2561 foreach($r as $item) {
2562 if ($box == "inbox" || $item['from-url'] != $profile_url){
2563 $recipient = $user_info;
2564 $sender = api_get_user($a,normalise_link($item['contact-url']));
2566 elseif ($box == "sentbox" || $item['from-url'] == $profile_url){
2567 $recipient = api_get_user($a,normalise_link($item['contact-url']));
2568 $sender = $user_info;
2571 $ret[]=api_format_messages($item, $recipient, $sender);
2575 $data = array('$messages' => $ret);
2579 $data = api_rss_extra($a, $data, $user_info);
2582 return api_apply_template("direct_messages", $type, $data);
2586 function api_direct_messages_sentbox(&$a, $type){
2587 return api_direct_messages_box($a, $type, "sentbox");
2589 function api_direct_messages_inbox(&$a, $type){
2590 return api_direct_messages_box($a, $type, "inbox");
2592 function api_direct_messages_all(&$a, $type){
2593 return api_direct_messages_box($a, $type, "all");
2595 function api_direct_messages_conversation(&$a, $type){
2596 return api_direct_messages_box($a, $type, "conversation");
2598 api_register_func('api/direct_messages/conversation','api_direct_messages_conversation',true);
2599 api_register_func('api/direct_messages/all','api_direct_messages_all',true);
2600 api_register_func('api/direct_messages/sent','api_direct_messages_sentbox',true);
2601 api_register_func('api/direct_messages','api_direct_messages_inbox',true);
2605 function api_oauth_request_token(&$a, $type){
2607 $oauth = new FKOAuth1();
2608 $r = $oauth->fetch_request_token(OAuthRequest::from_request());
2609 }catch(Exception $e){
2610 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage()); killme();
2615 function api_oauth_access_token(&$a, $type){
2617 $oauth = new FKOAuth1();
2618 $r = $oauth->fetch_access_token(OAuthRequest::from_request());
2619 }catch(Exception $e){
2620 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage()); killme();
2626 api_register_func('api/oauth/request_token', 'api_oauth_request_token', false);
2627 api_register_func('api/oauth/access_token', 'api_oauth_access_token', false);
2630 function api_fr_photos_list(&$a,$type) {
2631 if (api_user()===false) return false;
2632 $r = q("select distinct `resource-id` from photo where uid = %d and album != 'Contact Photos' ",
2633 intval(local_user())
2638 $ret[] = $rr['resource-id'];
2639 header("Content-type: application/json");
2640 echo json_encode($ret);
2645 function api_fr_photo_detail(&$a,$type) {
2646 if (api_user()===false) return false;
2647 if(! $_REQUEST['photo_id']) return false;
2648 $scale = ((array_key_exists('scale',$_REQUEST)) ? intval($_REQUEST['scale']) : 0);
2649 $r = q("select * from photo where uid = %d and `resource-id` = '%s' and scale = %d limit 1",
2650 intval(local_user()),
2651 dbesc($_REQUEST['photo_id']),
2655 header("Content-type: application/json");
2656 $r[0]['data'] = base64_encode($r[0]['data']);
2657 echo json_encode($r[0]);
2663 api_register_func('api/friendica/photos/list', 'api_fr_photos_list', true);
2664 api_register_func('api/friendica/photo', 'api_fr_photo_detail', true);
2668 function api_share_as_retweet(&$item) {
2669 $body = trim($item["body"]);
2671 // Skip if it isn't a pure repeated messages
2672 // Does it start with a share?
2673 if (strpos($body, "[share") > 0)
2676 // Does it end with a share?
2677 if (strlen($body) > (strrpos($body, "[/share]") + 8))
2680 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$1",$body);
2681 // Skip if there is no shared message in there
2682 if ($body == $attributes)
2686 preg_match("/author='(.*?)'/ism", $attributes, $matches);
2687 if ($matches[1] != "")
2688 $author = html_entity_decode($matches[1],ENT_QUOTES,'UTF-8');
2690 preg_match('/author="(.*?)"/ism', $attributes, $matches);
2691 if ($matches[1] != "")
2692 $author = $matches[1];
2695 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
2696 if ($matches[1] != "")
2697 $profile = $matches[1];
2699 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
2700 if ($matches[1] != "")
2701 $profile = $matches[1];
2704 preg_match("/avatar='(.*?)'/ism", $attributes, $matches);
2705 if ($matches[1] != "")
2706 $avatar = $matches[1];
2708 preg_match('/avatar="(.*?)"/ism', $attributes, $matches);
2709 if ($matches[1] != "")
2710 $avatar = $matches[1];
2713 preg_match("/link='(.*?)'/ism", $attributes, $matches);
2714 if ($matches[1] != "")
2715 $link = $matches[1];
2717 preg_match('/link="(.*?)"/ism', $attributes, $matches);
2718 if ($matches[1] != "")
2719 $link = $matches[1];
2721 $shared_body = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$2",$body);
2723 if (($shared_body == "") OR ($profile == "") OR ($author == "") OR ($avatar == ""))
2726 $item["body"] = $shared_body;
2727 $item["author-name"] = $author;
2728 $item["author-link"] = $profile;
2729 $item["author-avatar"] = $avatar;
2730 $item["plink"] = $link;
2736 function api_get_nick($profile) {
2738 - remove trailing jung from profile url
2739 - pump.io check has to check the website
2744 $friendica = preg_replace("=https?://(.*)/profile/(.*)=ism", "$2", $profile);
2745 if ($friendica != $profile)
2749 $diaspora = preg_replace("=https?://(.*)/u/(.*)=ism", "$2", $profile);
2750 if ($diaspora != $profile)
2755 $twitter = preg_replace("=https?://twitter.com/(.*)=ism", "$1", $profile);
2756 if ($twitter != $profile)
2762 $StatusnetHost = preg_replace("=https?://(.*)/user/(.*)=ism", "$1", $profile);
2763 if ($StatusnetHost != $profile) {
2764 $StatusnetUser = preg_replace("=https?://(.*)/user/(.*)=ism", "$2", $profile);
2765 if ($StatusnetUser != $profile) {
2766 $UserData = fetch_url("http://".$StatusnetHost."/api/users/show.json?user_id=".$StatusnetUser);
2767 $user = json_decode($UserData);
2769 $nick = $user->screen_name;
2774 // To-Do: look at the page if its really a pumpio site
2775 //if (!$nick == "") {
2776 // $pumpio = preg_replace("=https?://(.*)/(.*)/=ism", "$2", $profile."/");
2777 // if ($pumpio != $profile)
2779 // <div class="media" id="profile-block" data-profile-id="acct:kabniel@microca.st">
2784 q("UPDATE unique_contacts SET nick = '%s' WHERE url = '%s'",
2785 dbesc($nick), dbesc(normalise_link($profile)));
2792 function api_clean_plain_items($Text) {
2793 $include_entities = strtolower(x($_REQUEST,'include_entities')?$_REQUEST['include_entities']:"false");
2795 $Text = bb_CleanPictureLinks($Text);
2797 $URLSearchString = "^\[\]";
2799 $Text = preg_replace("/([!#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'$1$3',$Text);
2801 if ($include_entities == "true") {
2802 $Text = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'[url=$1]$1[/url]',$Text);
2805 $Text = preg_replace_callback("((.*?)\[class=(.*?)\](.*?)\[\/class\])ism","api_cleanup_share",$Text);
2809 function api_cleanup_share($shared) {
2810 if ($shared[2] != "type-link")
2813 if (!preg_match_all("/\[bookmark\=([^\]]*)\](.*?)\[\/bookmark\]/ism",$shared[3], $bookmark))
2819 if (isset($bookmark[2][0]))
2820 $title = $bookmark[2][0];
2822 if (isset($bookmark[1][0]))
2823 $link = $bookmark[1][0];
2825 if (strpos($shared[1],$title) !== false)
2828 if (strpos($shared[1],$link) !== false)
2831 $text = trim($shared[1]);
2833 //if (strlen($text) < strlen($title))
2834 if (($text == "") AND ($title != ""))
2835 $text .= "\n\n".trim($title);
2838 $text .= "\n".trim($link);
2840 return(trim($text));
2843 function api_best_nickname(&$contacts) {
2844 $best_contact = array();
2846 if (count($contact) == 0)
2849 foreach ($contacts AS $contact)
2850 if ($contact["network"] == "") {
2851 $contact["network"] = "dfrn";
2852 $best_contact = array($contact);
2855 if (sizeof($best_contact) == 0)
2856 foreach ($contacts AS $contact)
2857 if ($contact["network"] == "dfrn")
2858 $best_contact = array($contact);
2860 if (sizeof($best_contact) == 0)
2861 foreach ($contacts AS $contact)
2862 if ($contact["network"] == "dspr")
2863 $best_contact = array($contact);
2865 if (sizeof($best_contact) == 0)
2866 foreach ($contacts AS $contact)
2867 if ($contact["network"] == "stat")
2868 $best_contact = array($contact);
2870 if (sizeof($best_contact) == 0)
2871 foreach ($contacts AS $contact)
2872 if ($contact["network"] == "pump")
2873 $best_contact = array($contact);
2875 if (sizeof($best_contact) == 0)
2876 foreach ($contacts AS $contact)
2877 if ($contact["network"] == "twit")
2878 $best_contact = array($contact);
2880 if (sizeof($best_contact) == 1)
2881 $contacts = $best_contact;
2883 $contacts = array($contacts[0]);
2887 Not implemented by now:
2888 statuses/retweets_of_me
2893 account/update_location
2894 account/update_profile_background_image
2895 account/update_profile_image
2899 Not implemented in status.net:
2900 statuses/retweeted_to_me
2901 statuses/retweeted_by_me
2902 direct_messages/destroy
2904 account/update_delivery_device
2905 notifications/follow