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);
1190 $r = q("UPDATE `item` SET `unseen` = 0 WHERE `unseen` AND `id` IN (%s)", $idlist);
1193 $data = array('$statuses' => $ret);
1197 $data = api_rss_extra($a, $data, $user_info);
1200 $as = api_format_as($a, $ret, $user_info);
1201 $as['title'] = $a->config['sitename']." Home Timeline";
1202 $as['link']['url'] = $a->get_baseurl()."/".$user_info["screen_name"]."/all";
1207 return api_apply_template("timeline", $type, $data);
1209 api_register_func('api/statuses/home_timeline','api_statuses_home_timeline', true);
1210 api_register_func('api/statuses/friends_timeline','api_statuses_home_timeline', true);
1212 function api_statuses_public_timeline(&$a, $type){
1213 if (api_user()===false) return false;
1215 $user_info = api_get_user($a);
1216 // get last newtork messages
1220 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1221 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1222 if ($page<0) $page=0;
1223 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1224 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1225 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1226 $exclude_replies = (x($_REQUEST,'exclude_replies')?1:0);
1227 $conversation_id = (x($_REQUEST,'conversation_id')?$_REQUEST['conversation_id']:0);
1229 $start = $page*$count;
1232 $sql_extra = 'AND `item`.`id` <= '.intval($max_id);
1233 if ($exclude_replies > 0)
1234 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
1235 if ($conversation_id > 0)
1236 $sql_extra .= ' AND `item`.`parent` = '.intval($conversation_id);
1238 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1239 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1240 `contact`.`network`, `contact`.`thumb`, `contact`.`self`, `contact`.`writable`,
1241 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`,
1242 `user`.`nickname`, `user`.`hidewall`
1243 FROM `item` STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
1244 STRAIGHT_JOIN `user` ON `user`.`uid` = `item`.`uid`
1245 WHERE `verb` = '%s' AND `item`.`visible` = 1 AND `item`.`deleted` = 0 and `item`.`moderated` = 0
1246 AND `item`.`allow_cid` = '' AND `item`.`allow_gid` = ''
1247 AND `item`.`deny_cid` = '' AND `item`.`deny_gid` = ''
1248 AND `item`.`private` = 0 AND `item`.`wall` = 1 AND `user`.`hidewall` = 0
1249 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1252 ORDER BY `item`.`id` DESC LIMIT %d, %d ",
1253 dbesc(ACTIVITY_POST),
1258 $ret = api_format_items($r,$user_info);
1261 $data = array('$statuses' => $ret);
1265 $data = api_rss_extra($a, $data, $user_info);
1268 $as = api_format_as($a, $ret, $user_info);
1269 $as['title'] = $a->config['sitename']." Public Timeline";
1270 $as['link']['url'] = $a->get_baseurl()."/";
1275 return api_apply_template("timeline", $type, $data);
1277 api_register_func('api/statuses/public_timeline','api_statuses_public_timeline', true);
1282 function api_statuses_show(&$a, $type){
1283 if (api_user()===false) return false;
1285 $user_info = api_get_user($a);
1288 $id = intval($a->argv[3]);
1291 $id = intval($_REQUEST["id"]);
1295 $id = intval($a->argv[4]);
1297 logger('API: api_statuses_show: '.$id);
1299 $conversation = (x($_REQUEST,'conversation')?1:0);
1303 $sql_extra .= " AND `item`.`parent` = %d ORDER BY `received` ASC ";
1305 $sql_extra .= " AND `item`.`id` = %d";
1307 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1308 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1309 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1310 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1311 FROM `item`, `contact`
1312 WHERE `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1313 AND `contact`.`id` = `item`.`contact-id` AND `item`.`uid` = %d AND `item`.`verb` = '%s'
1314 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1317 dbesc(ACTIVITY_POST),
1322 die(api_error($a, $type, t("There is no status with this id.")));
1324 $ret = api_format_items($r,$user_info);
1326 if ($conversation) {
1327 $data = array('$statuses' => $ret);
1328 return api_apply_template("timeline", $type, $data);
1330 $data = array('$status' => $ret[0]);
1334 $data = api_rss_extra($a, $data, $user_info);
1336 return api_apply_template("status", $type, $data);
1339 api_register_func('api/statuses/show','api_statuses_show', true);
1345 function api_conversation_show(&$a, $type){
1346 if (api_user()===false) return false;
1348 $user_info = api_get_user($a);
1351 $id = intval($a->argv[3]);
1352 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1353 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1354 if ($page<0) $page=0;
1355 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1356 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1358 $start = $page*$count;
1361 $id = intval($_REQUEST["id"]);
1365 $id = intval($a->argv[4]);
1367 logger('API: api_conversation_show: '.$id);
1372 $sql_extra = ' AND `item`.`id` <= '.intval($max_id);
1374 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1375 `contact`.`name`, `contact`.`photo`, `contact`.`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` INNER JOIN (SELECT `uri`,`parent` FROM `item` WHERE `id` = %d) AS `temp1`
1379 ON (`item`.`thr-parent` = `temp1`.`uri` AND `item`.`parent` = `temp1`.`parent`), `contact`
1380 WHERE `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1381 AND `item`.`uid` = %d AND `item`.`verb` = '%s' AND `contact`.`id` = `item`.`contact-id`
1382 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1383 AND `item`.`id`>%d $sql_extra
1384 ORDER BY `item`.`id` DESC LIMIT %d ,%d",
1385 intval($id), intval(api_user()),
1386 dbesc(ACTIVITY_POST),
1388 intval($start), intval($count)
1392 die(api_error($a, $type, t("There is no conversation with this id.")));
1394 $ret = api_format_items($r,$user_info);
1396 $data = array('$statuses' => $ret);
1397 return api_apply_template("timeline", $type, $data);
1399 api_register_func('api/conversation/show','api_conversation_show', true);
1405 function api_statuses_repeat(&$a, $type){
1408 if (api_user()===false) return false;
1410 $user_info = api_get_user($a);
1413 $id = intval($a->argv[3]);
1416 $id = intval($_REQUEST["id"]);
1420 $id = intval($a->argv[4]);
1422 logger('API: api_statuses_repeat: '.$id);
1424 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`, `contact`.`nick` as `reply_author`,
1425 `contact`.`name`, `contact`.`photo` as `reply_photo`, `contact`.`url` as `reply_url`, `contact`.`rel`,
1426 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1427 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1428 FROM `item`, `contact`
1429 WHERE `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1430 AND `contact`.`id` = `item`.`contact-id`
1431 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1433 AND `item`.`id`=%d",
1437 if ($r[0]['body'] != "") {
1438 if (!intval(get_config('system','old_share'))) {
1439 if (strpos($r[0]['body'], "[/share]") !== false) {
1440 $pos = strpos($r[0]['body'], "[share");
1441 $post = substr($r[0]['body'], $pos);
1443 $post = share_header($r[0]['author-name'], $r[0]['author-link'], $r[0]['author-avatar'], $r[0]['guid'], $r[0]['created'], $r[0]['plink']);
1445 $post .= $r[0]['body'];
1446 $post .= "[/share]";
1448 $_REQUEST['body'] = $post;
1450 $_REQUEST['body'] = html_entity_decode("♲ ", ENT_QUOTES, 'UTF-8')."[url=".$r[0]['reply_url']."]".$r[0]['reply_author']."[/url] \n".$r[0]['body'];
1452 $_REQUEST['profile_uid'] = api_user();
1453 $_REQUEST['type'] = 'wall';
1454 $_REQUEST['api_source'] = true;
1456 if (!x($_REQUEST, "source"))
1457 $_REQUEST["source"] = api_source();
1459 require_once('mod/item.php');
1463 // this should output the last post (the one we just posted).
1465 return(api_status_show($a,$type));
1467 api_register_func('api/statuses/retweet','api_statuses_repeat', true);
1472 function api_statuses_destroy(&$a, $type){
1473 if (api_user()===false) return false;
1475 $user_info = api_get_user($a);
1478 $id = intval($a->argv[3]);
1481 $id = intval($_REQUEST["id"]);
1485 $id = intval($a->argv[4]);
1487 logger('API: api_statuses_destroy: '.$id);
1489 $ret = api_statuses_show($a, $type);
1491 require_once('include/items.php');
1492 drop_item($id, false);
1496 api_register_func('api/statuses/destroy','api_statuses_destroy', true);
1500 * http://developer.twitter.com/doc/get/statuses/mentions
1503 function api_statuses_mentions(&$a, $type){
1504 if (api_user()===false) return false;
1506 unset($_REQUEST["user_id"]);
1507 unset($_GET["user_id"]);
1509 unset($_REQUEST["screen_name"]);
1510 unset($_GET["screen_name"]);
1512 $user_info = api_get_user($a);
1513 // get last newtork messages
1517 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1518 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1519 if ($page<0) $page=0;
1520 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1521 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1522 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1524 $start = $page*$count;
1526 // Ugly code - should be changed
1527 $myurl = $a->get_baseurl() . '/profile/'. $a->user['nickname'];
1528 $myurl = substr($myurl,strpos($myurl,'://')+3);
1529 //$myurl = str_replace(array('www.','.'),array('','\\.'),$myurl);
1530 $myurl = str_replace('www.','',$myurl);
1531 $diasp_url = str_replace('/profile/','/u/',$myurl);
1534 $sql_extra = ' AND `item`.`id` <= '.intval($max_id);
1536 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1537 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1538 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1539 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1540 FROM `item`, `contact`
1541 WHERE `item`.`uid` = %d AND `verb` = '%s'
1542 AND NOT (`item`.`author-link` IN ('https://%s', 'http://%s'))
1543 AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1544 AND `contact`.`id` = `item`.`contact-id`
1545 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1546 AND `item`.`parent` IN (SELECT `iid` from thread where uid = %d AND `mention` AND !`ignored`)
1549 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1551 dbesc(ACTIVITY_POST),
1552 dbesc(protect_sprintf($myurl)),
1553 dbesc(protect_sprintf($myurl)),
1556 intval($start), intval($count)
1559 $ret = api_format_items($r,$user_info);
1562 $data = array('$statuses' => $ret);
1566 $data = api_rss_extra($a, $data, $user_info);
1569 $as = api_format_as($a, $ret, $user_info);
1570 $as["title"] = $a->config['sitename']." Mentions";
1571 $as['link']['url'] = $a->get_baseurl()."/";
1576 return api_apply_template("timeline", $type, $data);
1578 api_register_func('api/statuses/mentions','api_statuses_mentions', true);
1579 api_register_func('api/statuses/replies','api_statuses_mentions', true);
1582 function api_statuses_user_timeline(&$a, $type){
1583 if (api_user()===false) return false;
1585 $user_info = api_get_user($a);
1586 // get last network messages
1588 logger("api_statuses_user_timeline: api_user: ". api_user() .
1589 "\nuser_info: ".print_r($user_info, true) .
1590 "\n_REQUEST: ".print_r($_REQUEST, true),
1594 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1595 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1596 if ($page<0) $page=0;
1597 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1598 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1599 $exclude_replies = (x($_REQUEST,'exclude_replies')?1:0);
1600 $conversation_id = (x($_REQUEST,'conversation_id')?$_REQUEST['conversation_id']:0);
1602 $start = $page*$count;
1605 if ($user_info['self']==1)
1606 $sql_extra .= " AND `item`.`wall` = 1 ";
1608 if ($exclude_replies > 0)
1609 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
1610 if ($conversation_id > 0)
1611 $sql_extra .= ' AND `item`.`parent` = '.intval($conversation_id);
1613 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1614 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1615 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1616 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1617 FROM `item`, `contact`
1618 WHERE `item`.`uid` = %d AND `verb` = '%s'
1619 AND `item`.`contact-id` = %d
1620 AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1621 AND `contact`.`id` = `item`.`contact-id`
1622 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1625 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1627 dbesc(ACTIVITY_POST),
1628 intval($user_info['cid']),
1630 intval($start), intval($count)
1633 $ret = api_format_items($r,$user_info, true);
1635 $data = array('$statuses' => $ret);
1639 $data = api_rss_extra($a, $data, $user_info);
1642 return api_apply_template("timeline", $type, $data);
1645 api_register_func('api/statuses/user_timeline','api_statuses_user_timeline', true);
1649 * Star/unstar an item
1650 * param: id : id of the item
1652 * api v1 : https://web.archive.org/web/20131019055350/https://dev.twitter.com/docs/api/1/post/favorites/create/%3Aid
1654 function api_favorites_create_destroy(&$a, $type){
1655 if (api_user()===false) return false;
1657 # for versioned api.
1658 # TODO: we need a better global soluton
1660 if ($a->argv[1]=="1.1") $action_argv_id=3;
1662 if ($a->argc<=$action_argv_id) die(api_error($a, $type, t("Invalid request.")));
1663 $action = str_replace(".".$type,"",$a->argv[$action_argv_id]);
1664 if ($a->argc==$action_argv_id+2) {
1665 $itemid = intval($a->argv[$action_argv_id+1]);
1667 $itemid = intval($_REQUEST['id']);
1670 $item = q("SELECT * FROM item WHERE id=%d AND uid=%d",
1671 $itemid, api_user());
1673 if ($item===false || count($item)==0) die(api_error($a, $type, t("Invalid item.")));
1677 $item[0]['starred']=1;
1680 $item[0]['starred']=0;
1683 die(api_error($a, $type, t("Invalid action. ".$action)));
1685 $r = q("UPDATE item SET starred=%d WHERE id=%d AND uid=%d",
1686 $item[0]['starred'], $itemid, api_user());
1688 q("UPDATE thread SET starred=%d WHERE iid=%d AND uid=%d",
1689 $item[0]['starred'], $itemid, api_user());
1691 if ($r===false) die(api_error($a, $type, t("DB error")));
1694 $user_info = api_get_user($a);
1695 $rets = api_format_items($item,$user_info);
1698 $data = array('$status' => $ret);
1702 $data = api_rss_extra($a, $data, $user_info);
1705 return api_apply_template("status", $type, $data);
1708 api_register_func('api/favorites/create', 'api_favorites_create_destroy', true);
1709 api_register_func('api/favorites/destroy', 'api_favorites_create_destroy', true);
1711 function api_favorites(&$a, $type){
1714 if (api_user()===false) return false;
1716 $called_api= array();
1718 $user_info = api_get_user($a);
1720 // in friendica starred item are private
1721 // return favorites only for self
1722 logger('api_favorites: self:' . $user_info['self']);
1724 if ($user_info['self']==0) {
1730 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1731 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1732 $count = (x($_GET,'count')?$_GET['count']:20);
1733 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1734 if ($page<0) $page=0;
1736 $start = $page*$count;
1739 $sql_extra .= ' AND `item`.`id` <= '.intval($max_id);
1741 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1742 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1743 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1744 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1745 FROM `item`, `contact`
1746 WHERE `item`.`uid` = %d
1747 AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1748 AND `item`.`starred` = 1
1749 AND `contact`.`id` = `item`.`contact-id`
1750 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1753 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1756 intval($start), intval($count)
1759 $ret = api_format_items($r,$user_info);
1763 $data = array('$statuses' => $ret);
1767 $data = api_rss_extra($a, $data, $user_info);
1770 return api_apply_template("timeline", $type, $data);
1773 api_register_func('api/favorites','api_favorites', true);
1778 function api_format_as($a, $ret, $user_info) {
1781 $as['title'] = $a->config['sitename']." Public Timeline";
1783 foreach ($ret as $item) {
1784 $singleitem["actor"]["displayName"] = $item["user"]["name"];
1785 $singleitem["actor"]["id"] = $item["user"]["contact_url"];
1786 $avatar[0]["url"] = $item["user"]["profile_image_url"];
1787 $avatar[0]["rel"] = "avatar";
1788 $avatar[0]["type"] = "";
1789 $avatar[0]["width"] = 96;
1790 $avatar[0]["height"] = 96;
1791 $avatar[1]["url"] = $item["user"]["profile_image_url"];
1792 $avatar[1]["rel"] = "avatar";
1793 $avatar[1]["type"] = "";
1794 $avatar[1]["width"] = 48;
1795 $avatar[1]["height"] = 48;
1796 $avatar[2]["url"] = $item["user"]["profile_image_url"];
1797 $avatar[2]["rel"] = "avatar";
1798 $avatar[2]["type"] = "";
1799 $avatar[2]["width"] = 24;
1800 $avatar[2]["height"] = 24;
1801 $singleitem["actor"]["avatarLinks"] = $avatar;
1803 $singleitem["actor"]["image"]["url"] = $item["user"]["profile_image_url"];
1804 $singleitem["actor"]["image"]["rel"] = "avatar";
1805 $singleitem["actor"]["image"]["type"] = "";
1806 $singleitem["actor"]["image"]["width"] = 96;
1807 $singleitem["actor"]["image"]["height"] = 96;
1808 $singleitem["actor"]["type"] = "person";
1809 $singleitem["actor"]["url"] = $item["person"]["contact_url"];
1810 $singleitem["actor"]["statusnet:profile_info"]["local_id"] = $item["user"]["id"];
1811 $singleitem["actor"]["statusnet:profile_info"]["following"] = $item["user"]["following"] ? "true" : "false";
1812 $singleitem["actor"]["statusnet:profile_info"]["blocking"] = "false";
1813 $singleitem["actor"]["contact"]["preferredUsername"] = $item["user"]["screen_name"];
1814 $singleitem["actor"]["contact"]["displayName"] = $item["user"]["name"];
1815 $singleitem["actor"]["contact"]["addresses"] = "";
1817 $singleitem["body"] = $item["text"];
1818 $singleitem["object"]["displayName"] = $item["text"];
1819 $singleitem["object"]["id"] = $item["url"];
1820 $singleitem["object"]["type"] = "note";
1821 $singleitem["object"]["url"] = $item["url"];
1822 //$singleitem["context"] =;
1823 $singleitem["postedTime"] = date("c", strtotime($item["published"]));
1824 $singleitem["provider"]["objectType"] = "service";
1825 $singleitem["provider"]["displayName"] = "Test";
1826 $singleitem["provider"]["url"] = "http://test.tld";
1827 $singleitem["title"] = $item["text"];
1828 $singleitem["verb"] = "post";
1829 $singleitem["statusnet:notice_info"]["local_id"] = $item["id"];
1830 $singleitem["statusnet:notice_info"]["source"] = $item["source"];
1831 $singleitem["statusnet:notice_info"]["favorite"] = "false";
1832 $singleitem["statusnet:notice_info"]["repeated"] = "false";
1833 //$singleitem["original"] = $item;
1834 $items[] = $singleitem;
1836 $as['items'] = $items;
1837 $as['link']['url'] = $a->get_baseurl()."/".$user_info["screen_name"]."/all";
1838 $as['link']['rel'] = "alternate";
1839 $as['link']['type'] = "text/html";
1843 function api_format_messages($item, $recipient, $sender) {
1844 // standard meta information
1846 'id' => $item['id'],
1847 'sender_id' => $sender['id'] ,
1849 'recipient_id' => $recipient['id'],
1850 'created_at' => api_date($item['created']),
1851 'sender_screen_name' => $sender['screen_name'],
1852 'recipient_screen_name' => $recipient['screen_name'],
1853 'sender' => $sender,
1854 'recipient' => $recipient,
1857 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1858 unset($ret["sender"]["uid"]);
1859 unset($ret["sender"]["self"]);
1860 unset($ret["recipient"]["uid"]);
1861 unset($ret["recipient"]["self"]);
1863 //don't send title to regular StatusNET requests to avoid confusing these apps
1864 if (x($_GET, 'getText')) {
1865 $ret['title'] = $item['title'] ;
1866 if ($_GET["getText"] == "html") {
1867 $ret['text'] = bbcode($item['body'], false, false);
1869 elseif ($_GET["getText"] == "plain") {
1870 //$ret['text'] = html2plain(bbcode($item['body'], false, false, true), 0);
1871 $ret['text'] = trim(html2plain(bbcode(api_clean_plain_items($item['body']), false, false, 2, true), 0));
1875 $ret['text'] = $item['title']."\n".html2plain(bbcode(api_clean_plain_items($item['body']), false, false, 2, true), 0);
1877 if (isset($_GET["getUserObjects"]) && $_GET["getUserObjects"] == "false") {
1878 unset($ret['sender']);
1879 unset($ret['recipient']);
1885 function api_convert_item($item) {
1887 $body = $item['body'];
1888 $attachments = api_get_attachments($body);
1890 // Workaround for ostatus messages where the title is identically to the body
1891 $html = bbcode(api_clean_plain_items($body), false, false, 2, true);
1892 $statusbody = trim(html2plain($html, 0));
1894 // handle data: images
1895 $statusbody = api_format_items_embeded_images($item,$statusbody);
1897 $statustitle = trim($item['title']);
1899 if (($statustitle != '') and (strpos($statusbody, $statustitle) !== false))
1900 $statustext = trim($statusbody);
1902 $statustext = trim($statustitle."\n\n".$statusbody);
1904 if (($item["network"] == NETWORK_FEED) and (strlen($statustext)> 1000))
1905 $statustext = substr($statustext, 0, 1000)."... \n".$item["plink"];
1907 $statushtml = trim(bbcode($body, false, false));
1909 if ($item['title'] != "")
1910 $statushtml = "<h4>".bbcode($item['title'])."</h4>\n".$statushtml;
1912 $entities = api_get_entitities($statustext, $body);
1914 return(array("text" => $statustext, "html" => $statushtml, "attachments" => $attachments, "entities" => $entities));
1917 function api_get_attachments(&$body) {
1920 $text = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $text);
1922 $URLSearchString = "^\[\]";
1923 $ret = preg_match_all("/\[img\]([$URLSearchString]*)\[\/img\]/ism", $text, $images);
1928 $attachments = array();
1930 foreach ($images[1] AS $image) {
1931 $imagedata = get_photo_info($image);
1934 $attachments[] = array("url" => $image, "mimetype" => $imagedata["mime"], "size" => $imagedata["size"]);
1937 if (strstr($_SERVER['HTTP_USER_AGENT'], "AndStatus"))
1938 foreach ($images[0] AS $orig)
1939 $body = str_replace($orig, "", $body);
1941 return $attachments;
1944 function api_get_entitities(&$text, $bbcode) {
1947 * Links at the first character of the post
1952 $include_entities = strtolower(x($_REQUEST,'include_entities')?$_REQUEST['include_entities']:"false");
1954 if ($include_entities != "true") {
1955 require_once("mod/proxy.php");
1957 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
1959 foreach ($images[1] AS $image) {
1960 $replace = proxy_url($image);
1961 $text = str_replace($image, $replace, $text);
1966 $bbcode = bb_CleanPictureLinks($bbcode);
1968 // Change pure links in text to bbcode uris
1969 $bbcode = preg_replace("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", '$1[url=$2]$2[/url]', $bbcode);
1971 $entities = array();
1972 $entities["hashtags"] = array();
1973 $entities["symbols"] = array();
1974 $entities["urls"] = array();
1975 $entities["user_mentions"] = array();
1977 $URLSearchString = "^\[\]";
1979 $bbcode = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'#$2',$bbcode);
1981 $bbcode = preg_replace("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism",'[url=$1]$2[/url]',$bbcode);
1982 //$bbcode = preg_replace("/\[url\](.*?)\[\/url\]/ism",'[url=$1]$1[/url]',$bbcode);
1983 $bbcode = preg_replace("/\[video\](.*?)\[\/video\]/ism",'[url=$1]$1[/url]',$bbcode);
1985 $bbcode = preg_replace("/\[youtube\]([A-Za-z0-9\-_=]+)(.*?)\[\/youtube\]/ism",
1986 '[url=https://www.youtube.com/watch?v=$1]https://www.youtube.com/watch?v=$1[/url]', $bbcode);
1987 $bbcode = preg_replace("/\[youtube\](.*?)\[\/youtube\]/ism",'[url=$1]$1[/url]',$bbcode);
1989 $bbcode = preg_replace("/\[vimeo\]([0-9]+)(.*?)\[\/vimeo\]/ism",
1990 '[url=https://vimeo.com/$1]https://vimeo.com/$1[/url]', $bbcode);
1991 $bbcode = preg_replace("/\[vimeo\](.*?)\[\/vimeo\]/ism",'[url=$1]$1[/url]',$bbcode);
1993 $bbcode = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $bbcode);
1995 //preg_match_all("/\[url\]([$URLSearchString]*)\[\/url\]/ism", $bbcode, $urls1);
1996 preg_match_all("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $bbcode, $urls);
1998 $ordered_urls = array();
1999 foreach ($urls[1] AS $id=>$url) {
2000 //$start = strpos($text, $url, $offset);
2001 $start = iconv_strpos($text, $url, 0, "UTF-8");
2002 if (!($start === false))
2003 $ordered_urls[$start] = array("url" => $url, "title" => $urls[2][$id]);
2006 ksort($ordered_urls);
2009 //foreach ($urls[1] AS $id=>$url) {
2010 foreach ($ordered_urls AS $url) {
2011 if ((substr($url["title"], 0, 7) != "http://") AND (substr($url["title"], 0, 8) != "https://") AND
2012 !strpos($url["title"], "http://") AND !strpos($url["title"], "https://"))
2013 $display_url = $url["title"];
2015 $display_url = str_replace(array("http://www.", "https://www."), array("", ""), $url["url"]);
2016 $display_url = str_replace(array("http://", "https://"), array("", ""), $display_url);
2018 if (strlen($display_url) > 26)
2019 $display_url = substr($display_url, 0, 25)."…";
2022 //$start = strpos($text, $url, $offset);
2023 $start = iconv_strpos($text, $url["url"], $offset, "UTF-8");
2024 if (!($start === false)) {
2025 $entities["urls"][] = array("url" => $url["url"],
2026 "expanded_url" => $url["url"],
2027 "display_url" => $display_url,
2028 "indices" => array($start, $start+strlen($url["url"])));
2029 $offset = $start + 1;
2033 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2034 $ordered_images = array();
2035 foreach ($images[1] AS $image) {
2036 //$start = strpos($text, $url, $offset);
2037 $start = iconv_strpos($text, $image, 0, "UTF-8");
2038 if (!($start === false))
2039 $ordered_images[$start] = $image;
2041 //$entities["media"] = array();
2044 foreach ($ordered_images AS $url) {
2045 $display_url = str_replace(array("http://www.", "https://www."), array("", ""), $url);
2046 $display_url = str_replace(array("http://", "https://"), array("", ""), $display_url);
2048 if (strlen($display_url) > 26)
2049 $display_url = substr($display_url, 0, 25)."…";
2051 $start = iconv_strpos($text, $url, $offset, "UTF-8");
2052 if (!($start === false)) {
2053 $image = get_photo_info($url);
2055 // If image cache is activated, then use the following sizes:
2056 // thumb (150), small (340), medium (600) and large (1024)
2057 if (!get_config("system", "proxy_disabled")) {
2058 require_once("mod/proxy.php");
2059 $media_url = proxy_url($url);
2062 $scale = scale_image($image[0], $image[1], 150);
2063 $sizes["thumb"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2065 if (($image[0] > 150) OR ($image[1] > 150)) {
2066 $scale = scale_image($image[0], $image[1], 340);
2067 $sizes["small"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2070 $scale = scale_image($image[0], $image[1], 600);
2071 $sizes["medium"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2073 if (($image[0] > 600) OR ($image[1] > 600)) {
2074 $scale = scale_image($image[0], $image[1], 1024);
2075 $sizes["large"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2079 $sizes["medium"] = array("w" => $image[0], "h" => $image[1], "resize" => "fit");
2082 $entities["media"][] = array(
2084 "id_str" => (string)$start+1,
2085 "indices" => array($start, $start+strlen($url)),
2086 "media_url" => normalise_link($media_url),
2087 "media_url_https" => $media_url,
2089 "display_url" => $display_url,
2090 "expanded_url" => $url,
2094 $offset = $start + 1;
2100 function api_format_items_embeded_images($item, $text){
2102 $text = preg_replace_callback(
2103 "|data:image/([^;]+)[^=]+=*|m",
2104 function($match) use ($a, $item) {
2105 return $a->get_baseurl()."/display/".$item['guid'];
2111 function api_format_items($r,$user_info, $filter_user = false) {
2116 foreach($r as $item) {
2117 api_share_as_retweet($item);
2119 localize_item($item);
2120 $status_user = api_item_get_user($a,$item);
2122 // Look if the posts are matching if they should be filtered by user id
2123 if ($filter_user AND ($status_user["id"] != $user_info["id"]))
2126 if ($item['thr-parent'] != $item['uri']) {
2127 $r = q("SELECT id FROM item WHERE uid=%d AND uri='%s' LIMIT 1",
2129 dbesc($item['thr-parent']));
2131 $in_reply_to_status_id = intval($r[0]['id']);
2133 $in_reply_to_status_id = intval($item['parent']);
2135 $in_reply_to_status_id_str = (string) intval($item['parent']);
2137 $in_reply_to_screen_name = NULL;
2138 $in_reply_to_user_id = NULL;
2139 $in_reply_to_user_id_str = NULL;
2141 $r = q("SELECT `author-link` FROM item WHERE uid=%d AND id=%d LIMIT 1",
2143 intval($in_reply_to_status_id));
2145 $r = q("SELECT * FROM unique_contacts WHERE `url` = '%s'", dbesc(normalise_link($r[0]['author-link'])));
2148 if ($r[0]['nick'] == "")
2149 $r[0]['nick'] = api_get_nick($r[0]["url"]);
2151 $in_reply_to_screen_name = (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']);
2152 $in_reply_to_user_id = intval($r[0]['id']);
2153 $in_reply_to_user_id_str = (string) intval($r[0]['id']);
2157 $in_reply_to_screen_name = NULL;
2158 $in_reply_to_user_id = NULL;
2159 $in_reply_to_status_id = NULL;
2160 $in_reply_to_user_id_str = NULL;
2161 $in_reply_to_status_id_str = NULL;
2164 $converted = api_convert_item($item);
2167 'text' => $converted["text"],
2168 'truncated' => False,
2169 'created_at'=> api_date($item['created']),
2170 'in_reply_to_status_id' => $in_reply_to_status_id,
2171 'in_reply_to_status_id_str' => $in_reply_to_status_id_str,
2172 'source' => (($item['app']) ? $item['app'] : 'web'),
2173 'id' => intval($item['id']),
2174 'id_str' => (string) intval($item['id']),
2175 'in_reply_to_user_id' => $in_reply_to_user_id,
2176 'in_reply_to_user_id_str' => $in_reply_to_user_id_str,
2177 'in_reply_to_screen_name' => $in_reply_to_screen_name,
2179 'favorited' => $item['starred'] ? true : false,
2180 'user' => $status_user ,
2181 //'entities' => NULL,
2182 'statusnet_html' => $converted["html"],
2183 'statusnet_conversation_id' => $item['parent'],
2186 if (count($converted["attachments"]) > 0)
2187 $status["attachments"] = $converted["attachments"];
2189 if (count($converted["entities"]) > 0)
2190 $status["entities"] = $converted["entities"];
2192 if (($item['item_network'] != "") AND ($status["source"] == 'web'))
2193 $status["source"] = network_to_name($item['item_network']);
2194 else if (($item['item_network'] != "") AND (network_to_name($item['item_network']) != $status["source"]))
2195 $status["source"] = trim($status["source"].' ('.network_to_name($item['item_network']).')');
2198 // Retweets are only valid for top postings
2199 // It doesn't work reliable with the link if its a feed
2200 $IsRetweet = ($item['owner-link'] != $item['author-link']);
2202 $IsRetweet = (($item['owner-name'] != $item['author-name']) OR ($item['owner-avatar'] != $item['author-avatar']));
2204 if ($IsRetweet AND ($item["id"] == $item["parent"])) {
2205 $retweeted_status = $status;
2206 $retweeted_status["user"] = api_get_user($a,$item["author-link"]);
2208 $status["retweeted_status"] = $retweeted_status;
2211 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2212 unset($status["user"]["uid"]);
2213 unset($status["user"]["self"]);
2215 // 'geo' => array('type' => 'Point',
2216 // 'coordinates' => array((float) $notice->lat,
2217 // (float) $notice->lon));
2225 function api_account_rate_limit_status(&$a,$type) {
2228 'reset_time_in_seconds' => strtotime('now + 1 hour'),
2229 'remaining_hits' => (string) 150,
2230 'hourly_limit' => (string) 150,
2231 'reset_time' => api_date(datetime_convert('UTC','UTC','now + 1 hour',ATOM_TIME)),
2234 $hash['resettime_in_seconds'] = $hash['reset_time_in_seconds'];
2236 return api_apply_template('ratelimit', $type, array('$hash' => $hash));
2239 api_register_func('api/account/rate_limit_status','api_account_rate_limit_status',true);
2241 function api_help_test(&$a,$type) {
2248 return api_apply_template('test', $type, array("$ok" => $ok));
2251 api_register_func('api/help/test','api_help_test',false);
2253 function api_lists(&$a,$type) {
2258 api_register_func('api/lists','api_lists',true);
2260 function api_lists_list(&$a,$type) {
2265 api_register_func('api/lists/list','api_lists_list',true);
2268 * https://dev.twitter.com/docs/api/1/get/statuses/friends
2269 * This function is deprecated by Twitter
2270 * returns: json, xml
2272 function api_statuses_f(&$a, $type, $qtype) {
2273 if (api_user()===false) return false;
2274 $user_info = api_get_user($a);
2276 if (x($_GET,'cursor') && $_GET['cursor']=='undefined'){
2277 /* this is to stop Hotot to load friends multiple times
2278 * I'm not sure if I'm missing return something or
2279 * is a bug in hotot. Workaround, meantime
2283 return array('$users' => $ret);*/
2287 if($qtype == 'friends')
2288 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
2289 if($qtype == 'followers')
2290 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
2292 // friends and followers only for self
2293 if ($user_info['self'] == 0)
2294 $sql_extra = " AND false ";
2296 $r = q("SELECT `nurl` FROM `contact` WHERE `uid` = %d AND `self` = 0 AND `blocked` = 0 AND `pending` = 0 $sql_extra",
2301 foreach($r as $cid){
2302 $user = api_get_user($a, $cid['nurl']);
2303 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2304 unset($user["uid"]);
2305 unset($user["self"]);
2311 return array('$users' => $ret);
2314 function api_statuses_friends(&$a, $type){
2315 $data = api_statuses_f($a,$type,"friends");
2316 if ($data===false) return false;
2317 return api_apply_template("friends", $type, $data);
2319 function api_statuses_followers(&$a, $type){
2320 $data = api_statuses_f($a,$type,"followers");
2321 if ($data===false) return false;
2322 return api_apply_template("friends", $type, $data);
2324 api_register_func('api/statuses/friends','api_statuses_friends',true);
2325 api_register_func('api/statuses/followers','api_statuses_followers',true);
2332 function api_statusnet_config(&$a,$type) {
2333 $name = $a->config['sitename'];
2334 $server = $a->get_hostname();
2335 $logo = $a->get_baseurl() . '/images/friendica-64.png';
2336 $email = $a->config['admin_email'];
2337 $closed = (($a->config['register_policy'] == REGISTER_CLOSED) ? 'true' : 'false');
2338 $private = (($a->config['system']['block_public']) ? 'true' : 'false');
2339 $textlimit = (string) (($a->config['max_import_size']) ? $a->config['max_import_size'] : 200000);
2340 if($a->config['api_import_size'])
2341 $texlimit = string($a->config['api_import_size']);
2342 $ssl = (($a->config['system']['have_ssl']) ? 'true' : 'false');
2343 $sslserver = (($ssl === 'true') ? str_replace('http:','https:',$a->get_baseurl()) : '');
2346 'site' => array('name' => $name,'server' => $server, 'theme' => 'default', 'path' => '',
2347 'logo' => $logo, 'fancy' => true, 'language' => 'en', 'email' => $email, 'broughtby' => '',
2348 'broughtbyurl' => '', 'timezone' => 'UTC', 'closed' => $closed, 'inviteonly' => false,
2349 'private' => $private, 'textlimit' => $textlimit, 'sslserver' => $sslserver, 'ssl' => $ssl,
2350 'shorturllength' => '30',
2351 'friendica' => array(
2352 'FRIENDICA_PLATFORM' => FRIENDICA_PLATFORM,
2353 'FRIENDICA_VERSION' => FRIENDICA_VERSION,
2354 'DFRN_PROTOCOL_VERSION' => DFRN_PROTOCOL_VERSION,
2355 'DB_UPDATE_VERSION' => DB_UPDATE_VERSION
2360 return api_apply_template('config', $type, array('$config' => $config));
2363 api_register_func('api/statusnet/config','api_statusnet_config',false);
2365 function api_statusnet_version(&$a,$type) {
2369 if($type === 'xml') {
2370 header("Content-type: application/xml");
2371 echo '<?xml version="1.0" encoding="UTF-8"?>' . "\r\n" . '<version>0.9.7</version>' . "\r\n";
2374 elseif($type === 'json') {
2375 header("Content-type: application/json");
2380 api_register_func('api/statusnet/version','api_statusnet_version',false);
2383 function api_ff_ids(&$a,$type,$qtype) {
2387 $user_info = api_get_user($a);
2389 if($qtype == 'friends')
2390 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
2391 if($qtype == 'followers')
2392 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
2394 if (!$user_info["self"])
2395 $sql_extra = " AND false ";
2397 $stringify_ids = (x($_REQUEST,'stringify_ids')?$_REQUEST['stringify_ids']:false);
2399 $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",
2405 if($type === 'xml') {
2406 header("Content-type: application/xml");
2407 echo '<?xml version="1.0" encoding="UTF-8"?>' . "\r\n" . '<ids>' . "\r\n";
2409 echo '<id>' . $rr['id'] . '</id>' . "\r\n";
2410 echo '</ids>' . "\r\n";
2413 elseif($type === 'json') {
2415 header("Content-type: application/json");
2420 $ret[] = intval($rr['id']);
2422 echo json_encode($ret);
2428 function api_friends_ids(&$a,$type) {
2429 api_ff_ids($a,$type,'friends');
2431 function api_followers_ids(&$a,$type) {
2432 api_ff_ids($a,$type,'followers');
2434 api_register_func('api/friends/ids','api_friends_ids',true);
2435 api_register_func('api/followers/ids','api_followers_ids',true);
2438 function api_direct_messages_new(&$a, $type) {
2439 if (api_user()===false) return false;
2441 if (!x($_POST, "text") OR (!x($_POST,"screen_name") AND !x($_POST,"user_id"))) return;
2443 $sender = api_get_user($a);
2445 require_once("include/message.php");
2447 if ($_POST['screen_name']) {
2448 $r = q("SELECT `id`, `nurl`, `network` FROM `contact` WHERE `uid`=%d AND `nick`='%s'",
2450 dbesc($_POST['screen_name']));
2452 // Selecting the id by priority, friendica first
2453 api_best_nickname($r);
2455 $recipient = api_get_user($a, $r[0]['nurl']);
2457 $recipient = api_get_user($a, $_POST['user_id']);
2461 if (x($_REQUEST,'replyto')) {
2462 $r = q('SELECT `parent-uri`, `title` FROM `mail` WHERE `uid`=%d AND `id`=%d',
2464 intval($_REQUEST['replyto']));
2465 $replyto = $r[0]['parent-uri'];
2466 $sub = $r[0]['title'];
2469 if (x($_REQUEST,'title')) {
2470 $sub = $_REQUEST['title'];
2473 $sub = ((strlen($_POST['text'])>10)?substr($_POST['text'],0,10)."...":$_POST['text']);
2477 $id = send_message($recipient['cid'], $_POST['text'], $sub, $replyto);
2480 $r = q("SELECT * FROM `mail` WHERE id=%d", intval($id));
2481 $ret = api_format_messages($r[0], $recipient, $sender);
2484 $ret = array("error"=>$id);
2487 $data = Array('$messages'=>$ret);
2492 $data = api_rss_extra($a, $data, $user_info);
2495 return api_apply_template("direct_messages", $type, $data);
2498 api_register_func('api/direct_messages/new','api_direct_messages_new',true);
2500 function api_direct_messages_box(&$a, $type, $box) {
2501 if (api_user()===false) return false;
2505 $count = (x($_GET,'count')?$_GET['count']:20);
2506 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
2507 if ($page<0) $page=0;
2509 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
2510 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
2512 $user_id = (x($_REQUEST,'user_id')?$_REQUEST['user_id']:"");
2513 $screen_name = (x($_REQUEST,'screen_name')?$_REQUEST['screen_name']:"");
2516 unset($_REQUEST["user_id"]);
2517 unset($_GET["user_id"]);
2519 unset($_REQUEST["screen_name"]);
2520 unset($_GET["screen_name"]);
2522 $user_info = api_get_user($a);
2523 //$profile_url = $a->get_baseurl() . '/profile/' . $a->user['nickname'];
2524 $profile_url = $user_info["url"];
2528 $start = $page*$count;
2531 if ($box=="sentbox") {
2532 $sql_extra = "`mail`.`from-url`='".dbesc( $profile_url )."'";
2534 elseif ($box=="conversation") {
2535 $sql_extra = "`mail`.`parent-uri`='".dbesc( $_GET["uri"] ) ."'";
2537 elseif ($box=="all") {
2538 $sql_extra = "true";
2540 elseif ($box=="inbox") {
2541 $sql_extra = "`mail`.`from-url`!='".dbesc( $profile_url )."'";
2545 $sql_extra .= ' AND `mail`.`id` <= '.intval($max_id);
2547 if ($user_id !="") {
2548 $sql_extra .= ' AND `mail`.`contact-id` = ' . intval($user_id);
2550 elseif($screen_name !=""){
2551 $sql_extra .= " AND `contact`.`nick` = '" . dbesc($screen_name). "'";
2554 $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",
2557 intval($start), intval($count)
2562 foreach($r as $item) {
2563 if ($box == "inbox" || $item['from-url'] != $profile_url){
2564 $recipient = $user_info;
2565 $sender = api_get_user($a,normalise_link($item['contact-url']));
2567 elseif ($box == "sentbox" || $item['from-url'] == $profile_url){
2568 $recipient = api_get_user($a,normalise_link($item['contact-url']));
2569 $sender = $user_info;
2572 $ret[]=api_format_messages($item, $recipient, $sender);
2576 $data = array('$messages' => $ret);
2580 $data = api_rss_extra($a, $data, $user_info);
2583 return api_apply_template("direct_messages", $type, $data);
2587 function api_direct_messages_sentbox(&$a, $type){
2588 return api_direct_messages_box($a, $type, "sentbox");
2590 function api_direct_messages_inbox(&$a, $type){
2591 return api_direct_messages_box($a, $type, "inbox");
2593 function api_direct_messages_all(&$a, $type){
2594 return api_direct_messages_box($a, $type, "all");
2596 function api_direct_messages_conversation(&$a, $type){
2597 return api_direct_messages_box($a, $type, "conversation");
2599 api_register_func('api/direct_messages/conversation','api_direct_messages_conversation',true);
2600 api_register_func('api/direct_messages/all','api_direct_messages_all',true);
2601 api_register_func('api/direct_messages/sent','api_direct_messages_sentbox',true);
2602 api_register_func('api/direct_messages','api_direct_messages_inbox',true);
2606 function api_oauth_request_token(&$a, $type){
2608 $oauth = new FKOAuth1();
2609 $r = $oauth->fetch_request_token(OAuthRequest::from_request());
2610 }catch(Exception $e){
2611 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage()); killme();
2616 function api_oauth_access_token(&$a, $type){
2618 $oauth = new FKOAuth1();
2619 $r = $oauth->fetch_access_token(OAuthRequest::from_request());
2620 }catch(Exception $e){
2621 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage()); killme();
2627 api_register_func('api/oauth/request_token', 'api_oauth_request_token', false);
2628 api_register_func('api/oauth/access_token', 'api_oauth_access_token', false);
2631 function api_fr_photos_list(&$a,$type) {
2632 if (api_user()===false) return false;
2633 $r = q("select distinct `resource-id` from photo where uid = %d and album != 'Contact Photos' ",
2634 intval(local_user())
2639 $ret[] = $rr['resource-id'];
2640 header("Content-type: application/json");
2641 echo json_encode($ret);
2646 function api_fr_photo_detail(&$a,$type) {
2647 if (api_user()===false) return false;
2648 if(! $_REQUEST['photo_id']) return false;
2649 $scale = ((array_key_exists('scale',$_REQUEST)) ? intval($_REQUEST['scale']) : 0);
2650 $r = q("select * from photo where uid = %d and `resource-id` = '%s' and scale = %d limit 1",
2651 intval(local_user()),
2652 dbesc($_REQUEST['photo_id']),
2656 header("Content-type: application/json");
2657 $r[0]['data'] = base64_encode($r[0]['data']);
2658 echo json_encode($r[0]);
2664 api_register_func('api/friendica/photos/list', 'api_fr_photos_list', true);
2665 api_register_func('api/friendica/photo', 'api_fr_photo_detail', true);
2669 function api_share_as_retweet(&$item) {
2670 $body = trim($item["body"]);
2672 // Skip if it isn't a pure repeated messages
2673 // Does it start with a share?
2674 if (strpos($body, "[share") > 0)
2677 // Does it end with a share?
2678 if (strlen($body) > (strrpos($body, "[/share]") + 8))
2681 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$1",$body);
2682 // Skip if there is no shared message in there
2683 if ($body == $attributes)
2687 preg_match("/author='(.*?)'/ism", $attributes, $matches);
2688 if ($matches[1] != "")
2689 $author = html_entity_decode($matches[1],ENT_QUOTES,'UTF-8');
2691 preg_match('/author="(.*?)"/ism', $attributes, $matches);
2692 if ($matches[1] != "")
2693 $author = $matches[1];
2696 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
2697 if ($matches[1] != "")
2698 $profile = $matches[1];
2700 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
2701 if ($matches[1] != "")
2702 $profile = $matches[1];
2705 preg_match("/avatar='(.*?)'/ism", $attributes, $matches);
2706 if ($matches[1] != "")
2707 $avatar = $matches[1];
2709 preg_match('/avatar="(.*?)"/ism', $attributes, $matches);
2710 if ($matches[1] != "")
2711 $avatar = $matches[1];
2714 preg_match("/link='(.*?)'/ism", $attributes, $matches);
2715 if ($matches[1] != "")
2716 $link = $matches[1];
2718 preg_match('/link="(.*?)"/ism', $attributes, $matches);
2719 if ($matches[1] != "")
2720 $link = $matches[1];
2722 $shared_body = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$2",$body);
2724 if (($shared_body == "") OR ($profile == "") OR ($author == "") OR ($avatar == ""))
2727 $item["body"] = $shared_body;
2728 $item["author-name"] = $author;
2729 $item["author-link"] = $profile;
2730 $item["author-avatar"] = $avatar;
2731 $item["plink"] = $link;
2737 function api_get_nick($profile) {
2739 - remove trailing jung from profile url
2740 - pump.io check has to check the website
2745 $friendica = preg_replace("=https?://(.*)/profile/(.*)=ism", "$2", $profile);
2746 if ($friendica != $profile)
2750 $diaspora = preg_replace("=https?://(.*)/u/(.*)=ism", "$2", $profile);
2751 if ($diaspora != $profile)
2756 $twitter = preg_replace("=https?://twitter.com/(.*)=ism", "$1", $profile);
2757 if ($twitter != $profile)
2763 $StatusnetHost = preg_replace("=https?://(.*)/user/(.*)=ism", "$1", $profile);
2764 if ($StatusnetHost != $profile) {
2765 $StatusnetUser = preg_replace("=https?://(.*)/user/(.*)=ism", "$2", $profile);
2766 if ($StatusnetUser != $profile) {
2767 $UserData = fetch_url("http://".$StatusnetHost."/api/users/show.json?user_id=".$StatusnetUser);
2768 $user = json_decode($UserData);
2770 $nick = $user->screen_name;
2775 // To-Do: look at the page if its really a pumpio site
2776 //if (!$nick == "") {
2777 // $pumpio = preg_replace("=https?://(.*)/(.*)/=ism", "$2", $profile."/");
2778 // if ($pumpio != $profile)
2780 // <div class="media" id="profile-block" data-profile-id="acct:kabniel@microca.st">
2785 q("UPDATE unique_contacts SET nick = '%s' WHERE url = '%s'",
2786 dbesc($nick), dbesc(normalise_link($profile)));
2793 function api_clean_plain_items($Text) {
2794 $include_entities = strtolower(x($_REQUEST,'include_entities')?$_REQUEST['include_entities']:"false");
2796 $Text = bb_CleanPictureLinks($Text);
2798 $URLSearchString = "^\[\]";
2800 $Text = preg_replace("/([!#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'$1$3',$Text);
2802 if ($include_entities == "true") {
2803 $Text = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'[url=$1]$1[/url]',$Text);
2806 $Text = preg_replace_callback("((.*?)\[class=(.*?)\](.*?)\[\/class\])ism","api_cleanup_share",$Text);
2810 function api_cleanup_share($shared) {
2811 if ($shared[2] != "type-link")
2814 if (!preg_match_all("/\[bookmark\=([^\]]*)\](.*?)\[\/bookmark\]/ism",$shared[3], $bookmark))
2820 if (isset($bookmark[2][0]))
2821 $title = $bookmark[2][0];
2823 if (isset($bookmark[1][0]))
2824 $link = $bookmark[1][0];
2826 if (strpos($shared[1],$title) !== false)
2829 if (strpos($shared[1],$link) !== false)
2832 $text = trim($shared[1]);
2834 //if (strlen($text) < strlen($title))
2835 if (($text == "") AND ($title != ""))
2836 $text .= "\n\n".trim($title);
2839 $text .= "\n".trim($link);
2841 return(trim($text));
2844 function api_best_nickname(&$contacts) {
2845 $best_contact = array();
2847 if (count($contact) == 0)
2850 foreach ($contacts AS $contact)
2851 if ($contact["network"] == "") {
2852 $contact["network"] = "dfrn";
2853 $best_contact = array($contact);
2856 if (sizeof($best_contact) == 0)
2857 foreach ($contacts AS $contact)
2858 if ($contact["network"] == "dfrn")
2859 $best_contact = array($contact);
2861 if (sizeof($best_contact) == 0)
2862 foreach ($contacts AS $contact)
2863 if ($contact["network"] == "dspr")
2864 $best_contact = array($contact);
2866 if (sizeof($best_contact) == 0)
2867 foreach ($contacts AS $contact)
2868 if ($contact["network"] == "stat")
2869 $best_contact = array($contact);
2871 if (sizeof($best_contact) == 0)
2872 foreach ($contacts AS $contact)
2873 if ($contact["network"] == "pump")
2874 $best_contact = array($contact);
2876 if (sizeof($best_contact) == 0)
2877 foreach ($contacts AS $contact)
2878 if ($contact["network"] == "twit")
2879 $best_contact = array($contact);
2881 if (sizeof($best_contact) == 1)
2882 $contacts = $best_contact;
2884 $contacts = array($contacts[0]);
2888 Not implemented by now:
2889 statuses/retweets_of_me
2894 account/update_location
2895 account/update_profile_background_image
2896 account/update_profile_image
2900 Not implemented in status.net:
2901 statuses/retweeted_to_me
2902 statuses/retweeted_by_me
2903 direct_messages/destroy
2905 account/update_delivery_device
2906 notifications/follow