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));
105 // allow "user@server" login (but ignore 'server' part)
106 $at=strstr($user, "@", true);
107 if ( $at ) $user=$at;
110 * next code from mod/auth.php. needs better solution
115 'username' => trim($user),
116 'password' => trim($password),
117 'authenticated' => 0,
118 'user_record' => null
123 * A plugin indicates successful login by setting 'authenticated' to non-zero value and returning a user record
124 * Plugins should never set 'authenticated' except to indicate success - as hooks may be chained
125 * and later plugins should not interfere with an earlier one that succeeded.
129 call_hooks('authenticate', $addon_auth);
131 if(($addon_auth['authenticated']) && (count($addon_auth['user_record']))) {
132 $record = $addon_auth['user_record'];
135 // process normal login request
137 $r = q("SELECT * FROM `user` WHERE ( `email` = '%s' OR `nickname` = '%s' )
138 AND `password` = '%s' AND `blocked` = 0 AND `account_expired` = 0 AND `account_removed` = 0 AND `verified` = 1 LIMIT 1",
147 if((! $record) || (! count($record))) {
148 logger('API_login failure: ' . print_r($_SERVER,true), LOGGER_DEBUG);
149 header('WWW-Authenticate: Basic realm="Friendica"');
150 header('HTTP/1.0 401 Unauthorized');
151 die('This api requires login');
154 require_once('include/security.php');
155 authenticate_success($record); $_SESSION["allow_api"] = true;
157 call_hooks('logged_in', $a->user);
161 /**************************
162 * MAIN API ENTRY POINT *
163 **************************/
164 function api_call(&$a){
165 GLOBAL $API, $called_api;
169 foreach ($API as $p=>$info){
170 if (strpos($a->query_string, $p)===0){
171 $called_api= explode("/",$p);
172 //unset($_SERVER['PHP_AUTH_USER']);
173 if ($info['auth']===true && api_user()===false) {
177 load_contact_links(api_user());
179 logger('API call for ' . $a->user['username'] . ': ' . $a->query_string);
180 logger('API parameters: ' . print_r($_REQUEST,true));
182 if (strpos($a->query_string, ".xml")>0) $type="xml";
183 if (strpos($a->query_string, ".json")>0) $type="json";
184 if (strpos($a->query_string, ".rss")>0) $type="rss";
185 if (strpos($a->query_string, ".atom")>0) $type="atom";
186 if (strpos($a->query_string, ".as")>0) $type="as";
188 $r = call_user_func($info['func'], $a, $type);
189 if ($r===false) return;
193 $r = mb_convert_encoding($r, "UTF-8",mb_detect_encoding($r));
194 header ("Content-Type: text/xml");
195 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
198 header ("Content-Type: application/json");
200 $json = json_encode($rr);
201 if ($_GET['callback'])
202 $json = $_GET['callback']."(".$json.")";
206 header ("Content-Type: application/rss+xml");
207 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
210 header ("Content-Type: application/atom+xml");
211 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
214 //header ("Content-Type: application/json");
216 // return json_encode($rr);
217 return json_encode($r);
221 //echo "<pre>"; var_dump($r); die();
224 header("HTTP/1.1 404 Not Found");
225 logger('API call not implemented: '.$a->query_string." - ".print_r($_REQUEST,true));
226 return(api_error($a, $type, "not implemented"));
230 function api_error(&$a, $type, $error) {
231 # TODO: https://dev.twitter.com/overview/api/response-codes
232 $r = "<status><error>".$error."</error><request>".$a->query_string."</request></status>";
235 header ("Content-Type: text/xml");
236 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
239 header ("Content-Type: application/json");
240 return json_encode(array('error' => $error, 'request' => $a->query_string));
243 header ("Content-Type: application/rss+xml");
244 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
247 header ("Content-Type: application/atom+xml");
248 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
256 function api_rss_extra(&$a, $arr, $user_info){
257 if (is_null($user_info)) $user_info = api_get_user($a);
258 $arr['$user'] = $user_info;
259 $arr['$rss'] = array(
260 'alternate' => $user_info['url'],
261 'self' => $a->get_baseurl(). "/". $a->query_string,
262 'base' => $a->get_baseurl(),
263 'updated' => api_date(null),
264 'atom_updated' => datetime_convert('UTC','UTC','now',ATOM_TIME),
265 'language' => $user_info['language'],
266 'logo' => $a->get_baseurl()."/images/friendica-32.png",
274 * Unique contact to contact url.
276 function api_unique_id_to_url($id){
277 $r = q("SELECT url FROM unique_contacts WHERE id=%d LIMIT 1",
280 return ($r[0]["url"]);
286 * Returns user info array.
288 function api_get_user(&$a, $contact_id = Null, $type = "json"){
295 logger("api_get_user: Fetching user data for user ".$contact_id, LOGGER_DEBUG);
297 // Searching for contact URL
298 if(!is_null($contact_id) AND (intval($contact_id) == 0)){
299 $user = dbesc(normalise_link($contact_id));
301 $extra_query = "AND `contact`.`nurl` = '%s' ";
302 if (api_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(api_user());
305 // Searching for unique contact id
306 if(!is_null($contact_id) AND (intval($contact_id) != 0)){
307 $user = dbesc(api_unique_id_to_url($contact_id));
310 die(api_error($a, $type, t("User not found.")));
313 $extra_query = "AND `contact`.`nurl` = '%s' ";
314 if (api_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(api_user());
317 if(is_null($user) && x($_GET, 'user_id')) {
318 $user = dbesc(api_unique_id_to_url($_GET['user_id']));
321 die(api_error($a, $type, t("User not found.")));
324 $extra_query = "AND `contact`.`nurl` = '%s' ";
325 if (api_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(api_user());
327 if(is_null($user) && x($_GET, 'screen_name')) {
328 $user = dbesc($_GET['screen_name']);
330 $extra_query = "AND `contact`.`nick` = '%s' ";
331 if (api_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(api_user());
334 if (is_null($user) AND ($a->argc > (count($called_api)-1)) AND (count($called_api) > 0)){
335 $argid = count($called_api);
336 list($user, $null) = explode(".",$a->argv[$argid]);
337 if(is_numeric($user)){
338 $user = dbesc(api_unique_id_to_url($user));
344 $extra_query = "AND `contact`.`nurl` = '%s' ";
345 if (api_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(api_user());
347 $user = dbesc($user);
349 $extra_query = "AND `contact`.`nick` = '%s' ";
350 if (api_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(api_user());
354 logger("api_get_user: user ".$user, LOGGER_DEBUG);
357 if (api_user()===false) {
358 api_login($a); return False;
360 $user = $_SESSION['uid'];
361 $extra_query = "AND `contact`.`uid` = %d AND `contact`.`self` = 1 ";
366 logger('api_user: ' . $extra_query . ', user: ' . $user);
368 $uinfo = q("SELECT *, `contact`.`id` as `cid` FROM `contact`
374 // Selecting the id by priority, friendica first
375 api_best_nickname($uinfo);
377 // if the contact wasn't found, fetch it from the unique contacts
378 if (count($uinfo)==0) {
382 $r = q("SELECT * FROM unique_contacts WHERE url='%s' LIMIT 1", $url);
384 $r = q("SELECT * FROM unique_contacts WHERE nick='%s' LIMIT 1", $nick);
387 // If no nick where given, extract it from the address
388 if (($r[0]['nick'] == "") OR ($r[0]['name'] == $r[0]['nick']))
389 $r[0]['nick'] = api_get_nick($r[0]["url"]);
393 'id_str' => (string) $r[0]["id"],
394 'name' => $r[0]["name"],
395 'screen_name' => (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']),
397 'description' => NULL,
398 'profile_image_url' => $r[0]["avatar"],
399 'profile_image_url_https' => $r[0]["avatar"],
400 'url' => $r[0]["url"],
401 'protected' => false,
402 'followers_count' => 0,
403 'friends_count' => 0,
404 'created_at' => api_date(0),
405 'favourites_count' => 0,
407 'time_zone' => 'UTC',
408 'statuses_count' => 0,
409 'following' => false,
411 'statusnet_blocking' => false,
412 'notifications' => false,
413 'statusnet_profile_url' => $r[0]["url"],
422 die(api_error($a, $type, t("User not found.")));
426 if($uinfo[0]['self']) {
427 $usr = q("select * from user where uid = %d limit 1",
430 $profile = q("select * from profile where uid = %d and `is-default` = 1 limit 1",
434 //AND `allow_cid`='' AND `allow_gid`='' AND `deny_cid`='' AND `deny_gid`=''",
435 // count public wall messages
436 $r = q("SELECT count(*) as `count` FROM `item`
439 intval($uinfo[0]['uid'])
441 $countitms = $r[0]['count'];
444 //AND `allow_cid`='' AND `allow_gid`='' AND `deny_cid`='' AND `deny_gid`=''",
445 $r = q("SELECT count(*) as `count` FROM `item`
446 WHERE `contact-id` = %d",
447 intval($uinfo[0]['id'])
449 $countitms = $r[0]['count'];
453 $r = q("SELECT count(*) as `count` FROM `contact`
454 WHERE `uid` = %d AND `rel` IN ( %d, %d )
455 AND `self`=0 AND `blocked`=0 AND `pending`=0 AND `hidden`=0",
456 intval($uinfo[0]['uid']),
457 intval(CONTACT_IS_SHARING),
458 intval(CONTACT_IS_FRIEND)
460 $countfriends = $r[0]['count'];
462 $r = q("SELECT count(*) as `count` FROM `contact`
463 WHERE `uid` = %d AND `rel` IN ( %d, %d )
464 AND `self`=0 AND `blocked`=0 AND `pending`=0 AND `hidden`=0",
465 intval($uinfo[0]['uid']),
466 intval(CONTACT_IS_FOLLOWER),
467 intval(CONTACT_IS_FRIEND)
469 $countfollowers = $r[0]['count'];
471 $r = q("SELECT count(*) as `count` FROM item where starred = 1 and uid = %d and deleted = 0",
472 intval($uinfo[0]['uid'])
474 $starred = $r[0]['count'];
477 if(! $uinfo[0]['self']) {
483 // Add a nick if it isn't present there
484 if (($uinfo[0]['nick'] == "") OR ($uinfo[0]['name'] == $uinfo[0]['nick'])) {
485 $uinfo[0]['nick'] = api_get_nick($uinfo[0]["url"]);
488 // Fetching unique id
489 $r = q("SELECT id FROM unique_contacts WHERE url='%s' LIMIT 1", dbesc(normalise_link($uinfo[0]['url'])));
491 // If not there, then add it
492 if (count($r) == 0) {
493 q("INSERT INTO unique_contacts (url, name, nick, avatar) VALUES ('%s', '%s', '%s', '%s')",
494 dbesc(normalise_link($uinfo[0]['url'])), dbesc($uinfo[0]['name']),dbesc($uinfo[0]['nick']), dbesc($uinfo[0]['micro']));
496 $r = q("SELECT id FROM unique_contacts WHERE url='%s' LIMIT 1", dbesc(normalise_link($uinfo[0]['url'])));
499 require_once('include/contact_selectors.php');
500 $network_name = network_to_name($uinfo[0]['network']);
503 'id' => intval($r[0]['id']),
504 'id_str' => (string) intval($r[0]['id']),
505 'name' => (($uinfo[0]['name']) ? $uinfo[0]['name'] : $uinfo[0]['nick']),
506 'screen_name' => (($uinfo[0]['nick']) ? $uinfo[0]['nick'] : $uinfo[0]['name']),
507 'location' => ($usr) ? $usr[0]['default-location'] : $network_name,
508 'description' => (($profile) ? $profile[0]['pdesc'] : NULL),
509 'profile_image_url' => $uinfo[0]['micro'],
510 'profile_image_url_https' => $uinfo[0]['micro'],
511 'url' => $uinfo[0]['url'],
512 'protected' => false,
513 'followers_count' => intval($countfollowers),
514 'friends_count' => intval($countfriends),
515 'created_at' => api_date($uinfo[0]['created']),
516 'favourites_count' => intval($starred),
518 'time_zone' => 'UTC',
519 'statuses_count' => intval($countitms),
520 'following' => (($uinfo[0]['rel'] == CONTACT_IS_FOLLOWER) OR ($uinfo[0]['rel'] == CONTACT_IS_FRIEND)),
522 'statusnet_blocking' => false,
523 'notifications' => false,
524 'statusnet_profile_url' => $a->get_baseurl()."/contacts/".$uinfo[0]['cid'],
525 'uid' => intval($uinfo[0]['uid']),
526 'cid' => intval($uinfo[0]['cid']),
527 'self' => $uinfo[0]['self'],
528 'network' => $uinfo[0]['network'],
535 function api_item_get_user(&$a, $item) {
537 $author = q("SELECT * FROM unique_contacts WHERE url='%s' LIMIT 1",
538 dbesc(normalise_link($item['author-link'])));
540 if (count($author) == 0) {
541 q("INSERT INTO unique_contacts (url, name, avatar) VALUES ('%s', '%s', '%s')",
542 dbesc(normalise_link($item["author-link"])), dbesc($item["author-name"]), dbesc($item["author-avatar"]));
544 $author = q("SELECT id FROM unique_contacts WHERE url='%s' LIMIT 1",
545 dbesc(normalise_link($item['author-link'])));
546 } else if ($item["author-link"].$item["author-name"] != $author[0]["url"].$author[0]["name"]) {
547 q("UPDATE unique_contacts SET name = '%s', avatar = '%s' WHERE url = '%s'",
548 dbesc($item["author-name"]), dbesc($item["author-avatar"]), dbesc(normalise_link($item["author-link"])));
551 $owner = q("SELECT id FROM unique_contacts WHERE url='%s' LIMIT 1",
552 dbesc(normalise_link($item['owner-link'])));
554 if (count($owner) == 0) {
555 q("INSERT INTO unique_contacts (url, name, avatar) VALUES ('%s', '%s', '%s')",
556 dbesc(normalise_link($item["owner-link"])), dbesc($item["owner-name"]), dbesc($item["owner-avatar"]));
558 $owner = q("SELECT id FROM unique_contacts WHERE url='%s' LIMIT 1",
559 dbesc(normalise_link($item['owner-link'])));
560 } else if ($item["owner-link"].$item["owner-name"] != $owner[0]["url"].$owner[0]["name"]) {
561 q("UPDATE unique_contacts SET name = '%s', avatar = '%s' WHERE url = '%s'",
562 dbesc($item["owner-name"]), dbesc($item["owner-avatar"]), dbesc(normalise_link($item["owner-link"])));
565 // Comments in threads may appear as wall-to-wall postings.
566 // So only take the owner at the top posting.
567 if ($item["id"] == $item["parent"])
568 $status_user = api_get_user($a,$item["owner-link"]);
570 $status_user = api_get_user($a,$item["author-link"]);
572 $status_user["protected"] = (($item["allow_cid"] != "") OR
573 ($item["allow_gid"] != "") OR
574 ($item["deny_cid"] != "") OR
575 ($item["deny_gid"] != "") OR
578 return ($status_user);
583 * load api $templatename for $type and replace $data array
585 function api_apply_template($templatename, $type, $data){
593 $data = array_xmlify($data);
594 $tpl = get_markup_template("api_".$templatename."_".$type.".tpl");
596 header ("Content-Type: text/xml");
597 echo '<?xml version="1.0" encoding="UTF-8"?>'."\n".'<status><error>not implemented</error></status>';
600 $ret = replace_macros($tpl, $data);
615 * Returns an HTTP 200 OK response code and a representation of the requesting user if authentication was successful;
616 * returns a 401 status code and an error message if not.
617 * http://developer.twitter.com/doc/get/account/verify_credentials
619 function api_account_verify_credentials(&$a, $type){
620 if (api_user()===false) return false;
622 unset($_REQUEST["user_id"]);
623 unset($_GET["user_id"]);
625 unset($_REQUEST["screen_name"]);
626 unset($_GET["screen_name"]);
628 $skip_status = (x($_REQUEST,'skip_status')?$_REQUEST['skip_status']:false);
630 $user_info = api_get_user($a);
632 // "verified" isn't used here in the standard
633 unset($user_info["verified"]);
635 // - Adding last status
637 $user_info["status"] = api_status_show($a,"raw");
638 if (!count($user_info["status"]))
639 unset($user_info["status"]);
641 unset($user_info["status"]["user"]);
644 // "uid" and "self" are only needed for some internal stuff, so remove it from here
645 unset($user_info["uid"]);
646 unset($user_info["self"]);
648 return api_apply_template("user", $type, array('$user' => $user_info));
651 api_register_func('api/account/verify_credentials','api_account_verify_credentials', true);
655 * get data from $_POST or $_GET
657 function requestdata($k){
658 if (isset($_POST[$k])){
661 if (isset($_GET[$k])){
667 /*Waitman Gobble Mod*/
668 function api_statuses_mediap(&$a, $type) {
669 if (api_user()===false) {
670 logger('api_statuses_update: no user');
673 $user_info = api_get_user($a);
675 $_REQUEST['type'] = 'wall';
676 $_REQUEST['profile_uid'] = api_user();
677 $_REQUEST['api_source'] = true;
678 $txt = requestdata('status');
679 //$txt = urldecode(requestdata('status'));
681 require_once('library/HTMLPurifier.auto.php');
682 require_once('include/html2bbcode.php');
684 if((strpos($txt,'<') !== false) || (strpos($txt,'>') !== false)) {
685 $txt = html2bb_video($txt);
686 $config = HTMLPurifier_Config::createDefault();
687 $config->set('Cache.DefinitionImpl', null);
688 $purifier = new HTMLPurifier($config);
689 $txt = $purifier->purify($txt);
691 $txt = html2bbcode($txt);
693 $a->argv[1]=$user_info['screen_name']; //should be set to username?
695 $_REQUEST['hush']='yeah'; //tell wall_upload function to return img info instead of echo
696 require_once('mod/wall_upload.php');
697 $bebop = wall_upload_post($a);
699 //now that we have the img url in bbcode we can add it to the status and insert the wall item.
700 $_REQUEST['body']=$txt."\n\n".$bebop;
701 require_once('mod/item.php');
704 // this should output the last post (the one we just posted).
705 return api_status_show($a,$type);
707 api_register_func('api/statuses/mediap','api_statuses_mediap', true);
708 /*Waitman Gobble Mod*/
711 function api_statuses_update(&$a, $type) {
712 if (api_user()===false) {
713 logger('api_statuses_update: no user');
717 $user_info = api_get_user($a);
719 // convert $_POST array items to the form we use for web posts.
721 // logger('api_post: ' . print_r($_POST,true));
723 if(requestdata('htmlstatus')) {
724 require_once('library/HTMLPurifier.auto.php');
725 require_once('include/html2bbcode.php');
727 $txt = requestdata('htmlstatus');
728 if((strpos($txt,'<') !== false) || (strpos($txt,'>') !== false)) {
730 $txt = html2bb_video($txt);
732 $config = HTMLPurifier_Config::createDefault();
733 $config->set('Cache.DefinitionImpl', null);
736 $purifier = new HTMLPurifier($config);
737 $txt = $purifier->purify($txt);
739 $_REQUEST['body'] = html2bbcode($txt);
743 $_REQUEST['body'] = requestdata('status');
745 $_REQUEST['title'] = requestdata('title');
747 $parent = requestdata('in_reply_to_status_id');
748 if(ctype_digit($parent))
749 $_REQUEST['parent'] = $parent;
751 $_REQUEST['parent_uri'] = $parent;
753 if(requestdata('lat') && requestdata('long'))
754 $_REQUEST['coord'] = sprintf("%s %s",requestdata('lat'),requestdata('long'));
755 $_REQUEST['profile_uid'] = api_user();
758 $_REQUEST['type'] = 'net-comment';
760 // Check for throttling (maximum posts per day, week and month)
761 $throttle_day = get_config('system','throttle_limit_day');
762 if ($throttle_day > 0) {
763 $datefrom = date("Y-m-d H:i:s", time() - 24*60*60);
765 $r = q("SELECT COUNT(*) AS `posts_day` FROM `item` WHERE `uid`=%d AND `wall`
766 AND `created` > '%s' AND `id` = `parent`",
767 intval(api_user()), dbesc($datefrom));
770 $posts_day = $r[0]["posts_day"];
774 if ($posts_day > $throttle_day) {
775 logger('Daily posting limit reached for user '.api_user(), LOGGER_DEBUG);
776 die(api_error($a, $type, sprintf(t("Daily posting limit of %d posts reached. The post was rejected."), $throttle_day)));
780 $throttle_week = get_config('system','throttle_limit_week');
781 if ($throttle_week > 0) {
782 $datefrom = date("Y-m-d H:i:s", time() - 24*60*60*7);
784 $r = q("SELECT COUNT(*) AS `posts_week` FROM `item` WHERE `uid`=%d AND `wall`
785 AND `created` > '%s' AND `id` = `parent`",
786 intval(api_user()), dbesc($datefrom));
789 $posts_week = $r[0]["posts_week"];
793 if ($posts_week > $throttle_week) {
794 logger('Weekly posting limit reached for user '.api_user(), LOGGER_DEBUG);
795 die(api_error($a, $type, sprintf(t("Weekly posting limit of %d posts reached. The post was rejected."), $throttle_week)));
799 $throttle_month = get_config('system','throttle_limit_month');
800 if ($throttle_month > 0) {
801 $datefrom = date("Y-m-d H:i:s", time() - 24*60*60*30);
803 $r = q("SELECT COUNT(*) AS `posts_month` FROM `item` WHERE `uid`=%d AND `wall`
804 AND `created` > '%s' AND `id` = `parent`",
805 intval(api_user()), dbesc($datefrom));
808 $posts_month = $r[0]["posts_month"];
812 if ($posts_month > $throttle_month) {
813 logger('Monthly posting limit reached for user '.api_user(), LOGGER_DEBUG);
814 die(api_error($a, $type, sprintf(t("Monthly posting limit of %d posts reached. The post was rejected."), $throttle_month)));
818 $_REQUEST['type'] = 'wall';
821 if(x($_FILES,'media')) {
822 // upload the image if we have one
823 $_REQUEST['hush']='yeah'; //tell wall_upload function to return img info instead of echo
824 require_once('mod/wall_upload.php');
825 $media = wall_upload_post($a);
827 $_REQUEST['body'] .= "\n\n".$media;
830 // To-Do: Multiple IDs
831 if (requestdata('media_ids')) {
832 $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",
833 intval(requestdata('media_ids')), api_user());
835 $phototypes = Photo::supportedTypes();
836 $ext = $phototypes[$r[0]['type']];
837 $_REQUEST['body'] .= "\n\n".'[url='.$a->get_baseurl().'/photos/'.$r[0]['nickname'].'/image/'.$r[0]['resource-id'].']';
838 $_REQUEST['body'] .= '[img]'.$a->get_baseurl()."/photo/".$r[0]['resource-id']."-".$r[0]['scale'].".".$ext."[/img][/url]";
842 // set this so that the item_post() function is quiet and doesn't redirect or emit json
844 $_REQUEST['api_source'] = true;
846 if (!x($_REQUEST, "source"))
847 $_REQUEST["source"] = api_source();
849 // call out normal post function
851 require_once('mod/item.php');
854 // this should output the last post (the one we just posted).
855 return api_status_show($a,$type);
857 api_register_func('api/statuses/update','api_statuses_update', true);
858 api_register_func('api/statuses/update_with_media','api_statuses_update', true);
861 function api_media_upload(&$a, $type) {
862 if (api_user()===false) {
867 $user_info = api_get_user($a);
869 if(!x($_FILES,'media')) {
874 require_once('mod/wall_upload.php');
875 $media = wall_upload_post($a, false);
881 $returndata = array();
882 $returndata["media_id"] = $media["id"];
883 $returndata["media_id_string"] = (string)$media["id"];
884 $returndata["size"] = $media["size"];
885 $returndata["image"] = array("w" => $media["width"],
886 "h" => $media["height"],
887 "image_type" => $media["type"]);
889 logger("Media uploaded: ".print_r($returndata, true), LOGGER_DEBUG);
891 return array("media" => $returndata);
894 api_register_func('api/media/upload','api_media_upload', true);
896 function api_status_show(&$a, $type){
897 $user_info = api_get_user($a);
899 logger('api_status_show: user_info: '.print_r($user_info, true), LOGGER_DEBUG);
901 // get last public wall message
902 $lastwall = q("SELECT `item`.*, `i`.`contact-id` as `reply_uid`, `i`.`author-link` AS `item-author`
903 FROM `item`, `item` as `i`
904 WHERE `item`.`contact-id` = %d AND `item`.`uid` = %d
905 AND ((`item`.`author-link` IN ('%s', '%s')) OR (`item`.`owner-link` IN ('%s', '%s')))
906 AND `i`.`id` = `item`.`parent`
907 AND `item`.`type`!='activity'
908 AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''
909 ORDER BY `item`.`created` DESC
911 intval($user_info['cid']),
913 dbesc($user_info['url']),
914 dbesc(normalise_link($user_info['url'])),
915 dbesc($user_info['url']),
916 dbesc(normalise_link($user_info['url']))
919 if (count($lastwall)>0){
920 $lastwall = $lastwall[0];
922 $in_reply_to_status_id = NULL;
923 $in_reply_to_user_id = NULL;
924 $in_reply_to_status_id_str = NULL;
925 $in_reply_to_user_id_str = NULL;
926 $in_reply_to_screen_name = NULL;
927 if (intval($lastwall['parent']) != intval($lastwall['id'])) {
928 $in_reply_to_status_id= intval($lastwall['parent']);
929 $in_reply_to_status_id_str = (string) intval($lastwall['parent']);
931 $r = q("SELECT * FROM unique_contacts WHERE `url` = '%s'", dbesc(normalise_link($lastwall['item-author'])));
933 if ($r[0]['nick'] == "")
934 $r[0]['nick'] = api_get_nick($r[0]["url"]);
936 $in_reply_to_screen_name = (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']);
937 $in_reply_to_user_id = intval($r[0]['id']);
938 $in_reply_to_user_id_str = (string) intval($r[0]['id']);
942 // There seems to be situation, where both fields are identical:
943 // https://github.com/friendica/friendica/issues/1010
944 // This is a bugfix for that.
945 if (intval($in_reply_to_status_id) == intval($lastwall['id'])) {
946 logger('api_status_show: this message should never appear: id: '.$lastwall['id'].' similar to reply-to: '.$in_reply_to_status_id, LOGGER_DEBUG);
947 $in_reply_to_status_id = NULL;
948 $in_reply_to_user_id = NULL;
949 $in_reply_to_status_id_str = NULL;
950 $in_reply_to_user_id_str = NULL;
951 $in_reply_to_screen_name = NULL;
954 $converted = api_convert_item($item);
956 $status_info = array(
957 'text' => $converted["text"],
958 'truncated' => false,
959 'created_at' => api_date($lastwall['created']),
960 'in_reply_to_status_id' => $in_reply_to_status_id,
961 'in_reply_to_status_id_str' => $in_reply_to_status_id_str,
962 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
963 'id' => intval($lastwall['id']),
964 'id_str' => (string) $lastwall['id'],
965 'in_reply_to_user_id' => $in_reply_to_user_id,
966 'in_reply_to_user_id_str' => $in_reply_to_user_id_str,
967 'in_reply_to_screen_name' => $in_reply_to_screen_name,
969 'favorited' => $lastwall['starred'] ? true : false,
970 'user' => $user_info,
971 'statusnet_html' => $converted["html"],
972 'statusnet_conversation_id' => $lastwall['parent'],
975 if (count($converted["attachments"]) > 0)
976 $status_info["attachments"] = $converted["attachments"];
978 if (count($converted["entities"]) > 0)
979 $status_info["entities"] = $converted["entities"];
981 if (($lastwall['item_network'] != "") AND ($status["source"] == 'web'))
982 $status_info["source"] = network_to_name($lastwall['item_network']);
983 elseif (($lastwall['item_network'] != "") AND (network_to_name($lastwall['item_network']) != $status_info["source"]))
984 $status_info["source"] = trim($status_info["source"].' ('.network_to_name($lastwall['item_network']).')');
986 // "uid" and "self" are only needed for some internal stuff, so remove it from here
987 unset($status_info["user"]["uid"]);
988 unset($status_info["user"]["self"]);
992 return($status_info);
994 return api_apply_template("status", $type, array('$status' => $status_info));
1003 * Returns extended information of a given user, specified by ID or screen name as per the required id parameter.
1004 * The author's most recent status will be returned inline.
1005 * http://developer.twitter.com/doc/get/users/show
1007 function api_users_show(&$a, $type){
1008 $user_info = api_get_user($a);
1010 $lastwall = q("SELECT `item`.*
1011 FROM `item`, `contact`
1012 WHERE `item`.`uid` = %d AND `verb` = '%s' AND `item`.`contact-id` = %d
1013 AND ((`item`.`author-link` IN ('%s', '%s')) OR (`item`.`owner-link` IN ('%s', '%s')))
1014 AND `contact`.`id`=`item`.`contact-id`
1015 AND `type`!='activity'
1016 AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''
1017 ORDER BY `created` DESC
1020 dbesc(ACTIVITY_POST),
1021 intval($user_info['cid']),
1022 dbesc($user_info['url']),
1023 dbesc(normalise_link($user_info['url'])),
1024 dbesc($user_info['url']),
1025 dbesc(normalise_link($user_info['url']))
1027 if (count($lastwall)>0){
1028 $lastwall = $lastwall[0];
1030 $in_reply_to_status_id = NULL;
1031 $in_reply_to_user_id = NULL;
1032 $in_reply_to_status_id_str = NULL;
1033 $in_reply_to_user_id_str = NULL;
1034 $in_reply_to_screen_name = NULL;
1035 if ($lastwall['parent']!=$lastwall['id']) {
1036 $reply = q("SELECT `item`.`id`, `item`.`contact-id` as `reply_uid`, `contact`.`nick` as `reply_author`, `item`.`author-link` AS `item-author`
1037 FROM `item`,`contact` WHERE `contact`.`id`=`item`.`contact-id` AND `item`.`id` = %d", intval($lastwall['parent']));
1038 if (count($reply)>0) {
1039 $in_reply_to_status_id = intval($lastwall['parent']);
1040 $in_reply_to_status_id_str = (string) intval($lastwall['parent']);
1042 $r = q("SELECT * FROM unique_contacts WHERE `url` = '%s'", dbesc(normalise_link($reply[0]['item-author'])));
1044 if ($r[0]['nick'] == "")
1045 $r[0]['nick'] = api_get_nick($r[0]["url"]);
1047 $in_reply_to_screen_name = (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']);
1048 $in_reply_to_user_id = intval($r[0]['id']);
1049 $in_reply_to_user_id_str = (string) intval($r[0]['id']);
1054 $converted = api_convert_item($item);
1056 $user_info['status'] = array(
1057 'text' => $converted["text"],
1058 'truncated' => false,
1059 'created_at' => api_date($lastwall['created']),
1060 'in_reply_to_status_id' => $in_reply_to_status_id,
1061 'in_reply_to_status_id_str' => $in_reply_to_status_id_str,
1062 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
1063 'id' => intval($lastwall['contact-id']),
1064 'id_str' => (string) $lastwall['contact-id'],
1065 'in_reply_to_user_id' => $in_reply_to_user_id,
1066 'in_reply_to_user_id_str' => $in_reply_to_user_id_str,
1067 'in_reply_to_screen_name' => $in_reply_to_screen_name,
1069 'favorited' => $lastwall['starred'] ? true : false,
1070 'statusnet_html' => $converted["html"],
1071 'statusnet_conversation_id' => $lastwall['parent'],
1074 if (count($converted["attachments"]) > 0)
1075 $user_info["status"]["attachments"] = $converted["attachments"];
1077 if (count($converted["entities"]) > 0)
1078 $user_info["status"]["entities"] = $converted["entities"];
1080 if (($lastwall['item_network'] != "") AND ($user_info["status"]["source"] == 'web'))
1081 $user_info["status"]["source"] = network_to_name($lastwall['item_network']);
1082 if (($lastwall['item_network'] != "") AND (network_to_name($lastwall['item_network']) != $user_info["status"]["source"]))
1083 $user_info["status"]["source"] = trim($user_info["status"]["source"].' ('.network_to_name($lastwall['item_network']).')');
1087 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1088 unset($user_info["uid"]);
1089 unset($user_info["self"]);
1091 return api_apply_template("user", $type, array('$user' => $user_info));
1094 api_register_func('api/users/show','api_users_show');
1097 function api_users_search(&$a, $type) {
1098 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1100 $userlist = array();
1102 if (isset($_GET["q"])) {
1103 $r = q("SELECT id FROM unique_contacts WHERE name='%s'", dbesc($_GET["q"]));
1105 $r = q("SELECT id FROM unique_contacts WHERE nick='%s'", dbesc($_GET["q"]));
1108 foreach ($r AS $user) {
1109 $user_info = api_get_user($a, $user["id"]);
1110 //echo print_r($user_info, true)."\n";
1111 $userdata = api_apply_template("user", $type, array('user' => $user_info));
1112 $userlist[] = $userdata["user"];
1114 $userlist = array("users" => $userlist);
1116 die(api_error($a, $type, t("User not found.")));
1118 die(api_error($a, $type, t("User not found.")));
1123 api_register_func('api/users/search','api_users_search');
1127 * http://developer.twitter.com/doc/get/statuses/home_timeline
1129 * TODO: Optional parameters
1130 * TODO: Add reply info
1132 function api_statuses_home_timeline(&$a, $type){
1133 if (api_user()===false) return false;
1135 unset($_REQUEST["user_id"]);
1136 unset($_GET["user_id"]);
1138 unset($_REQUEST["screen_name"]);
1139 unset($_GET["screen_name"]);
1141 $user_info = api_get_user($a);
1142 // get last newtork messages
1146 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1147 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1148 if ($page<0) $page=0;
1149 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1150 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1151 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1152 $exclude_replies = (x($_REQUEST,'exclude_replies')?1:0);
1153 $conversation_id = (x($_REQUEST,'conversation_id')?$_REQUEST['conversation_id']:0);
1155 $start = $page*$count;
1159 $sql_extra .= ' AND `item`.`id` <= '.intval($max_id);
1160 if ($exclude_replies > 0)
1161 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
1162 if ($conversation_id > 0)
1163 $sql_extra .= ' AND `item`.`parent` = '.intval($conversation_id);
1165 $r = q("SELECT STRAIGHT_JOIN `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1166 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1167 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1168 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1169 FROM `item`, `contact`
1170 WHERE `item`.`uid` = %d AND `verb` = '%s'
1171 AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1172 AND `contact`.`id` = `item`.`contact-id`
1173 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1176 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1178 dbesc(ACTIVITY_POST),
1180 intval($start), intval($count)
1183 $ret = api_format_items($r,$user_info);
1185 // Set all posts from the query above to seen
1187 foreach ($r AS $item)
1188 $idarray[] = intval($item["id"]);
1190 $idlist = implode(",", $idarray);
1193 $r = q("UPDATE `item` SET `unseen` = 0 WHERE `unseen` AND `id` IN (%s)", $idlist);
1196 $data = array('$statuses' => $ret);
1200 $data = api_rss_extra($a, $data, $user_info);
1203 $as = api_format_as($a, $ret, $user_info);
1204 $as['title'] = $a->config['sitename']." Home Timeline";
1205 $as['link']['url'] = $a->get_baseurl()."/".$user_info["screen_name"]."/all";
1210 return api_apply_template("timeline", $type, $data);
1212 api_register_func('api/statuses/home_timeline','api_statuses_home_timeline', true);
1213 api_register_func('api/statuses/friends_timeline','api_statuses_home_timeline', true);
1215 function api_statuses_public_timeline(&$a, $type){
1216 if (api_user()===false) return false;
1218 $user_info = api_get_user($a);
1219 // get last newtork messages
1223 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1224 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1225 if ($page<0) $page=0;
1226 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1227 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1228 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1229 $exclude_replies = (x($_REQUEST,'exclude_replies')?1:0);
1230 $conversation_id = (x($_REQUEST,'conversation_id')?$_REQUEST['conversation_id']:0);
1232 $start = $page*$count;
1235 $sql_extra = 'AND `item`.`id` <= '.intval($max_id);
1236 if ($exclude_replies > 0)
1237 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
1238 if ($conversation_id > 0)
1239 $sql_extra .= ' AND `item`.`parent` = '.intval($conversation_id);
1241 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1242 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1243 `contact`.`network`, `contact`.`thumb`, `contact`.`self`, `contact`.`writable`,
1244 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`,
1245 `user`.`nickname`, `user`.`hidewall`
1246 FROM `item` STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
1247 STRAIGHT_JOIN `user` ON `user`.`uid` = `item`.`uid`
1248 WHERE `verb` = '%s' AND `item`.`visible` = 1 AND `item`.`deleted` = 0 and `item`.`moderated` = 0
1249 AND `item`.`allow_cid` = '' AND `item`.`allow_gid` = ''
1250 AND `item`.`deny_cid` = '' AND `item`.`deny_gid` = ''
1251 AND `item`.`private` = 0 AND `item`.`wall` = 1 AND `user`.`hidewall` = 0
1252 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1255 ORDER BY `item`.`id` DESC LIMIT %d, %d ",
1256 dbesc(ACTIVITY_POST),
1261 $ret = api_format_items($r,$user_info);
1264 $data = array('$statuses' => $ret);
1268 $data = api_rss_extra($a, $data, $user_info);
1271 $as = api_format_as($a, $ret, $user_info);
1272 $as['title'] = $a->config['sitename']." Public Timeline";
1273 $as['link']['url'] = $a->get_baseurl()."/";
1278 return api_apply_template("timeline", $type, $data);
1280 api_register_func('api/statuses/public_timeline','api_statuses_public_timeline', true);
1285 function api_statuses_show(&$a, $type){
1286 if (api_user()===false) return false;
1288 $user_info = api_get_user($a);
1291 $id = intval($a->argv[3]);
1294 $id = intval($_REQUEST["id"]);
1298 $id = intval($a->argv[4]);
1300 logger('API: api_statuses_show: '.$id);
1302 $conversation = (x($_REQUEST,'conversation')?1:0);
1306 $sql_extra .= " AND `item`.`parent` = %d ORDER BY `received` ASC ";
1308 $sql_extra .= " AND `item`.`id` = %d";
1310 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1311 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1312 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1313 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1314 FROM `item`, `contact`
1315 WHERE `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1316 AND `contact`.`id` = `item`.`contact-id` AND `item`.`uid` = %d AND `item`.`verb` = '%s'
1317 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1320 dbesc(ACTIVITY_POST),
1325 die(api_error($a, $type, t("There is no status with this id.")));
1327 $ret = api_format_items($r,$user_info);
1329 if ($conversation) {
1330 $data = array('$statuses' => $ret);
1331 return api_apply_template("timeline", $type, $data);
1333 $data = array('$status' => $ret[0]);
1337 $data = api_rss_extra($a, $data, $user_info);
1339 return api_apply_template("status", $type, $data);
1342 api_register_func('api/statuses/show','api_statuses_show', true);
1348 function api_conversation_show(&$a, $type){
1349 if (api_user()===false) return false;
1351 $user_info = api_get_user($a);
1354 $id = intval($a->argv[3]);
1355 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1356 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1357 if ($page<0) $page=0;
1358 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1359 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1361 $start = $page*$count;
1364 $id = intval($_REQUEST["id"]);
1368 $id = intval($a->argv[4]);
1370 logger('API: api_conversation_show: '.$id);
1372 $r = q("SELECT `parent` FROM `item` WHERE `id` = %d", intval($id));
1374 $id = $r[0]["parent"];
1379 $sql_extra = ' AND `item`.`id` <= '.intval($max_id);
1381 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1382 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1383 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1384 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1385 FROM `item` INNER JOIN (SELECT `uri`,`parent` FROM `item` WHERE `id` = %d) AS `temp1`
1386 ON (`item`.`thr-parent` = `temp1`.`uri` AND `item`.`parent` = `temp1`.`parent`), `contact`
1387 WHERE `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1388 AND `item`.`uid` = %d AND `item`.`verb` = '%s' AND `contact`.`id` = `item`.`contact-id`
1389 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1390 AND `item`.`id`>%d $sql_extra
1391 ORDER BY `item`.`id` DESC LIMIT %d ,%d",
1392 intval($id), intval(api_user()),
1393 dbesc(ACTIVITY_POST),
1395 intval($start), intval($count)
1399 die(api_error($a, $type, t("There is no conversation with this id.")));
1401 $ret = api_format_items($r,$user_info);
1403 $data = array('$statuses' => $ret);
1404 return api_apply_template("timeline", $type, $data);
1406 api_register_func('api/conversation/show','api_conversation_show', true);
1412 function api_statuses_repeat(&$a, $type){
1415 if (api_user()===false) return false;
1417 $user_info = api_get_user($a);
1420 $id = intval($a->argv[3]);
1423 $id = intval($_REQUEST["id"]);
1427 $id = intval($a->argv[4]);
1429 logger('API: api_statuses_repeat: '.$id);
1431 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`, `contact`.`nick` as `reply_author`,
1432 `contact`.`name`, `contact`.`photo` as `reply_photo`, `contact`.`url` as `reply_url`, `contact`.`rel`,
1433 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1434 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1435 FROM `item`, `contact`
1436 WHERE `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1437 AND `contact`.`id` = `item`.`contact-id`
1438 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1440 AND `item`.`id`=%d",
1444 if ($r[0]['body'] != "") {
1445 if (!intval(get_config('system','old_share'))) {
1446 if (strpos($r[0]['body'], "[/share]") !== false) {
1447 $pos = strpos($r[0]['body'], "[share");
1448 $post = substr($r[0]['body'], $pos);
1450 $post = share_header($r[0]['author-name'], $r[0]['author-link'], $r[0]['author-avatar'], $r[0]['guid'], $r[0]['created'], $r[0]['plink']);
1452 $post .= $r[0]['body'];
1453 $post .= "[/share]";
1455 $_REQUEST['body'] = $post;
1457 $_REQUEST['body'] = html_entity_decode("♲ ", ENT_QUOTES, 'UTF-8')."[url=".$r[0]['reply_url']."]".$r[0]['reply_author']."[/url] \n".$r[0]['body'];
1459 $_REQUEST['profile_uid'] = api_user();
1460 $_REQUEST['type'] = 'wall';
1461 $_REQUEST['api_source'] = true;
1463 if (!x($_REQUEST, "source"))
1464 $_REQUEST["source"] = api_source();
1466 require_once('mod/item.php');
1470 // this should output the last post (the one we just posted).
1472 return(api_status_show($a,$type));
1474 api_register_func('api/statuses/retweet','api_statuses_repeat', true);
1479 function api_statuses_destroy(&$a, $type){
1480 if (api_user()===false) return false;
1482 $user_info = api_get_user($a);
1485 $id = intval($a->argv[3]);
1488 $id = intval($_REQUEST["id"]);
1492 $id = intval($a->argv[4]);
1494 logger('API: api_statuses_destroy: '.$id);
1496 $ret = api_statuses_show($a, $type);
1498 require_once('include/items.php');
1499 drop_item($id, false);
1503 api_register_func('api/statuses/destroy','api_statuses_destroy', true);
1507 * http://developer.twitter.com/doc/get/statuses/mentions
1510 function api_statuses_mentions(&$a, $type){
1511 if (api_user()===false) return false;
1513 unset($_REQUEST["user_id"]);
1514 unset($_GET["user_id"]);
1516 unset($_REQUEST["screen_name"]);
1517 unset($_GET["screen_name"]);
1519 $user_info = api_get_user($a);
1520 // get last newtork messages
1524 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1525 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1526 if ($page<0) $page=0;
1527 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1528 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1529 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1531 $start = $page*$count;
1533 // Ugly code - should be changed
1534 $myurl = $a->get_baseurl() . '/profile/'. $a->user['nickname'];
1535 $myurl = substr($myurl,strpos($myurl,'://')+3);
1536 //$myurl = str_replace(array('www.','.'),array('','\\.'),$myurl);
1537 $myurl = str_replace('www.','',$myurl);
1538 $diasp_url = str_replace('/profile/','/u/',$myurl);
1541 $sql_extra = ' AND `item`.`id` <= '.intval($max_id);
1543 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1544 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1545 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1546 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1547 FROM `item`, `contact`
1548 WHERE `item`.`uid` = %d AND `verb` = '%s'
1549 AND NOT (`item`.`author-link` IN ('https://%s', 'http://%s'))
1550 AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1551 AND `contact`.`id` = `item`.`contact-id`
1552 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1553 AND `item`.`parent` IN (SELECT `iid` from thread where uid = %d AND `mention` AND !`ignored`)
1556 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1558 dbesc(ACTIVITY_POST),
1559 dbesc(protect_sprintf($myurl)),
1560 dbesc(protect_sprintf($myurl)),
1563 intval($start), intval($count)
1566 $ret = api_format_items($r,$user_info);
1569 $data = array('$statuses' => $ret);
1573 $data = api_rss_extra($a, $data, $user_info);
1576 $as = api_format_as($a, $ret, $user_info);
1577 $as["title"] = $a->config['sitename']." Mentions";
1578 $as['link']['url'] = $a->get_baseurl()."/";
1583 return api_apply_template("timeline", $type, $data);
1585 api_register_func('api/statuses/mentions','api_statuses_mentions', true);
1586 api_register_func('api/statuses/replies','api_statuses_mentions', true);
1589 function api_statuses_user_timeline(&$a, $type){
1590 if (api_user()===false) return false;
1592 $user_info = api_get_user($a);
1593 // get last network messages
1595 logger("api_statuses_user_timeline: api_user: ". api_user() .
1596 "\nuser_info: ".print_r($user_info, true) .
1597 "\n_REQUEST: ".print_r($_REQUEST, true),
1601 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1602 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1603 if ($page<0) $page=0;
1604 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1605 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1606 $exclude_replies = (x($_REQUEST,'exclude_replies')?1:0);
1607 $conversation_id = (x($_REQUEST,'conversation_id')?$_REQUEST['conversation_id']:0);
1609 $start = $page*$count;
1612 if ($user_info['self']==1)
1613 $sql_extra .= " AND `item`.`wall` = 1 ";
1615 if ($exclude_replies > 0)
1616 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
1617 if ($conversation_id > 0)
1618 $sql_extra .= ' AND `item`.`parent` = '.intval($conversation_id);
1620 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1621 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1622 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1623 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1624 FROM `item`, `contact`
1625 WHERE `item`.`uid` = %d AND `verb` = '%s'
1626 AND `item`.`contact-id` = %d
1627 AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1628 AND `contact`.`id` = `item`.`contact-id`
1629 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1632 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1634 dbesc(ACTIVITY_POST),
1635 intval($user_info['cid']),
1637 intval($start), intval($count)
1640 $ret = api_format_items($r,$user_info, true);
1642 $data = array('$statuses' => $ret);
1646 $data = api_rss_extra($a, $data, $user_info);
1649 return api_apply_template("timeline", $type, $data);
1652 api_register_func('api/statuses/user_timeline','api_statuses_user_timeline', true);
1656 * Star/unstar an item
1657 * param: id : id of the item
1659 * api v1 : https://web.archive.org/web/20131019055350/https://dev.twitter.com/docs/api/1/post/favorites/create/%3Aid
1661 function api_favorites_create_destroy(&$a, $type){
1662 if (api_user()===false) return false;
1664 # for versioned api.
1665 # TODO: we need a better global soluton
1667 if ($a->argv[1]=="1.1") $action_argv_id=3;
1669 if ($a->argc<=$action_argv_id) die(api_error($a, $type, t("Invalid request.")));
1670 $action = str_replace(".".$type,"",$a->argv[$action_argv_id]);
1671 if ($a->argc==$action_argv_id+2) {
1672 $itemid = intval($a->argv[$action_argv_id+1]);
1674 $itemid = intval($_REQUEST['id']);
1677 $item = q("SELECT * FROM item WHERE id=%d AND uid=%d",
1678 $itemid, api_user());
1680 if ($item===false || count($item)==0) die(api_error($a, $type, t("Invalid item.")));
1684 $item[0]['starred']=1;
1687 $item[0]['starred']=0;
1690 die(api_error($a, $type, t("Invalid action. ".$action)));
1692 $r = q("UPDATE item SET starred=%d WHERE id=%d AND uid=%d",
1693 $item[0]['starred'], $itemid, api_user());
1695 q("UPDATE thread SET starred=%d WHERE iid=%d AND uid=%d",
1696 $item[0]['starred'], $itemid, api_user());
1698 if ($r===false) die(api_error($a, $type, t("DB error")));
1701 $user_info = api_get_user($a);
1702 $rets = api_format_items($item,$user_info);
1705 $data = array('$status' => $ret);
1709 $data = api_rss_extra($a, $data, $user_info);
1712 return api_apply_template("status", $type, $data);
1715 api_register_func('api/favorites/create', 'api_favorites_create_destroy', true);
1716 api_register_func('api/favorites/destroy', 'api_favorites_create_destroy', true);
1718 function api_favorites(&$a, $type){
1721 if (api_user()===false) return false;
1723 $called_api= array();
1725 $user_info = api_get_user($a);
1727 // in friendica starred item are private
1728 // return favorites only for self
1729 logger('api_favorites: self:' . $user_info['self']);
1731 if ($user_info['self']==0) {
1737 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1738 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1739 $count = (x($_GET,'count')?$_GET['count']:20);
1740 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1741 if ($page<0) $page=0;
1743 $start = $page*$count;
1746 $sql_extra .= ' AND `item`.`id` <= '.intval($max_id);
1748 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1749 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1750 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1751 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1752 FROM `item`, `contact`
1753 WHERE `item`.`uid` = %d
1754 AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1755 AND `item`.`starred` = 1
1756 AND `contact`.`id` = `item`.`contact-id`
1757 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1760 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1763 intval($start), intval($count)
1766 $ret = api_format_items($r,$user_info);
1770 $data = array('$statuses' => $ret);
1774 $data = api_rss_extra($a, $data, $user_info);
1777 return api_apply_template("timeline", $type, $data);
1780 api_register_func('api/favorites','api_favorites', true);
1785 function api_format_as($a, $ret, $user_info) {
1788 $as['title'] = $a->config['sitename']." Public Timeline";
1790 foreach ($ret as $item) {
1791 $singleitem["actor"]["displayName"] = $item["user"]["name"];
1792 $singleitem["actor"]["id"] = $item["user"]["contact_url"];
1793 $avatar[0]["url"] = $item["user"]["profile_image_url"];
1794 $avatar[0]["rel"] = "avatar";
1795 $avatar[0]["type"] = "";
1796 $avatar[0]["width"] = 96;
1797 $avatar[0]["height"] = 96;
1798 $avatar[1]["url"] = $item["user"]["profile_image_url"];
1799 $avatar[1]["rel"] = "avatar";
1800 $avatar[1]["type"] = "";
1801 $avatar[1]["width"] = 48;
1802 $avatar[1]["height"] = 48;
1803 $avatar[2]["url"] = $item["user"]["profile_image_url"];
1804 $avatar[2]["rel"] = "avatar";
1805 $avatar[2]["type"] = "";
1806 $avatar[2]["width"] = 24;
1807 $avatar[2]["height"] = 24;
1808 $singleitem["actor"]["avatarLinks"] = $avatar;
1810 $singleitem["actor"]["image"]["url"] = $item["user"]["profile_image_url"];
1811 $singleitem["actor"]["image"]["rel"] = "avatar";
1812 $singleitem["actor"]["image"]["type"] = "";
1813 $singleitem["actor"]["image"]["width"] = 96;
1814 $singleitem["actor"]["image"]["height"] = 96;
1815 $singleitem["actor"]["type"] = "person";
1816 $singleitem["actor"]["url"] = $item["person"]["contact_url"];
1817 $singleitem["actor"]["statusnet:profile_info"]["local_id"] = $item["user"]["id"];
1818 $singleitem["actor"]["statusnet:profile_info"]["following"] = $item["user"]["following"] ? "true" : "false";
1819 $singleitem["actor"]["statusnet:profile_info"]["blocking"] = "false";
1820 $singleitem["actor"]["contact"]["preferredUsername"] = $item["user"]["screen_name"];
1821 $singleitem["actor"]["contact"]["displayName"] = $item["user"]["name"];
1822 $singleitem["actor"]["contact"]["addresses"] = "";
1824 $singleitem["body"] = $item["text"];
1825 $singleitem["object"]["displayName"] = $item["text"];
1826 $singleitem["object"]["id"] = $item["url"];
1827 $singleitem["object"]["type"] = "note";
1828 $singleitem["object"]["url"] = $item["url"];
1829 //$singleitem["context"] =;
1830 $singleitem["postedTime"] = date("c", strtotime($item["published"]));
1831 $singleitem["provider"]["objectType"] = "service";
1832 $singleitem["provider"]["displayName"] = "Test";
1833 $singleitem["provider"]["url"] = "http://test.tld";
1834 $singleitem["title"] = $item["text"];
1835 $singleitem["verb"] = "post";
1836 $singleitem["statusnet:notice_info"]["local_id"] = $item["id"];
1837 $singleitem["statusnet:notice_info"]["source"] = $item["source"];
1838 $singleitem["statusnet:notice_info"]["favorite"] = "false";
1839 $singleitem["statusnet:notice_info"]["repeated"] = "false";
1840 //$singleitem["original"] = $item;
1841 $items[] = $singleitem;
1843 $as['items'] = $items;
1844 $as['link']['url'] = $a->get_baseurl()."/".$user_info["screen_name"]."/all";
1845 $as['link']['rel'] = "alternate";
1846 $as['link']['type'] = "text/html";
1850 function api_format_messages($item, $recipient, $sender) {
1851 // standard meta information
1853 'id' => $item['id'],
1854 'sender_id' => $sender['id'] ,
1856 'recipient_id' => $recipient['id'],
1857 'created_at' => api_date($item['created']),
1858 'sender_screen_name' => $sender['screen_name'],
1859 'recipient_screen_name' => $recipient['screen_name'],
1860 'sender' => $sender,
1861 'recipient' => $recipient,
1864 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1865 unset($ret["sender"]["uid"]);
1866 unset($ret["sender"]["self"]);
1867 unset($ret["recipient"]["uid"]);
1868 unset($ret["recipient"]["self"]);
1870 //don't send title to regular StatusNET requests to avoid confusing these apps
1871 if (x($_GET, 'getText')) {
1872 $ret['title'] = $item['title'] ;
1873 if ($_GET["getText"] == "html") {
1874 $ret['text'] = bbcode($item['body'], false, false);
1876 elseif ($_GET["getText"] == "plain") {
1877 //$ret['text'] = html2plain(bbcode($item['body'], false, false, true), 0);
1878 $ret['text'] = trim(html2plain(bbcode(api_clean_plain_items($item['body']), false, false, 2, true), 0));
1882 $ret['text'] = $item['title']."\n".html2plain(bbcode(api_clean_plain_items($item['body']), false, false, 2, true), 0);
1884 if (isset($_GET["getUserObjects"]) && $_GET["getUserObjects"] == "false") {
1885 unset($ret['sender']);
1886 unset($ret['recipient']);
1892 function api_convert_item($item) {
1894 $body = $item['body'];
1895 $attachments = api_get_attachments($body);
1897 // Workaround for ostatus messages where the title is identically to the body
1898 $html = bbcode(api_clean_plain_items($body), false, false, 2, true);
1899 $statusbody = trim(html2plain($html, 0));
1901 // handle data: images
1902 $statusbody = api_format_items_embeded_images($item,$statusbody);
1904 $statustitle = trim($item['title']);
1906 if (($statustitle != '') and (strpos($statusbody, $statustitle) !== false))
1907 $statustext = trim($statusbody);
1909 $statustext = trim($statustitle."\n\n".$statusbody);
1911 if (($item["network"] == NETWORK_FEED) and (strlen($statustext)> 1000))
1912 $statustext = substr($statustext, 0, 1000)."... \n".$item["plink"];
1914 $statushtml = trim(bbcode($body, false, false));
1916 if ($item['title'] != "")
1917 $statushtml = "<h4>".bbcode($item['title'])."</h4>\n".$statushtml;
1919 $entities = api_get_entitities($statustext, $body);
1921 return(array("text" => $statustext, "html" => $statushtml, "attachments" => $attachments, "entities" => $entities));
1924 function api_get_attachments(&$body) {
1927 $text = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $text);
1929 $URLSearchString = "^\[\]";
1930 $ret = preg_match_all("/\[img\]([$URLSearchString]*)\[\/img\]/ism", $text, $images);
1935 $attachments = array();
1937 foreach ($images[1] AS $image) {
1938 $imagedata = get_photo_info($image);
1941 $attachments[] = array("url" => $image, "mimetype" => $imagedata["mime"], "size" => $imagedata["size"]);
1944 if (strstr($_SERVER['HTTP_USER_AGENT'], "AndStatus"))
1945 foreach ($images[0] AS $orig)
1946 $body = str_replace($orig, "", $body);
1948 return $attachments;
1951 function api_get_entitities(&$text, $bbcode) {
1954 * Links at the first character of the post
1959 $include_entities = strtolower(x($_REQUEST,'include_entities')?$_REQUEST['include_entities']:"false");
1961 if ($include_entities != "true") {
1962 require_once("mod/proxy.php");
1964 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
1966 foreach ($images[1] AS $image) {
1967 $replace = proxy_url($image);
1968 $text = str_replace($image, $replace, $text);
1973 $bbcode = bb_CleanPictureLinks($bbcode);
1975 // Change pure links in text to bbcode uris
1976 $bbcode = preg_replace("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", '$1[url=$2]$2[/url]', $bbcode);
1978 $entities = array();
1979 $entities["hashtags"] = array();
1980 $entities["symbols"] = array();
1981 $entities["urls"] = array();
1982 $entities["user_mentions"] = array();
1984 $URLSearchString = "^\[\]";
1986 $bbcode = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'#$2',$bbcode);
1988 $bbcode = preg_replace("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism",'[url=$1]$2[/url]',$bbcode);
1989 //$bbcode = preg_replace("/\[url\](.*?)\[\/url\]/ism",'[url=$1]$1[/url]',$bbcode);
1990 $bbcode = preg_replace("/\[video\](.*?)\[\/video\]/ism",'[url=$1]$1[/url]',$bbcode);
1992 $bbcode = preg_replace("/\[youtube\]([A-Za-z0-9\-_=]+)(.*?)\[\/youtube\]/ism",
1993 '[url=https://www.youtube.com/watch?v=$1]https://www.youtube.com/watch?v=$1[/url]', $bbcode);
1994 $bbcode = preg_replace("/\[youtube\](.*?)\[\/youtube\]/ism",'[url=$1]$1[/url]',$bbcode);
1996 $bbcode = preg_replace("/\[vimeo\]([0-9]+)(.*?)\[\/vimeo\]/ism",
1997 '[url=https://vimeo.com/$1]https://vimeo.com/$1[/url]', $bbcode);
1998 $bbcode = preg_replace("/\[vimeo\](.*?)\[\/vimeo\]/ism",'[url=$1]$1[/url]',$bbcode);
2000 $bbcode = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $bbcode);
2002 //preg_match_all("/\[url\]([$URLSearchString]*)\[\/url\]/ism", $bbcode, $urls1);
2003 preg_match_all("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $bbcode, $urls);
2005 $ordered_urls = array();
2006 foreach ($urls[1] AS $id=>$url) {
2007 //$start = strpos($text, $url, $offset);
2008 $start = iconv_strpos($text, $url, 0, "UTF-8");
2009 if (!($start === false))
2010 $ordered_urls[$start] = array("url" => $url, "title" => $urls[2][$id]);
2013 ksort($ordered_urls);
2016 //foreach ($urls[1] AS $id=>$url) {
2017 foreach ($ordered_urls AS $url) {
2018 if ((substr($url["title"], 0, 7) != "http://") AND (substr($url["title"], 0, 8) != "https://") AND
2019 !strpos($url["title"], "http://") AND !strpos($url["title"], "https://"))
2020 $display_url = $url["title"];
2022 $display_url = str_replace(array("http://www.", "https://www."), array("", ""), $url["url"]);
2023 $display_url = str_replace(array("http://", "https://"), array("", ""), $display_url);
2025 if (strlen($display_url) > 26)
2026 $display_url = substr($display_url, 0, 25)."…";
2029 //$start = strpos($text, $url, $offset);
2030 $start = iconv_strpos($text, $url["url"], $offset, "UTF-8");
2031 if (!($start === false)) {
2032 $entities["urls"][] = array("url" => $url["url"],
2033 "expanded_url" => $url["url"],
2034 "display_url" => $display_url,
2035 "indices" => array($start, $start+strlen($url["url"])));
2036 $offset = $start + 1;
2040 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2041 $ordered_images = array();
2042 foreach ($images[1] AS $image) {
2043 //$start = strpos($text, $url, $offset);
2044 $start = iconv_strpos($text, $image, 0, "UTF-8");
2045 if (!($start === false))
2046 $ordered_images[$start] = $image;
2048 //$entities["media"] = array();
2051 foreach ($ordered_images AS $url) {
2052 $display_url = str_replace(array("http://www.", "https://www."), array("", ""), $url);
2053 $display_url = str_replace(array("http://", "https://"), array("", ""), $display_url);
2055 if (strlen($display_url) > 26)
2056 $display_url = substr($display_url, 0, 25)."…";
2058 $start = iconv_strpos($text, $url, $offset, "UTF-8");
2059 if (!($start === false)) {
2060 $image = get_photo_info($url);
2062 // If image cache is activated, then use the following sizes:
2063 // thumb (150), small (340), medium (600) and large (1024)
2064 if (!get_config("system", "proxy_disabled")) {
2065 require_once("mod/proxy.php");
2066 $media_url = proxy_url($url);
2069 $scale = scale_image($image[0], $image[1], 150);
2070 $sizes["thumb"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2072 if (($image[0] > 150) OR ($image[1] > 150)) {
2073 $scale = scale_image($image[0], $image[1], 340);
2074 $sizes["small"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2077 $scale = scale_image($image[0], $image[1], 600);
2078 $sizes["medium"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2080 if (($image[0] > 600) OR ($image[1] > 600)) {
2081 $scale = scale_image($image[0], $image[1], 1024);
2082 $sizes["large"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2086 $sizes["medium"] = array("w" => $image[0], "h" => $image[1], "resize" => "fit");
2089 $entities["media"][] = array(
2091 "id_str" => (string)$start+1,
2092 "indices" => array($start, $start+strlen($url)),
2093 "media_url" => normalise_link($media_url),
2094 "media_url_https" => $media_url,
2096 "display_url" => $display_url,
2097 "expanded_url" => $url,
2101 $offset = $start + 1;
2107 function api_format_items_embeded_images($item, $text){
2109 $text = preg_replace_callback(
2110 "|data:image/([^;]+)[^=]+=*|m",
2111 function($match) use ($a, $item) {
2112 return $a->get_baseurl()."/display/".$item['guid'];
2118 function api_format_items($r,$user_info, $filter_user = false) {
2123 foreach($r as $item) {
2124 api_share_as_retweet($item);
2126 localize_item($item);
2127 $status_user = api_item_get_user($a,$item);
2129 // Look if the posts are matching if they should be filtered by user id
2130 if ($filter_user AND ($status_user["id"] != $user_info["id"]))
2133 if ($item['thr-parent'] != $item['uri']) {
2134 $r = q("SELECT id FROM item WHERE uid=%d AND uri='%s' LIMIT 1",
2136 dbesc($item['thr-parent']));
2138 $in_reply_to_status_id = intval($r[0]['id']);
2140 $in_reply_to_status_id = intval($item['parent']);
2142 $in_reply_to_status_id_str = (string) intval($item['parent']);
2144 $in_reply_to_screen_name = NULL;
2145 $in_reply_to_user_id = NULL;
2146 $in_reply_to_user_id_str = NULL;
2148 $r = q("SELECT `author-link` FROM item WHERE uid=%d AND id=%d LIMIT 1",
2150 intval($in_reply_to_status_id));
2152 $r = q("SELECT * FROM unique_contacts WHERE `url` = '%s'", dbesc(normalise_link($r[0]['author-link'])));
2155 if ($r[0]['nick'] == "")
2156 $r[0]['nick'] = api_get_nick($r[0]["url"]);
2158 $in_reply_to_screen_name = (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']);
2159 $in_reply_to_user_id = intval($r[0]['id']);
2160 $in_reply_to_user_id_str = (string) intval($r[0]['id']);
2164 $in_reply_to_screen_name = NULL;
2165 $in_reply_to_user_id = NULL;
2166 $in_reply_to_status_id = NULL;
2167 $in_reply_to_user_id_str = NULL;
2168 $in_reply_to_status_id_str = NULL;
2171 $converted = api_convert_item($item);
2174 'text' => $converted["text"],
2175 'truncated' => False,
2176 'created_at'=> api_date($item['created']),
2177 'in_reply_to_status_id' => $in_reply_to_status_id,
2178 'in_reply_to_status_id_str' => $in_reply_to_status_id_str,
2179 'source' => (($item['app']) ? $item['app'] : 'web'),
2180 'id' => intval($item['id']),
2181 'id_str' => (string) intval($item['id']),
2182 'in_reply_to_user_id' => $in_reply_to_user_id,
2183 'in_reply_to_user_id_str' => $in_reply_to_user_id_str,
2184 'in_reply_to_screen_name' => $in_reply_to_screen_name,
2186 'favorited' => $item['starred'] ? true : false,
2187 'user' => $status_user ,
2188 //'entities' => NULL,
2189 'statusnet_html' => $converted["html"],
2190 'statusnet_conversation_id' => $item['parent'],
2193 if (count($converted["attachments"]) > 0)
2194 $status["attachments"] = $converted["attachments"];
2196 if (count($converted["entities"]) > 0)
2197 $status["entities"] = $converted["entities"];
2199 if (($item['item_network'] != "") AND ($status["source"] == 'web'))
2200 $status["source"] = network_to_name($item['item_network']);
2201 else if (($item['item_network'] != "") AND (network_to_name($item['item_network']) != $status["source"]))
2202 $status["source"] = trim($status["source"].' ('.network_to_name($item['item_network']).')');
2205 // Retweets are only valid for top postings
2206 // It doesn't work reliable with the link if its a feed
2207 $IsRetweet = ($item['owner-link'] != $item['author-link']);
2209 $IsRetweet = (($item['owner-name'] != $item['author-name']) OR ($item['owner-avatar'] != $item['author-avatar']));
2211 if ($IsRetweet AND ($item["id"] == $item["parent"])) {
2212 $retweeted_status = $status;
2213 $retweeted_status["user"] = api_get_user($a,$item["author-link"]);
2215 $status["retweeted_status"] = $retweeted_status;
2218 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2219 unset($status["user"]["uid"]);
2220 unset($status["user"]["self"]);
2222 // 'geo' => array('type' => 'Point',
2223 // 'coordinates' => array((float) $notice->lat,
2224 // (float) $notice->lon));
2232 function api_account_rate_limit_status(&$a,$type) {
2235 'reset_time_in_seconds' => strtotime('now + 1 hour'),
2236 'remaining_hits' => (string) 150,
2237 'hourly_limit' => (string) 150,
2238 'reset_time' => api_date(datetime_convert('UTC','UTC','now + 1 hour',ATOM_TIME)),
2241 $hash['resettime_in_seconds'] = $hash['reset_time_in_seconds'];
2243 return api_apply_template('ratelimit', $type, array('$hash' => $hash));
2246 api_register_func('api/account/rate_limit_status','api_account_rate_limit_status',true);
2248 function api_help_test(&$a,$type) {
2255 return api_apply_template('test', $type, array("$ok" => $ok));
2258 api_register_func('api/help/test','api_help_test',false);
2260 function api_lists(&$a,$type) {
2265 api_register_func('api/lists','api_lists',true);
2267 function api_lists_list(&$a,$type) {
2272 api_register_func('api/lists/list','api_lists_list',true);
2275 * https://dev.twitter.com/docs/api/1/get/statuses/friends
2276 * This function is deprecated by Twitter
2277 * returns: json, xml
2279 function api_statuses_f(&$a, $type, $qtype) {
2280 if (api_user()===false) return false;
2281 $user_info = api_get_user($a);
2283 if (x($_GET,'cursor') && $_GET['cursor']=='undefined'){
2284 /* this is to stop Hotot to load friends multiple times
2285 * I'm not sure if I'm missing return something or
2286 * is a bug in hotot. Workaround, meantime
2290 return array('$users' => $ret);*/
2294 if($qtype == 'friends')
2295 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
2296 if($qtype == 'followers')
2297 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
2299 // friends and followers only for self
2300 if ($user_info['self'] == 0)
2301 $sql_extra = " AND false ";
2303 $r = q("SELECT `nurl` FROM `contact` WHERE `uid` = %d AND `self` = 0 AND `blocked` = 0 AND `pending` = 0 $sql_extra",
2308 foreach($r as $cid){
2309 $user = api_get_user($a, $cid['nurl']);
2310 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2311 unset($user["uid"]);
2312 unset($user["self"]);
2318 return array('$users' => $ret);
2321 function api_statuses_friends(&$a, $type){
2322 $data = api_statuses_f($a,$type,"friends");
2323 if ($data===false) return false;
2324 return api_apply_template("friends", $type, $data);
2326 function api_statuses_followers(&$a, $type){
2327 $data = api_statuses_f($a,$type,"followers");
2328 if ($data===false) return false;
2329 return api_apply_template("friends", $type, $data);
2331 api_register_func('api/statuses/friends','api_statuses_friends',true);
2332 api_register_func('api/statuses/followers','api_statuses_followers',true);
2339 function api_statusnet_config(&$a,$type) {
2340 $name = $a->config['sitename'];
2341 $server = $a->get_hostname();
2342 $logo = $a->get_baseurl() . '/images/friendica-64.png';
2343 $email = $a->config['admin_email'];
2344 $closed = (($a->config['register_policy'] == REGISTER_CLOSED) ? 'true' : 'false');
2345 $private = (($a->config['system']['block_public']) ? 'true' : 'false');
2346 $textlimit = (string) (($a->config['max_import_size']) ? $a->config['max_import_size'] : 200000);
2347 if($a->config['api_import_size'])
2348 $texlimit = string($a->config['api_import_size']);
2349 $ssl = (($a->config['system']['have_ssl']) ? 'true' : 'false');
2350 $sslserver = (($ssl === 'true') ? str_replace('http:','https:',$a->get_baseurl()) : '');
2353 'site' => array('name' => $name,'server' => $server, 'theme' => 'default', 'path' => '',
2354 'logo' => $logo, 'fancy' => true, 'language' => 'en', 'email' => $email, 'broughtby' => '',
2355 'broughtbyurl' => '', 'timezone' => 'UTC', 'closed' => $closed, 'inviteonly' => false,
2356 'private' => $private, 'textlimit' => $textlimit, 'sslserver' => $sslserver, 'ssl' => $ssl,
2357 'shorturllength' => '30',
2358 'friendica' => array(
2359 'FRIENDICA_PLATFORM' => FRIENDICA_PLATFORM,
2360 'FRIENDICA_VERSION' => FRIENDICA_VERSION,
2361 'DFRN_PROTOCOL_VERSION' => DFRN_PROTOCOL_VERSION,
2362 'DB_UPDATE_VERSION' => DB_UPDATE_VERSION
2367 return api_apply_template('config', $type, array('$config' => $config));
2370 api_register_func('api/statusnet/config','api_statusnet_config',false);
2372 function api_statusnet_version(&$a,$type) {
2376 if($type === 'xml') {
2377 header("Content-type: application/xml");
2378 echo '<?xml version="1.0" encoding="UTF-8"?>' . "\r\n" . '<version>0.9.7</version>' . "\r\n";
2381 elseif($type === 'json') {
2382 header("Content-type: application/json");
2387 api_register_func('api/statusnet/version','api_statusnet_version',false);
2390 function api_ff_ids(&$a,$type,$qtype) {
2394 $user_info = api_get_user($a);
2396 if($qtype == 'friends')
2397 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
2398 if($qtype == 'followers')
2399 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
2401 if (!$user_info["self"])
2402 $sql_extra = " AND false ";
2404 $stringify_ids = (x($_REQUEST,'stringify_ids')?$_REQUEST['stringify_ids']:false);
2406 $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",
2412 if($type === 'xml') {
2413 header("Content-type: application/xml");
2414 echo '<?xml version="1.0" encoding="UTF-8"?>' . "\r\n" . '<ids>' . "\r\n";
2416 echo '<id>' . $rr['id'] . '</id>' . "\r\n";
2417 echo '</ids>' . "\r\n";
2420 elseif($type === 'json') {
2422 header("Content-type: application/json");
2427 $ret[] = intval($rr['id']);
2429 echo json_encode($ret);
2435 function api_friends_ids(&$a,$type) {
2436 api_ff_ids($a,$type,'friends');
2438 function api_followers_ids(&$a,$type) {
2439 api_ff_ids($a,$type,'followers');
2441 api_register_func('api/friends/ids','api_friends_ids',true);
2442 api_register_func('api/followers/ids','api_followers_ids',true);
2445 function api_direct_messages_new(&$a, $type) {
2446 if (api_user()===false) return false;
2448 if (!x($_POST, "text") OR (!x($_POST,"screen_name") AND !x($_POST,"user_id"))) return;
2450 $sender = api_get_user($a);
2452 require_once("include/message.php");
2454 if ($_POST['screen_name']) {
2455 $r = q("SELECT `id`, `nurl`, `network` FROM `contact` WHERE `uid`=%d AND `nick`='%s'",
2457 dbesc($_POST['screen_name']));
2459 // Selecting the id by priority, friendica first
2460 api_best_nickname($r);
2462 $recipient = api_get_user($a, $r[0]['nurl']);
2464 $recipient = api_get_user($a, $_POST['user_id']);
2468 if (x($_REQUEST,'replyto')) {
2469 $r = q('SELECT `parent-uri`, `title` FROM `mail` WHERE `uid`=%d AND `id`=%d',
2471 intval($_REQUEST['replyto']));
2472 $replyto = $r[0]['parent-uri'];
2473 $sub = $r[0]['title'];
2476 if (x($_REQUEST,'title')) {
2477 $sub = $_REQUEST['title'];
2480 $sub = ((strlen($_POST['text'])>10)?substr($_POST['text'],0,10)."...":$_POST['text']);
2484 $id = send_message($recipient['cid'], $_POST['text'], $sub, $replyto);
2487 $r = q("SELECT * FROM `mail` WHERE id=%d", intval($id));
2488 $ret = api_format_messages($r[0], $recipient, $sender);
2491 $ret = array("error"=>$id);
2494 $data = Array('$messages'=>$ret);
2499 $data = api_rss_extra($a, $data, $user_info);
2502 return api_apply_template("direct_messages", $type, $data);
2505 api_register_func('api/direct_messages/new','api_direct_messages_new',true);
2507 function api_direct_messages_box(&$a, $type, $box) {
2508 if (api_user()===false) return false;
2512 $count = (x($_GET,'count')?$_GET['count']:20);
2513 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
2514 if ($page<0) $page=0;
2516 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
2517 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
2519 $user_id = (x($_REQUEST,'user_id')?$_REQUEST['user_id']:"");
2520 $screen_name = (x($_REQUEST,'screen_name')?$_REQUEST['screen_name']:"");
2523 unset($_REQUEST["user_id"]);
2524 unset($_GET["user_id"]);
2526 unset($_REQUEST["screen_name"]);
2527 unset($_GET["screen_name"]);
2529 $user_info = api_get_user($a);
2530 //$profile_url = $a->get_baseurl() . '/profile/' . $a->user['nickname'];
2531 $profile_url = $user_info["url"];
2535 $start = $page*$count;
2538 if ($box=="sentbox") {
2539 $sql_extra = "`mail`.`from-url`='".dbesc( $profile_url )."'";
2541 elseif ($box=="conversation") {
2542 $sql_extra = "`mail`.`parent-uri`='".dbesc( $_GET["uri"] ) ."'";
2544 elseif ($box=="all") {
2545 $sql_extra = "true";
2547 elseif ($box=="inbox") {
2548 $sql_extra = "`mail`.`from-url`!='".dbesc( $profile_url )."'";
2552 $sql_extra .= ' AND `mail`.`id` <= '.intval($max_id);
2554 if ($user_id !="") {
2555 $sql_extra .= ' AND `mail`.`contact-id` = ' . intval($user_id);
2557 elseif($screen_name !=""){
2558 $sql_extra .= " AND `contact`.`nick` = '" . dbesc($screen_name). "'";
2561 $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",
2564 intval($start), intval($count)
2569 foreach($r as $item) {
2570 if ($box == "inbox" || $item['from-url'] != $profile_url){
2571 $recipient = $user_info;
2572 $sender = api_get_user($a,normalise_link($item['contact-url']));
2574 elseif ($box == "sentbox" || $item['from-url'] == $profile_url){
2575 $recipient = api_get_user($a,normalise_link($item['contact-url']));
2576 $sender = $user_info;
2579 $ret[]=api_format_messages($item, $recipient, $sender);
2583 $data = array('$messages' => $ret);
2587 $data = api_rss_extra($a, $data, $user_info);
2590 return api_apply_template("direct_messages", $type, $data);
2594 function api_direct_messages_sentbox(&$a, $type){
2595 return api_direct_messages_box($a, $type, "sentbox");
2597 function api_direct_messages_inbox(&$a, $type){
2598 return api_direct_messages_box($a, $type, "inbox");
2600 function api_direct_messages_all(&$a, $type){
2601 return api_direct_messages_box($a, $type, "all");
2603 function api_direct_messages_conversation(&$a, $type){
2604 return api_direct_messages_box($a, $type, "conversation");
2606 api_register_func('api/direct_messages/conversation','api_direct_messages_conversation',true);
2607 api_register_func('api/direct_messages/all','api_direct_messages_all',true);
2608 api_register_func('api/direct_messages/sent','api_direct_messages_sentbox',true);
2609 api_register_func('api/direct_messages','api_direct_messages_inbox',true);
2613 function api_oauth_request_token(&$a, $type){
2615 $oauth = new FKOAuth1();
2616 $r = $oauth->fetch_request_token(OAuthRequest::from_request());
2617 }catch(Exception $e){
2618 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage()); killme();
2623 function api_oauth_access_token(&$a, $type){
2625 $oauth = new FKOAuth1();
2626 $r = $oauth->fetch_access_token(OAuthRequest::from_request());
2627 }catch(Exception $e){
2628 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage()); killme();
2634 api_register_func('api/oauth/request_token', 'api_oauth_request_token', false);
2635 api_register_func('api/oauth/access_token', 'api_oauth_access_token', false);
2638 function api_fr_photos_list(&$a,$type) {
2639 if (api_user()===false) return false;
2640 $r = q("select distinct `resource-id` from photo where uid = %d and album != 'Contact Photos' ",
2641 intval(local_user())
2646 $ret[] = $rr['resource-id'];
2647 header("Content-type: application/json");
2648 echo json_encode($ret);
2653 function api_fr_photo_detail(&$a,$type) {
2654 if (api_user()===false) return false;
2655 if(! $_REQUEST['photo_id']) return false;
2656 $scale = ((array_key_exists('scale',$_REQUEST)) ? intval($_REQUEST['scale']) : 0);
2657 $r = q("select * from photo where uid = %d and `resource-id` = '%s' and scale = %d limit 1",
2658 intval(local_user()),
2659 dbesc($_REQUEST['photo_id']),
2663 header("Content-type: application/json");
2664 $r[0]['data'] = base64_encode($r[0]['data']);
2665 echo json_encode($r[0]);
2671 api_register_func('api/friendica/photos/list', 'api_fr_photos_list', true);
2672 api_register_func('api/friendica/photo', 'api_fr_photo_detail', true);
2677 * similar as /mod/redir.php
2678 * redirect to 'url' after dfrn auth
2680 * why this when there is mod/redir.php already?
2681 * This use api_user() and api_login()
2684 * c_url: url of remote contact to auth to
2685 * url: string, url to redirect after auth
2687 function api_friendica_remoteauth(&$a) {
2688 $url = ((x($_GET,'url')) ? $_GET['url'] : '');
2689 $c_url = ((x($_GET,'c_url')) ? $_GET['c_url'] : '');
2691 if ($url === '' || $c_url === '')
2692 die((api_error($a, 'json', "Wrong parameters")));
2694 $c_url = normalise_link($c_url);
2698 $r = q("SELECT * FROM `contact` WHERE `id` = %d AND `nurl` = '%s' LIMIT 1",
2703 if ((! count($r)) || ($r[0]['network'] !== NETWORK_DFRN))
2704 die((api_error($a, 'json', "Unknown contact")));
2708 $dfrn_id = $orig_id = (($r[0]['issued-id']) ? $r[0]['issued-id'] : $r[0]['dfrn-id']);
2710 if($r[0]['duplex'] && $r[0]['issued-id']) {
2711 $orig_id = $r[0]['issued-id'];
2712 $dfrn_id = '1:' . $orig_id;
2714 if($r[0]['duplex'] && $r[0]['dfrn-id']) {
2715 $orig_id = $r[0]['dfrn-id'];
2716 $dfrn_id = '0:' . $orig_id;
2719 $sec = random_string();
2721 q("INSERT INTO `profile_check` ( `uid`, `cid`, `dfrn_id`, `sec`, `expire`)
2722 VALUES( %d, %s, '%s', '%s', %d )",
2730 logger($r[0]['name'] . ' ' . $sec, LOGGER_DEBUG);
2731 $dest = (($url) ? '&destination_url=' . $url : '');
2732 goaway ($r[0]['poll'] . '?dfrn_id=' . $dfrn_id
2733 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
2734 . '&type=profile&sec=' . $sec . $dest . $quiet );
2736 api_register_func('api/friendica/remoteauth', 'api_friendica_remoteauth', true);
2740 function api_share_as_retweet(&$item) {
2741 $body = trim($item["body"]);
2743 // Skip if it isn't a pure repeated messages
2744 // Does it start with a share?
2745 if (strpos($body, "[share") > 0)
2748 // Does it end with a share?
2749 if (strlen($body) > (strrpos($body, "[/share]") + 8))
2752 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$1",$body);
2753 // Skip if there is no shared message in there
2754 if ($body == $attributes)
2758 preg_match("/author='(.*?)'/ism", $attributes, $matches);
2759 if ($matches[1] != "")
2760 $author = html_entity_decode($matches[1],ENT_QUOTES,'UTF-8');
2762 preg_match('/author="(.*?)"/ism', $attributes, $matches);
2763 if ($matches[1] != "")
2764 $author = $matches[1];
2767 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
2768 if ($matches[1] != "")
2769 $profile = $matches[1];
2771 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
2772 if ($matches[1] != "")
2773 $profile = $matches[1];
2776 preg_match("/avatar='(.*?)'/ism", $attributes, $matches);
2777 if ($matches[1] != "")
2778 $avatar = $matches[1];
2780 preg_match('/avatar="(.*?)"/ism', $attributes, $matches);
2781 if ($matches[1] != "")
2782 $avatar = $matches[1];
2785 preg_match("/link='(.*?)'/ism", $attributes, $matches);
2786 if ($matches[1] != "")
2787 $link = $matches[1];
2789 preg_match('/link="(.*?)"/ism', $attributes, $matches);
2790 if ($matches[1] != "")
2791 $link = $matches[1];
2793 $shared_body = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$2",$body);
2795 if (($shared_body == "") OR ($profile == "") OR ($author == "") OR ($avatar == ""))
2798 $item["body"] = $shared_body;
2799 $item["author-name"] = $author;
2800 $item["author-link"] = $profile;
2801 $item["author-avatar"] = $avatar;
2802 $item["plink"] = $link;
2808 function api_get_nick($profile) {
2810 - remove trailing jung from profile url
2811 - pump.io check has to check the website
2816 $friendica = preg_replace("=https?://(.*)/profile/(.*)=ism", "$2", $profile);
2817 if ($friendica != $profile)
2821 $diaspora = preg_replace("=https?://(.*)/u/(.*)=ism", "$2", $profile);
2822 if ($diaspora != $profile)
2827 $twitter = preg_replace("=https?://twitter.com/(.*)=ism", "$1", $profile);
2828 if ($twitter != $profile)
2834 $StatusnetHost = preg_replace("=https?://(.*)/user/(.*)=ism", "$1", $profile);
2835 if ($StatusnetHost != $profile) {
2836 $StatusnetUser = preg_replace("=https?://(.*)/user/(.*)=ism", "$2", $profile);
2837 if ($StatusnetUser != $profile) {
2838 $UserData = fetch_url("http://".$StatusnetHost."/api/users/show.json?user_id=".$StatusnetUser);
2839 $user = json_decode($UserData);
2841 $nick = $user->screen_name;
2846 // To-Do: look at the page if its really a pumpio site
2847 //if (!$nick == "") {
2848 // $pumpio = preg_replace("=https?://(.*)/(.*)/=ism", "$2", $profile."/");
2849 // if ($pumpio != $profile)
2851 // <div class="media" id="profile-block" data-profile-id="acct:kabniel@microca.st">
2856 q("UPDATE unique_contacts SET nick = '%s' WHERE url = '%s'",
2857 dbesc($nick), dbesc(normalise_link($profile)));
2864 function api_clean_plain_items($Text) {
2865 $include_entities = strtolower(x($_REQUEST,'include_entities')?$_REQUEST['include_entities']:"false");
2867 $Text = bb_CleanPictureLinks($Text);
2869 $URLSearchString = "^\[\]";
2871 $Text = preg_replace("/([!#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'$1$3',$Text);
2873 if ($include_entities == "true") {
2874 $Text = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'[url=$1]$1[/url]',$Text);
2877 $Text = preg_replace_callback("((.*?)\[class=(.*?)\](.*?)\[\/class\])ism","api_cleanup_share",$Text);
2881 function api_cleanup_share($shared) {
2882 if ($shared[2] != "type-link")
2885 if (!preg_match_all("/\[bookmark\=([^\]]*)\](.*?)\[\/bookmark\]/ism",$shared[3], $bookmark))
2891 if (isset($bookmark[2][0]))
2892 $title = $bookmark[2][0];
2894 if (isset($bookmark[1][0]))
2895 $link = $bookmark[1][0];
2897 if (strpos($shared[1],$title) !== false)
2900 if (strpos($shared[1],$link) !== false)
2903 $text = trim($shared[1]);
2905 //if (strlen($text) < strlen($title))
2906 if (($text == "") AND ($title != ""))
2907 $text .= "\n\n".trim($title);
2910 $text .= "\n".trim($link);
2912 return(trim($text));
2915 function api_best_nickname(&$contacts) {
2916 $best_contact = array();
2918 if (count($contact) == 0)
2921 foreach ($contacts AS $contact)
2922 if ($contact["network"] == "") {
2923 $contact["network"] = "dfrn";
2924 $best_contact = array($contact);
2927 if (sizeof($best_contact) == 0)
2928 foreach ($contacts AS $contact)
2929 if ($contact["network"] == "dfrn")
2930 $best_contact = array($contact);
2932 if (sizeof($best_contact) == 0)
2933 foreach ($contacts AS $contact)
2934 if ($contact["network"] == "dspr")
2935 $best_contact = array($contact);
2937 if (sizeof($best_contact) == 0)
2938 foreach ($contacts AS $contact)
2939 if ($contact["network"] == "stat")
2940 $best_contact = array($contact);
2942 if (sizeof($best_contact) == 0)
2943 foreach ($contacts AS $contact)
2944 if ($contact["network"] == "pump")
2945 $best_contact = array($contact);
2947 if (sizeof($best_contact) == 0)
2948 foreach ($contacts AS $contact)
2949 if ($contact["network"] == "twit")
2950 $best_contact = array($contact);
2952 if (sizeof($best_contact) == 1)
2953 $contacts = $best_contact;
2955 $contacts = array($contacts[0]);
2960 Not implemented by now:
2961 statuses/retweets_of_me
2966 account/update_location
2967 account/update_profile_background_image
2968 account/update_profile_image
2972 Not implemented in status.net:
2973 statuses/retweeted_to_me
2974 statuses/retweeted_by_me
2975 direct_messages/destroy
2977 account/update_delivery_device
2978 notifications/follow