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 `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);
1375 $sql_extra = ' AND `item`.`id` <= '.intval($max_id);
1377 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1378 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1379 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1380 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1381 FROM `item` INNER JOIN (SELECT `uri`,`parent` FROM `item` WHERE `id` = %d) AS `temp1`
1382 ON (`item`.`thr-parent` = `temp1`.`uri` AND `item`.`parent` = `temp1`.`parent`), `contact`
1383 WHERE `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1384 AND `item`.`uid` = %d AND `item`.`verb` = '%s' AND `contact`.`id` = `item`.`contact-id`
1385 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1386 AND `item`.`id`>%d $sql_extra
1387 ORDER BY `item`.`id` DESC LIMIT %d ,%d",
1388 intval($id), intval(api_user()),
1389 dbesc(ACTIVITY_POST),
1391 intval($start), intval($count)
1395 die(api_error($a, $type, t("There is no conversation with this id.")));
1397 $ret = api_format_items($r,$user_info);
1399 $data = array('$statuses' => $ret);
1400 return api_apply_template("timeline", $type, $data);
1402 api_register_func('api/conversation/show','api_conversation_show', true);
1408 function api_statuses_repeat(&$a, $type){
1411 if (api_user()===false) return false;
1413 $user_info = api_get_user($a);
1416 $id = intval($a->argv[3]);
1419 $id = intval($_REQUEST["id"]);
1423 $id = intval($a->argv[4]);
1425 logger('API: api_statuses_repeat: '.$id);
1427 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`, `contact`.`nick` as `reply_author`,
1428 `contact`.`name`, `contact`.`photo` as `reply_photo`, `contact`.`url` as `reply_url`, `contact`.`rel`,
1429 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1430 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1431 FROM `item`, `contact`
1432 WHERE `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1433 AND `contact`.`id` = `item`.`contact-id`
1434 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1436 AND `item`.`id`=%d",
1440 if ($r[0]['body'] != "") {
1441 if (!intval(get_config('system','old_share'))) {
1442 if (strpos($r[0]['body'], "[/share]") !== false) {
1443 $pos = strpos($r[0]['body'], "[share");
1444 $post = substr($r[0]['body'], $pos);
1446 $post = share_header($r[0]['author-name'], $r[0]['author-link'], $r[0]['author-avatar'], $r[0]['guid'], $r[0]['created'], $r[0]['plink']);
1448 $post .= $r[0]['body'];
1449 $post .= "[/share]";
1451 $_REQUEST['body'] = $post;
1453 $_REQUEST['body'] = html_entity_decode("♲ ", ENT_QUOTES, 'UTF-8')."[url=".$r[0]['reply_url']."]".$r[0]['reply_author']."[/url] \n".$r[0]['body'];
1455 $_REQUEST['profile_uid'] = api_user();
1456 $_REQUEST['type'] = 'wall';
1457 $_REQUEST['api_source'] = true;
1459 if (!x($_REQUEST, "source"))
1460 $_REQUEST["source"] = api_source();
1462 require_once('mod/item.php');
1466 // this should output the last post (the one we just posted).
1468 return(api_status_show($a,$type));
1470 api_register_func('api/statuses/retweet','api_statuses_repeat', true);
1475 function api_statuses_destroy(&$a, $type){
1476 if (api_user()===false) return false;
1478 $user_info = api_get_user($a);
1481 $id = intval($a->argv[3]);
1484 $id = intval($_REQUEST["id"]);
1488 $id = intval($a->argv[4]);
1490 logger('API: api_statuses_destroy: '.$id);
1492 $ret = api_statuses_show($a, $type);
1494 require_once('include/items.php');
1495 drop_item($id, false);
1499 api_register_func('api/statuses/destroy','api_statuses_destroy', true);
1503 * http://developer.twitter.com/doc/get/statuses/mentions
1506 function api_statuses_mentions(&$a, $type){
1507 if (api_user()===false) return false;
1509 unset($_REQUEST["user_id"]);
1510 unset($_GET["user_id"]);
1512 unset($_REQUEST["screen_name"]);
1513 unset($_GET["screen_name"]);
1515 $user_info = api_get_user($a);
1516 // get last newtork messages
1520 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1521 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1522 if ($page<0) $page=0;
1523 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1524 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1525 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1527 $start = $page*$count;
1529 // Ugly code - should be changed
1530 $myurl = $a->get_baseurl() . '/profile/'. $a->user['nickname'];
1531 $myurl = substr($myurl,strpos($myurl,'://')+3);
1532 //$myurl = str_replace(array('www.','.'),array('','\\.'),$myurl);
1533 $myurl = str_replace('www.','',$myurl);
1534 $diasp_url = str_replace('/profile/','/u/',$myurl);
1537 $sql_extra = ' AND `item`.`id` <= '.intval($max_id);
1539 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1540 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1541 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1542 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1543 FROM `item`, `contact`
1544 WHERE `item`.`uid` = %d AND `verb` = '%s'
1545 AND NOT (`item`.`author-link` IN ('https://%s', 'http://%s'))
1546 AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1547 AND `contact`.`id` = `item`.`contact-id`
1548 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1549 AND `item`.`parent` IN (SELECT `iid` from thread where uid = %d AND `mention` AND !`ignored`)
1552 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1554 dbesc(ACTIVITY_POST),
1555 dbesc(protect_sprintf($myurl)),
1556 dbesc(protect_sprintf($myurl)),
1559 intval($start), intval($count)
1562 $ret = api_format_items($r,$user_info);
1565 $data = array('$statuses' => $ret);
1569 $data = api_rss_extra($a, $data, $user_info);
1572 $as = api_format_as($a, $ret, $user_info);
1573 $as["title"] = $a->config['sitename']." Mentions";
1574 $as['link']['url'] = $a->get_baseurl()."/";
1579 return api_apply_template("timeline", $type, $data);
1581 api_register_func('api/statuses/mentions','api_statuses_mentions', true);
1582 api_register_func('api/statuses/replies','api_statuses_mentions', true);
1585 function api_statuses_user_timeline(&$a, $type){
1586 if (api_user()===false) return false;
1588 $user_info = api_get_user($a);
1589 // get last network messages
1591 logger("api_statuses_user_timeline: api_user: ". api_user() .
1592 "\nuser_info: ".print_r($user_info, true) .
1593 "\n_REQUEST: ".print_r($_REQUEST, true),
1597 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1598 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1599 if ($page<0) $page=0;
1600 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1601 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1602 $exclude_replies = (x($_REQUEST,'exclude_replies')?1:0);
1603 $conversation_id = (x($_REQUEST,'conversation_id')?$_REQUEST['conversation_id']:0);
1605 $start = $page*$count;
1608 if ($user_info['self']==1)
1609 $sql_extra .= " AND `item`.`wall` = 1 ";
1611 if ($exclude_replies > 0)
1612 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
1613 if ($conversation_id > 0)
1614 $sql_extra .= ' AND `item`.`parent` = '.intval($conversation_id);
1616 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1617 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1618 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1619 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1620 FROM `item`, `contact`
1621 WHERE `item`.`uid` = %d AND `verb` = '%s'
1622 AND `item`.`contact-id` = %d
1623 AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1624 AND `contact`.`id` = `item`.`contact-id`
1625 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1628 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1630 dbesc(ACTIVITY_POST),
1631 intval($user_info['cid']),
1633 intval($start), intval($count)
1636 $ret = api_format_items($r,$user_info, true);
1638 $data = array('$statuses' => $ret);
1642 $data = api_rss_extra($a, $data, $user_info);
1645 return api_apply_template("timeline", $type, $data);
1648 api_register_func('api/statuses/user_timeline','api_statuses_user_timeline', true);
1652 * Star/unstar an item
1653 * param: id : id of the item
1655 * api v1 : https://web.archive.org/web/20131019055350/https://dev.twitter.com/docs/api/1/post/favorites/create/%3Aid
1657 function api_favorites_create_destroy(&$a, $type){
1658 if (api_user()===false) return false;
1660 # for versioned api.
1661 # TODO: we need a better global soluton
1663 if ($a->argv[1]=="1.1") $action_argv_id=3;
1665 if ($a->argc<=$action_argv_id) die(api_error($a, $type, t("Invalid request.")));
1666 $action = str_replace(".".$type,"",$a->argv[$action_argv_id]);
1667 if ($a->argc==$action_argv_id+2) {
1668 $itemid = intval($a->argv[$action_argv_id+1]);
1670 $itemid = intval($_REQUEST['id']);
1673 $item = q("SELECT * FROM item WHERE id=%d AND uid=%d",
1674 $itemid, api_user());
1676 if ($item===false || count($item)==0) die(api_error($a, $type, t("Invalid item.")));
1680 $item[0]['starred']=1;
1683 $item[0]['starred']=0;
1686 die(api_error($a, $type, t("Invalid action. ".$action)));
1688 $r = q("UPDATE item SET starred=%d WHERE id=%d AND uid=%d",
1689 $item[0]['starred'], $itemid, api_user());
1691 q("UPDATE thread SET starred=%d WHERE iid=%d AND uid=%d",
1692 $item[0]['starred'], $itemid, api_user());
1694 if ($r===false) die(api_error($a, $type, t("DB error")));
1697 $user_info = api_get_user($a);
1698 $rets = api_format_items($item,$user_info);
1701 $data = array('$status' => $ret);
1705 $data = api_rss_extra($a, $data, $user_info);
1708 return api_apply_template("status", $type, $data);
1711 api_register_func('api/favorites/create', 'api_favorites_create_destroy', true);
1712 api_register_func('api/favorites/destroy', 'api_favorites_create_destroy', true);
1714 function api_favorites(&$a, $type){
1717 if (api_user()===false) return false;
1719 $called_api= array();
1721 $user_info = api_get_user($a);
1723 // in friendica starred item are private
1724 // return favorites only for self
1725 logger('api_favorites: self:' . $user_info['self']);
1727 if ($user_info['self']==0) {
1733 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1734 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1735 $count = (x($_GET,'count')?$_GET['count']:20);
1736 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1737 if ($page<0) $page=0;
1739 $start = $page*$count;
1742 $sql_extra .= ' AND `item`.`id` <= '.intval($max_id);
1744 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1745 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1746 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1747 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1748 FROM `item`, `contact`
1749 WHERE `item`.`uid` = %d
1750 AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1751 AND `item`.`starred` = 1
1752 AND `contact`.`id` = `item`.`contact-id`
1753 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1756 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1759 intval($start), intval($count)
1762 $ret = api_format_items($r,$user_info);
1766 $data = array('$statuses' => $ret);
1770 $data = api_rss_extra($a, $data, $user_info);
1773 return api_apply_template("timeline", $type, $data);
1776 api_register_func('api/favorites','api_favorites', true);
1781 function api_format_as($a, $ret, $user_info) {
1784 $as['title'] = $a->config['sitename']." Public Timeline";
1786 foreach ($ret as $item) {
1787 $singleitem["actor"]["displayName"] = $item["user"]["name"];
1788 $singleitem["actor"]["id"] = $item["user"]["contact_url"];
1789 $avatar[0]["url"] = $item["user"]["profile_image_url"];
1790 $avatar[0]["rel"] = "avatar";
1791 $avatar[0]["type"] = "";
1792 $avatar[0]["width"] = 96;
1793 $avatar[0]["height"] = 96;
1794 $avatar[1]["url"] = $item["user"]["profile_image_url"];
1795 $avatar[1]["rel"] = "avatar";
1796 $avatar[1]["type"] = "";
1797 $avatar[1]["width"] = 48;
1798 $avatar[1]["height"] = 48;
1799 $avatar[2]["url"] = $item["user"]["profile_image_url"];
1800 $avatar[2]["rel"] = "avatar";
1801 $avatar[2]["type"] = "";
1802 $avatar[2]["width"] = 24;
1803 $avatar[2]["height"] = 24;
1804 $singleitem["actor"]["avatarLinks"] = $avatar;
1806 $singleitem["actor"]["image"]["url"] = $item["user"]["profile_image_url"];
1807 $singleitem["actor"]["image"]["rel"] = "avatar";
1808 $singleitem["actor"]["image"]["type"] = "";
1809 $singleitem["actor"]["image"]["width"] = 96;
1810 $singleitem["actor"]["image"]["height"] = 96;
1811 $singleitem["actor"]["type"] = "person";
1812 $singleitem["actor"]["url"] = $item["person"]["contact_url"];
1813 $singleitem["actor"]["statusnet:profile_info"]["local_id"] = $item["user"]["id"];
1814 $singleitem["actor"]["statusnet:profile_info"]["following"] = $item["user"]["following"] ? "true" : "false";
1815 $singleitem["actor"]["statusnet:profile_info"]["blocking"] = "false";
1816 $singleitem["actor"]["contact"]["preferredUsername"] = $item["user"]["screen_name"];
1817 $singleitem["actor"]["contact"]["displayName"] = $item["user"]["name"];
1818 $singleitem["actor"]["contact"]["addresses"] = "";
1820 $singleitem["body"] = $item["text"];
1821 $singleitem["object"]["displayName"] = $item["text"];
1822 $singleitem["object"]["id"] = $item["url"];
1823 $singleitem["object"]["type"] = "note";
1824 $singleitem["object"]["url"] = $item["url"];
1825 //$singleitem["context"] =;
1826 $singleitem["postedTime"] = date("c", strtotime($item["published"]));
1827 $singleitem["provider"]["objectType"] = "service";
1828 $singleitem["provider"]["displayName"] = "Test";
1829 $singleitem["provider"]["url"] = "http://test.tld";
1830 $singleitem["title"] = $item["text"];
1831 $singleitem["verb"] = "post";
1832 $singleitem["statusnet:notice_info"]["local_id"] = $item["id"];
1833 $singleitem["statusnet:notice_info"]["source"] = $item["source"];
1834 $singleitem["statusnet:notice_info"]["favorite"] = "false";
1835 $singleitem["statusnet:notice_info"]["repeated"] = "false";
1836 //$singleitem["original"] = $item;
1837 $items[] = $singleitem;
1839 $as['items'] = $items;
1840 $as['link']['url'] = $a->get_baseurl()."/".$user_info["screen_name"]."/all";
1841 $as['link']['rel'] = "alternate";
1842 $as['link']['type'] = "text/html";
1846 function api_format_messages($item, $recipient, $sender) {
1847 // standard meta information
1849 'id' => $item['id'],
1850 'sender_id' => $sender['id'] ,
1852 'recipient_id' => $recipient['id'],
1853 'created_at' => api_date($item['created']),
1854 'sender_screen_name' => $sender['screen_name'],
1855 'recipient_screen_name' => $recipient['screen_name'],
1856 'sender' => $sender,
1857 'recipient' => $recipient,
1860 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1861 unset($ret["sender"]["uid"]);
1862 unset($ret["sender"]["self"]);
1863 unset($ret["recipient"]["uid"]);
1864 unset($ret["recipient"]["self"]);
1866 //don't send title to regular StatusNET requests to avoid confusing these apps
1867 if (x($_GET, 'getText')) {
1868 $ret['title'] = $item['title'] ;
1869 if ($_GET["getText"] == "html") {
1870 $ret['text'] = bbcode($item['body'], false, false);
1872 elseif ($_GET["getText"] == "plain") {
1873 //$ret['text'] = html2plain(bbcode($item['body'], false, false, true), 0);
1874 $ret['text'] = trim(html2plain(bbcode(api_clean_plain_items($item['body']), false, false, 2, true), 0));
1878 $ret['text'] = $item['title']."\n".html2plain(bbcode(api_clean_plain_items($item['body']), false, false, 2, true), 0);
1880 if (isset($_GET["getUserObjects"]) && $_GET["getUserObjects"] == "false") {
1881 unset($ret['sender']);
1882 unset($ret['recipient']);
1888 function api_convert_item($item) {
1890 $body = $item['body'];
1891 $attachments = api_get_attachments($body);
1893 // Workaround for ostatus messages where the title is identically to the body
1894 $html = bbcode(api_clean_plain_items($body), false, false, 2, true);
1895 $statusbody = trim(html2plain($html, 0));
1897 // handle data: images
1898 $statusbody = api_format_items_embeded_images($item,$statusbody);
1900 $statustitle = trim($item['title']);
1902 if (($statustitle != '') and (strpos($statusbody, $statustitle) !== false))
1903 $statustext = trim($statusbody);
1905 $statustext = trim($statustitle."\n\n".$statusbody);
1907 if (($item["network"] == NETWORK_FEED) and (strlen($statustext)> 1000))
1908 $statustext = substr($statustext, 0, 1000)."... \n".$item["plink"];
1910 $statushtml = trim(bbcode($body, false, false));
1912 if ($item['title'] != "")
1913 $statushtml = "<h4>".bbcode($item['title'])."</h4>\n".$statushtml;
1915 $entities = api_get_entitities($statustext, $body);
1917 return(array("text" => $statustext, "html" => $statushtml, "attachments" => $attachments, "entities" => $entities));
1920 function api_get_attachments(&$body) {
1923 $text = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $text);
1925 $URLSearchString = "^\[\]";
1926 $ret = preg_match_all("/\[img\]([$URLSearchString]*)\[\/img\]/ism", $text, $images);
1931 $attachments = array();
1933 foreach ($images[1] AS $image) {
1934 $imagedata = get_photo_info($image);
1937 $attachments[] = array("url" => $image, "mimetype" => $imagedata["mime"], "size" => $imagedata["size"]);
1940 if (strstr($_SERVER['HTTP_USER_AGENT'], "AndStatus"))
1941 foreach ($images[0] AS $orig)
1942 $body = str_replace($orig, "", $body);
1944 return $attachments;
1947 function api_get_entitities(&$text, $bbcode) {
1950 * Links at the first character of the post
1955 $include_entities = strtolower(x($_REQUEST,'include_entities')?$_REQUEST['include_entities']:"false");
1957 if ($include_entities != "true") {
1958 require_once("mod/proxy.php");
1960 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
1962 foreach ($images[1] AS $image) {
1963 $replace = proxy_url($image);
1964 $text = str_replace($image, $replace, $text);
1969 $bbcode = bb_CleanPictureLinks($bbcode);
1971 // Change pure links in text to bbcode uris
1972 $bbcode = preg_replace("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", '$1[url=$2]$2[/url]', $bbcode);
1974 $entities = array();
1975 $entities["hashtags"] = array();
1976 $entities["symbols"] = array();
1977 $entities["urls"] = array();
1978 $entities["user_mentions"] = array();
1980 $URLSearchString = "^\[\]";
1982 $bbcode = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'#$2',$bbcode);
1984 $bbcode = preg_replace("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism",'[url=$1]$2[/url]',$bbcode);
1985 //$bbcode = preg_replace("/\[url\](.*?)\[\/url\]/ism",'[url=$1]$1[/url]',$bbcode);
1986 $bbcode = preg_replace("/\[video\](.*?)\[\/video\]/ism",'[url=$1]$1[/url]',$bbcode);
1988 $bbcode = preg_replace("/\[youtube\]([A-Za-z0-9\-_=]+)(.*?)\[\/youtube\]/ism",
1989 '[url=https://www.youtube.com/watch?v=$1]https://www.youtube.com/watch?v=$1[/url]', $bbcode);
1990 $bbcode = preg_replace("/\[youtube\](.*?)\[\/youtube\]/ism",'[url=$1]$1[/url]',$bbcode);
1992 $bbcode = preg_replace("/\[vimeo\]([0-9]+)(.*?)\[\/vimeo\]/ism",
1993 '[url=https://vimeo.com/$1]https://vimeo.com/$1[/url]', $bbcode);
1994 $bbcode = preg_replace("/\[vimeo\](.*?)\[\/vimeo\]/ism",'[url=$1]$1[/url]',$bbcode);
1996 $bbcode = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $bbcode);
1998 //preg_match_all("/\[url\]([$URLSearchString]*)\[\/url\]/ism", $bbcode, $urls1);
1999 preg_match_all("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $bbcode, $urls);
2001 $ordered_urls = array();
2002 foreach ($urls[1] AS $id=>$url) {
2003 //$start = strpos($text, $url, $offset);
2004 $start = iconv_strpos($text, $url, 0, "UTF-8");
2005 if (!($start === false))
2006 $ordered_urls[$start] = array("url" => $url, "title" => $urls[2][$id]);
2009 ksort($ordered_urls);
2012 //foreach ($urls[1] AS $id=>$url) {
2013 foreach ($ordered_urls AS $url) {
2014 if ((substr($url["title"], 0, 7) != "http://") AND (substr($url["title"], 0, 8) != "https://") AND
2015 !strpos($url["title"], "http://") AND !strpos($url["title"], "https://"))
2016 $display_url = $url["title"];
2018 $display_url = str_replace(array("http://www.", "https://www."), array("", ""), $url["url"]);
2019 $display_url = str_replace(array("http://", "https://"), array("", ""), $display_url);
2021 if (strlen($display_url) > 26)
2022 $display_url = substr($display_url, 0, 25)."…";
2025 //$start = strpos($text, $url, $offset);
2026 $start = iconv_strpos($text, $url["url"], $offset, "UTF-8");
2027 if (!($start === false)) {
2028 $entities["urls"][] = array("url" => $url["url"],
2029 "expanded_url" => $url["url"],
2030 "display_url" => $display_url,
2031 "indices" => array($start, $start+strlen($url["url"])));
2032 $offset = $start + 1;
2036 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2037 $ordered_images = array();
2038 foreach ($images[1] AS $image) {
2039 //$start = strpos($text, $url, $offset);
2040 $start = iconv_strpos($text, $image, 0, "UTF-8");
2041 if (!($start === false))
2042 $ordered_images[$start] = $image;
2044 //$entities["media"] = array();
2047 foreach ($ordered_images AS $url) {
2048 $display_url = str_replace(array("http://www.", "https://www."), array("", ""), $url);
2049 $display_url = str_replace(array("http://", "https://"), array("", ""), $display_url);
2051 if (strlen($display_url) > 26)
2052 $display_url = substr($display_url, 0, 25)."…";
2054 $start = iconv_strpos($text, $url, $offset, "UTF-8");
2055 if (!($start === false)) {
2056 $image = get_photo_info($url);
2058 // If image cache is activated, then use the following sizes:
2059 // thumb (150), small (340), medium (600) and large (1024)
2060 if (!get_config("system", "proxy_disabled")) {
2061 require_once("mod/proxy.php");
2062 $media_url = proxy_url($url);
2065 $scale = scale_image($image[0], $image[1], 150);
2066 $sizes["thumb"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2068 if (($image[0] > 150) OR ($image[1] > 150)) {
2069 $scale = scale_image($image[0], $image[1], 340);
2070 $sizes["small"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2073 $scale = scale_image($image[0], $image[1], 600);
2074 $sizes["medium"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2076 if (($image[0] > 600) OR ($image[1] > 600)) {
2077 $scale = scale_image($image[0], $image[1], 1024);
2078 $sizes["large"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2082 $sizes["medium"] = array("w" => $image[0], "h" => $image[1], "resize" => "fit");
2085 $entities["media"][] = array(
2087 "id_str" => (string)$start+1,
2088 "indices" => array($start, $start+strlen($url)),
2089 "media_url" => normalise_link($media_url),
2090 "media_url_https" => $media_url,
2092 "display_url" => $display_url,
2093 "expanded_url" => $url,
2097 $offset = $start + 1;
2103 function api_format_items_embeded_images($item, $text){
2105 $text = preg_replace_callback(
2106 "|data:image/([^;]+)[^=]+=*|m",
2107 function($match) use ($a, $item) {
2108 return $a->get_baseurl()."/display/".$item['guid'];
2114 function api_format_items($r,$user_info, $filter_user = false) {
2119 foreach($r as $item) {
2120 api_share_as_retweet($item);
2122 localize_item($item);
2123 $status_user = api_item_get_user($a,$item);
2125 // Look if the posts are matching if they should be filtered by user id
2126 if ($filter_user AND ($status_user["id"] != $user_info["id"]))
2129 if ($item['thr-parent'] != $item['uri']) {
2130 $r = q("SELECT id FROM item WHERE uid=%d AND uri='%s' LIMIT 1",
2132 dbesc($item['thr-parent']));
2134 $in_reply_to_status_id = intval($r[0]['id']);
2136 $in_reply_to_status_id = intval($item['parent']);
2138 $in_reply_to_status_id_str = (string) intval($item['parent']);
2140 $in_reply_to_screen_name = NULL;
2141 $in_reply_to_user_id = NULL;
2142 $in_reply_to_user_id_str = NULL;
2144 $r = q("SELECT `author-link` FROM item WHERE uid=%d AND id=%d LIMIT 1",
2146 intval($in_reply_to_status_id));
2148 $r = q("SELECT * FROM unique_contacts WHERE `url` = '%s'", dbesc(normalise_link($r[0]['author-link'])));
2151 if ($r[0]['nick'] == "")
2152 $r[0]['nick'] = api_get_nick($r[0]["url"]);
2154 $in_reply_to_screen_name = (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']);
2155 $in_reply_to_user_id = intval($r[0]['id']);
2156 $in_reply_to_user_id_str = (string) intval($r[0]['id']);
2160 $in_reply_to_screen_name = NULL;
2161 $in_reply_to_user_id = NULL;
2162 $in_reply_to_status_id = NULL;
2163 $in_reply_to_user_id_str = NULL;
2164 $in_reply_to_status_id_str = NULL;
2167 $converted = api_convert_item($item);
2170 'text' => $converted["text"],
2171 'truncated' => False,
2172 'created_at'=> api_date($item['created']),
2173 'in_reply_to_status_id' => $in_reply_to_status_id,
2174 'in_reply_to_status_id_str' => $in_reply_to_status_id_str,
2175 'source' => (($item['app']) ? $item['app'] : 'web'),
2176 'id' => intval($item['id']),
2177 'id_str' => (string) intval($item['id']),
2178 'in_reply_to_user_id' => $in_reply_to_user_id,
2179 'in_reply_to_user_id_str' => $in_reply_to_user_id_str,
2180 'in_reply_to_screen_name' => $in_reply_to_screen_name,
2182 'favorited' => $item['starred'] ? true : false,
2183 'user' => $status_user ,
2184 //'entities' => NULL,
2185 'statusnet_html' => $converted["html"],
2186 'statusnet_conversation_id' => $item['parent'],
2189 if (count($converted["attachments"]) > 0)
2190 $status["attachments"] = $converted["attachments"];
2192 if (count($converted["entities"]) > 0)
2193 $status["entities"] = $converted["entities"];
2195 if (($item['item_network'] != "") AND ($status["source"] == 'web'))
2196 $status["source"] = network_to_name($item['item_network']);
2197 else if (($item['item_network'] != "") AND (network_to_name($item['item_network']) != $status["source"]))
2198 $status["source"] = trim($status["source"].' ('.network_to_name($item['item_network']).')');
2201 // Retweets are only valid for top postings
2202 // It doesn't work reliable with the link if its a feed
2203 $IsRetweet = ($item['owner-link'] != $item['author-link']);
2205 $IsRetweet = (($item['owner-name'] != $item['author-name']) OR ($item['owner-avatar'] != $item['author-avatar']));
2207 if ($IsRetweet AND ($item["id"] == $item["parent"])) {
2208 $retweeted_status = $status;
2209 $retweeted_status["user"] = api_get_user($a,$item["author-link"]);
2211 $status["retweeted_status"] = $retweeted_status;
2214 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2215 unset($status["user"]["uid"]);
2216 unset($status["user"]["self"]);
2218 // 'geo' => array('type' => 'Point',
2219 // 'coordinates' => array((float) $notice->lat,
2220 // (float) $notice->lon));
2228 function api_account_rate_limit_status(&$a,$type) {
2231 'reset_time_in_seconds' => strtotime('now + 1 hour'),
2232 'remaining_hits' => (string) 150,
2233 'hourly_limit' => (string) 150,
2234 'reset_time' => api_date(datetime_convert('UTC','UTC','now + 1 hour',ATOM_TIME)),
2237 $hash['resettime_in_seconds'] = $hash['reset_time_in_seconds'];
2239 return api_apply_template('ratelimit', $type, array('$hash' => $hash));
2242 api_register_func('api/account/rate_limit_status','api_account_rate_limit_status',true);
2244 function api_help_test(&$a,$type) {
2251 return api_apply_template('test', $type, array("$ok" => $ok));
2254 api_register_func('api/help/test','api_help_test',false);
2256 function api_lists(&$a,$type) {
2261 api_register_func('api/lists','api_lists',true);
2263 function api_lists_list(&$a,$type) {
2268 api_register_func('api/lists/list','api_lists_list',true);
2271 * https://dev.twitter.com/docs/api/1/get/statuses/friends
2272 * This function is deprecated by Twitter
2273 * returns: json, xml
2275 function api_statuses_f(&$a, $type, $qtype) {
2276 if (api_user()===false) return false;
2277 $user_info = api_get_user($a);
2279 if (x($_GET,'cursor') && $_GET['cursor']=='undefined'){
2280 /* this is to stop Hotot to load friends multiple times
2281 * I'm not sure if I'm missing return something or
2282 * is a bug in hotot. Workaround, meantime
2286 return array('$users' => $ret);*/
2290 if($qtype == 'friends')
2291 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
2292 if($qtype == 'followers')
2293 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
2295 // friends and followers only for self
2296 if ($user_info['self'] == 0)
2297 $sql_extra = " AND false ";
2299 $r = q("SELECT `nurl` FROM `contact` WHERE `uid` = %d AND `self` = 0 AND `blocked` = 0 AND `pending` = 0 $sql_extra",
2304 foreach($r as $cid){
2305 $user = api_get_user($a, $cid['nurl']);
2306 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2307 unset($user["uid"]);
2308 unset($user["self"]);
2314 return array('$users' => $ret);
2317 function api_statuses_friends(&$a, $type){
2318 $data = api_statuses_f($a,$type,"friends");
2319 if ($data===false) return false;
2320 return api_apply_template("friends", $type, $data);
2322 function api_statuses_followers(&$a, $type){
2323 $data = api_statuses_f($a,$type,"followers");
2324 if ($data===false) return false;
2325 return api_apply_template("friends", $type, $data);
2327 api_register_func('api/statuses/friends','api_statuses_friends',true);
2328 api_register_func('api/statuses/followers','api_statuses_followers',true);
2335 function api_statusnet_config(&$a,$type) {
2336 $name = $a->config['sitename'];
2337 $server = $a->get_hostname();
2338 $logo = $a->get_baseurl() . '/images/friendica-64.png';
2339 $email = $a->config['admin_email'];
2340 $closed = (($a->config['register_policy'] == REGISTER_CLOSED) ? 'true' : 'false');
2341 $private = (($a->config['system']['block_public']) ? 'true' : 'false');
2342 $textlimit = (string) (($a->config['max_import_size']) ? $a->config['max_import_size'] : 200000);
2343 if($a->config['api_import_size'])
2344 $texlimit = string($a->config['api_import_size']);
2345 $ssl = (($a->config['system']['have_ssl']) ? 'true' : 'false');
2346 $sslserver = (($ssl === 'true') ? str_replace('http:','https:',$a->get_baseurl()) : '');
2349 'site' => array('name' => $name,'server' => $server, 'theme' => 'default', 'path' => '',
2350 'logo' => $logo, 'fancy' => true, 'language' => 'en', 'email' => $email, 'broughtby' => '',
2351 'broughtbyurl' => '', 'timezone' => 'UTC', 'closed' => $closed, 'inviteonly' => false,
2352 'private' => $private, 'textlimit' => $textlimit, 'sslserver' => $sslserver, 'ssl' => $ssl,
2353 'shorturllength' => '30',
2354 'friendica' => array(
2355 'FRIENDICA_PLATFORM' => FRIENDICA_PLATFORM,
2356 'FRIENDICA_VERSION' => FRIENDICA_VERSION,
2357 'DFRN_PROTOCOL_VERSION' => DFRN_PROTOCOL_VERSION,
2358 'DB_UPDATE_VERSION' => DB_UPDATE_VERSION
2363 return api_apply_template('config', $type, array('$config' => $config));
2366 api_register_func('api/statusnet/config','api_statusnet_config',false);
2368 function api_statusnet_version(&$a,$type) {
2372 if($type === 'xml') {
2373 header("Content-type: application/xml");
2374 echo '<?xml version="1.0" encoding="UTF-8"?>' . "\r\n" . '<version>0.9.7</version>' . "\r\n";
2377 elseif($type === 'json') {
2378 header("Content-type: application/json");
2383 api_register_func('api/statusnet/version','api_statusnet_version',false);
2386 function api_ff_ids(&$a,$type,$qtype) {
2390 $user_info = api_get_user($a);
2392 if($qtype == 'friends')
2393 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
2394 if($qtype == 'followers')
2395 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
2397 if (!$user_info["self"])
2398 $sql_extra = " AND false ";
2400 $stringify_ids = (x($_REQUEST,'stringify_ids')?$_REQUEST['stringify_ids']:false);
2402 $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",
2408 if($type === 'xml') {
2409 header("Content-type: application/xml");
2410 echo '<?xml version="1.0" encoding="UTF-8"?>' . "\r\n" . '<ids>' . "\r\n";
2412 echo '<id>' . $rr['id'] . '</id>' . "\r\n";
2413 echo '</ids>' . "\r\n";
2416 elseif($type === 'json') {
2418 header("Content-type: application/json");
2423 $ret[] = intval($rr['id']);
2425 echo json_encode($ret);
2431 function api_friends_ids(&$a,$type) {
2432 api_ff_ids($a,$type,'friends');
2434 function api_followers_ids(&$a,$type) {
2435 api_ff_ids($a,$type,'followers');
2437 api_register_func('api/friends/ids','api_friends_ids',true);
2438 api_register_func('api/followers/ids','api_followers_ids',true);
2441 function api_direct_messages_new(&$a, $type) {
2442 if (api_user()===false) return false;
2444 if (!x($_POST, "text") OR (!x($_POST,"screen_name") AND !x($_POST,"user_id"))) return;
2446 $sender = api_get_user($a);
2448 require_once("include/message.php");
2450 if ($_POST['screen_name']) {
2451 $r = q("SELECT `id`, `nurl`, `network` FROM `contact` WHERE `uid`=%d AND `nick`='%s'",
2453 dbesc($_POST['screen_name']));
2455 // Selecting the id by priority, friendica first
2456 api_best_nickname($r);
2458 $recipient = api_get_user($a, $r[0]['nurl']);
2460 $recipient = api_get_user($a, $_POST['user_id']);
2464 if (x($_REQUEST,'replyto')) {
2465 $r = q('SELECT `parent-uri`, `title` FROM `mail` WHERE `uid`=%d AND `id`=%d',
2467 intval($_REQUEST['replyto']));
2468 $replyto = $r[0]['parent-uri'];
2469 $sub = $r[0]['title'];
2472 if (x($_REQUEST,'title')) {
2473 $sub = $_REQUEST['title'];
2476 $sub = ((strlen($_POST['text'])>10)?substr($_POST['text'],0,10)."...":$_POST['text']);
2480 $id = send_message($recipient['cid'], $_POST['text'], $sub, $replyto);
2483 $r = q("SELECT * FROM `mail` WHERE id=%d", intval($id));
2484 $ret = api_format_messages($r[0], $recipient, $sender);
2487 $ret = array("error"=>$id);
2490 $data = Array('$messages'=>$ret);
2495 $data = api_rss_extra($a, $data, $user_info);
2498 return api_apply_template("direct_messages", $type, $data);
2501 api_register_func('api/direct_messages/new','api_direct_messages_new',true);
2503 function api_direct_messages_box(&$a, $type, $box) {
2504 if (api_user()===false) return false;
2508 $count = (x($_GET,'count')?$_GET['count']:20);
2509 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
2510 if ($page<0) $page=0;
2512 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
2513 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
2515 $user_id = (x($_REQUEST,'user_id')?$_REQUEST['user_id']:"");
2516 $screen_name = (x($_REQUEST,'screen_name')?$_REQUEST['screen_name']:"");
2519 unset($_REQUEST["user_id"]);
2520 unset($_GET["user_id"]);
2522 unset($_REQUEST["screen_name"]);
2523 unset($_GET["screen_name"]);
2525 $user_info = api_get_user($a);
2526 //$profile_url = $a->get_baseurl() . '/profile/' . $a->user['nickname'];
2527 $profile_url = $user_info["url"];
2531 $start = $page*$count;
2534 if ($box=="sentbox") {
2535 $sql_extra = "`mail`.`from-url`='".dbesc( $profile_url )."'";
2537 elseif ($box=="conversation") {
2538 $sql_extra = "`mail`.`parent-uri`='".dbesc( $_GET["uri"] ) ."'";
2540 elseif ($box=="all") {
2541 $sql_extra = "true";
2543 elseif ($box=="inbox") {
2544 $sql_extra = "`mail`.`from-url`!='".dbesc( $profile_url )."'";
2548 $sql_extra .= ' AND `mail`.`id` <= '.intval($max_id);
2550 if ($user_id !="") {
2551 $sql_extra .= ' AND `mail`.`contact-id` = ' . intval($user_id);
2553 elseif($screen_name !=""){
2554 $sql_extra .= " AND `contact`.`nick` = '" . dbesc($screen_name). "'";
2557 $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",
2560 intval($start), intval($count)
2565 foreach($r as $item) {
2566 if ($box == "inbox" || $item['from-url'] != $profile_url){
2567 $recipient = $user_info;
2568 $sender = api_get_user($a,normalise_link($item['contact-url']));
2570 elseif ($box == "sentbox" || $item['from-url'] == $profile_url){
2571 $recipient = api_get_user($a,normalise_link($item['contact-url']));
2572 $sender = $user_info;
2575 $ret[]=api_format_messages($item, $recipient, $sender);
2579 $data = array('$messages' => $ret);
2583 $data = api_rss_extra($a, $data, $user_info);
2586 return api_apply_template("direct_messages", $type, $data);
2590 function api_direct_messages_sentbox(&$a, $type){
2591 return api_direct_messages_box($a, $type, "sentbox");
2593 function api_direct_messages_inbox(&$a, $type){
2594 return api_direct_messages_box($a, $type, "inbox");
2596 function api_direct_messages_all(&$a, $type){
2597 return api_direct_messages_box($a, $type, "all");
2599 function api_direct_messages_conversation(&$a, $type){
2600 return api_direct_messages_box($a, $type, "conversation");
2602 api_register_func('api/direct_messages/conversation','api_direct_messages_conversation',true);
2603 api_register_func('api/direct_messages/all','api_direct_messages_all',true);
2604 api_register_func('api/direct_messages/sent','api_direct_messages_sentbox',true);
2605 api_register_func('api/direct_messages','api_direct_messages_inbox',true);
2609 function api_oauth_request_token(&$a, $type){
2611 $oauth = new FKOAuth1();
2612 $r = $oauth->fetch_request_token(OAuthRequest::from_request());
2613 }catch(Exception $e){
2614 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage()); killme();
2619 function api_oauth_access_token(&$a, $type){
2621 $oauth = new FKOAuth1();
2622 $r = $oauth->fetch_access_token(OAuthRequest::from_request());
2623 }catch(Exception $e){
2624 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage()); killme();
2630 api_register_func('api/oauth/request_token', 'api_oauth_request_token', false);
2631 api_register_func('api/oauth/access_token', 'api_oauth_access_token', false);
2634 function api_fr_photos_list(&$a,$type) {
2635 if (api_user()===false) return false;
2636 $r = q("select distinct `resource-id` from photo where uid = %d and album != 'Contact Photos' ",
2637 intval(local_user())
2642 $ret[] = $rr['resource-id'];
2643 header("Content-type: application/json");
2644 echo json_encode($ret);
2649 function api_fr_photo_detail(&$a,$type) {
2650 if (api_user()===false) return false;
2651 if(! $_REQUEST['photo_id']) return false;
2652 $scale = ((array_key_exists('scale',$_REQUEST)) ? intval($_REQUEST['scale']) : 0);
2653 $r = q("select * from photo where uid = %d and `resource-id` = '%s' and scale = %d limit 1",
2654 intval(local_user()),
2655 dbesc($_REQUEST['photo_id']),
2659 header("Content-type: application/json");
2660 $r[0]['data'] = base64_encode($r[0]['data']);
2661 echo json_encode($r[0]);
2667 api_register_func('api/friendica/photos/list', 'api_fr_photos_list', true);
2668 api_register_func('api/friendica/photo', 'api_fr_photo_detail', true);
2673 * similar as /mod/redir.php
2674 * redirect to 'url' after dfrn auth
2676 * why this when there is mod/redir.php already?
2677 * This use api_user() and api_login()
2680 * c_url: url of remote contact to auth to
2681 * url: string, url to redirect after auth
2683 function api_friendica_remoteauth(&$a) {
2684 $url = ((x($_GET,'url')) ? $_GET['url'] : '');
2685 $c_url = ((x($_GET,'c_url')) ? $_GET['c_url'] : '');
2687 if ($url === '' || $c_url === '')
2688 die((api_error($a, 'json', "Wrong parameters")));
2690 $c_url = normalise_link($c_url);
2694 $r = q("SELECT * FROM `contact` WHERE `id` = %d AND `nurl` = '%s' LIMIT 1",
2699 if ((! count($r)) || ($r[0]['network'] !== NETWORK_DFRN))
2700 die((api_error($a, 'json', "Unknown contact")));
2704 $dfrn_id = $orig_id = (($r[0]['issued-id']) ? $r[0]['issued-id'] : $r[0]['dfrn-id']);
2706 if($r[0]['duplex'] && $r[0]['issued-id']) {
2707 $orig_id = $r[0]['issued-id'];
2708 $dfrn_id = '1:' . $orig_id;
2710 if($r[0]['duplex'] && $r[0]['dfrn-id']) {
2711 $orig_id = $r[0]['dfrn-id'];
2712 $dfrn_id = '0:' . $orig_id;
2715 $sec = random_string();
2717 q("INSERT INTO `profile_check` ( `uid`, `cid`, `dfrn_id`, `sec`, `expire`)
2718 VALUES( %d, %s, '%s', '%s', %d )",
2726 logger($r[0]['name'] . ' ' . $sec, LOGGER_DEBUG);
2727 $dest = (($url) ? '&destination_url=' . $url : '');
2728 goaway ($r[0]['poll'] . '?dfrn_id=' . $dfrn_id
2729 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
2730 . '&type=profile&sec=' . $sec . $dest . $quiet );
2732 api_register_func('api/friendica/remoteauth', 'api_friendica_remoteauth', true);
2736 function api_share_as_retweet(&$item) {
2737 $body = trim($item["body"]);
2739 // Skip if it isn't a pure repeated messages
2740 // Does it start with a share?
2741 if (strpos($body, "[share") > 0)
2744 // Does it end with a share?
2745 if (strlen($body) > (strrpos($body, "[/share]") + 8))
2748 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$1",$body);
2749 // Skip if there is no shared message in there
2750 if ($body == $attributes)
2754 preg_match("/author='(.*?)'/ism", $attributes, $matches);
2755 if ($matches[1] != "")
2756 $author = html_entity_decode($matches[1],ENT_QUOTES,'UTF-8');
2758 preg_match('/author="(.*?)"/ism', $attributes, $matches);
2759 if ($matches[1] != "")
2760 $author = $matches[1];
2763 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
2764 if ($matches[1] != "")
2765 $profile = $matches[1];
2767 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
2768 if ($matches[1] != "")
2769 $profile = $matches[1];
2772 preg_match("/avatar='(.*?)'/ism", $attributes, $matches);
2773 if ($matches[1] != "")
2774 $avatar = $matches[1];
2776 preg_match('/avatar="(.*?)"/ism', $attributes, $matches);
2777 if ($matches[1] != "")
2778 $avatar = $matches[1];
2781 preg_match("/link='(.*?)'/ism", $attributes, $matches);
2782 if ($matches[1] != "")
2783 $link = $matches[1];
2785 preg_match('/link="(.*?)"/ism', $attributes, $matches);
2786 if ($matches[1] != "")
2787 $link = $matches[1];
2789 $shared_body = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$2",$body);
2791 if (($shared_body == "") OR ($profile == "") OR ($author == "") OR ($avatar == ""))
2794 $item["body"] = $shared_body;
2795 $item["author-name"] = $author;
2796 $item["author-link"] = $profile;
2797 $item["author-avatar"] = $avatar;
2798 $item["plink"] = $link;
2804 function api_get_nick($profile) {
2806 - remove trailing jung from profile url
2807 - pump.io check has to check the website
2812 $friendica = preg_replace("=https?://(.*)/profile/(.*)=ism", "$2", $profile);
2813 if ($friendica != $profile)
2817 $diaspora = preg_replace("=https?://(.*)/u/(.*)=ism", "$2", $profile);
2818 if ($diaspora != $profile)
2823 $twitter = preg_replace("=https?://twitter.com/(.*)=ism", "$1", $profile);
2824 if ($twitter != $profile)
2830 $StatusnetHost = preg_replace("=https?://(.*)/user/(.*)=ism", "$1", $profile);
2831 if ($StatusnetHost != $profile) {
2832 $StatusnetUser = preg_replace("=https?://(.*)/user/(.*)=ism", "$2", $profile);
2833 if ($StatusnetUser != $profile) {
2834 $UserData = fetch_url("http://".$StatusnetHost."/api/users/show.json?user_id=".$StatusnetUser);
2835 $user = json_decode($UserData);
2837 $nick = $user->screen_name;
2842 // To-Do: look at the page if its really a pumpio site
2843 //if (!$nick == "") {
2844 // $pumpio = preg_replace("=https?://(.*)/(.*)/=ism", "$2", $profile."/");
2845 // if ($pumpio != $profile)
2847 // <div class="media" id="profile-block" data-profile-id="acct:kabniel@microca.st">
2852 q("UPDATE unique_contacts SET nick = '%s' WHERE url = '%s'",
2853 dbesc($nick), dbesc(normalise_link($profile)));
2860 function api_clean_plain_items($Text) {
2861 $include_entities = strtolower(x($_REQUEST,'include_entities')?$_REQUEST['include_entities']:"false");
2863 $Text = bb_CleanPictureLinks($Text);
2865 $URLSearchString = "^\[\]";
2867 $Text = preg_replace("/([!#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'$1$3',$Text);
2869 if ($include_entities == "true") {
2870 $Text = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'[url=$1]$1[/url]',$Text);
2873 $Text = preg_replace_callback("((.*?)\[class=(.*?)\](.*?)\[\/class\])ism","api_cleanup_share",$Text);
2877 function api_cleanup_share($shared) {
2878 if ($shared[2] != "type-link")
2881 if (!preg_match_all("/\[bookmark\=([^\]]*)\](.*?)\[\/bookmark\]/ism",$shared[3], $bookmark))
2887 if (isset($bookmark[2][0]))
2888 $title = $bookmark[2][0];
2890 if (isset($bookmark[1][0]))
2891 $link = $bookmark[1][0];
2893 if (strpos($shared[1],$title) !== false)
2896 if (strpos($shared[1],$link) !== false)
2899 $text = trim($shared[1]);
2901 //if (strlen($text) < strlen($title))
2902 if (($text == "") AND ($title != ""))
2903 $text .= "\n\n".trim($title);
2906 $text .= "\n".trim($link);
2908 return(trim($text));
2911 function api_best_nickname(&$contacts) {
2912 $best_contact = array();
2914 if (count($contact) == 0)
2917 foreach ($contacts AS $contact)
2918 if ($contact["network"] == "") {
2919 $contact["network"] = "dfrn";
2920 $best_contact = array($contact);
2923 if (sizeof($best_contact) == 0)
2924 foreach ($contacts AS $contact)
2925 if ($contact["network"] == "dfrn")
2926 $best_contact = array($contact);
2928 if (sizeof($best_contact) == 0)
2929 foreach ($contacts AS $contact)
2930 if ($contact["network"] == "dspr")
2931 $best_contact = array($contact);
2933 if (sizeof($best_contact) == 0)
2934 foreach ($contacts AS $contact)
2935 if ($contact["network"] == "stat")
2936 $best_contact = array($contact);
2938 if (sizeof($best_contact) == 0)
2939 foreach ($contacts AS $contact)
2940 if ($contact["network"] == "pump")
2941 $best_contact = array($contact);
2943 if (sizeof($best_contact) == 0)
2944 foreach ($contacts AS $contact)
2945 if ($contact["network"] == "twit")
2946 $best_contact = array($contact);
2948 if (sizeof($best_contact) == 1)
2949 $contacts = $best_contact;
2951 $contacts = array($contacts[0]);
2956 Not implemented by now:
2957 statuses/retweets_of_me
2962 account/update_location
2963 account/update_profile_background_image
2964 account/update_profile_image
2968 Not implemented in status.net:
2969 statuses/retweeted_to_me
2970 statuses/retweeted_by_me
2971 direct_messages/destroy
2973 account/update_delivery_device
2974 notifications/follow