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");
12 require_once("mod/item.php");
13 require_once('include/security.php');
14 require_once('include/contact_selectors.php');
15 require_once('library/HTMLPurifier.auto.php');
16 require_once('include/html2bbcode.php');
17 require_once('mod/wall_upload.php');
18 require_once("mod/proxy.php");
19 require_once("include/message.php");
31 // It is not sufficient to use local_user() to check whether someone is allowed to use the API,
32 // because this will open CSRF holes (just embed an image with src=friendicasite.com/api/statuses/update?status=CSRF
33 // into a page, and visitors will post something without noticing it).
34 // Instead, use this function.
35 if ($_SESSION["allow_api"])
41 function api_source() {
42 if (requestdata('source'))
43 return (requestdata('source'));
45 // Support for known clients that doesn't send a source name
46 if (strstr($_SERVER['HTTP_USER_AGENT'], "Twidere"))
49 logger("Unrecognized user-agent ".$_SERVER['HTTP_USER_AGENT'], LOGGER_DEBUG);
54 function api_date($str){
55 //Wed May 23 06:01:13 +0000 2007
56 return datetime_convert('UTC', 'UTC', $str, "D M d H:i:s +0000 Y" );
60 function api_register_func($path, $func, $auth=false){
62 $API[$path] = array('func'=>$func, 'auth'=>$auth);
64 // Workaround for hotot
65 $path = str_replace("api/", "api/1.1/", $path);
66 $API[$path] = array('func'=>$func, 'auth'=>$auth);
73 function api_login(&$a){
76 $oauth = new FKOAuth1();
77 list($consumer,$token) = $oauth->verify_request(OAuthRequest::from_request());
78 if (!is_null($token)){
79 $oauth->loginUser($token->uid);
80 call_hooks('logged_in', $a->user);
83 echo __file__.__line__.__function__."<pre>"; var_dump($consumer, $token); die();
85 logger(__file__.__line__.__function__."\n".$e);
86 //die(__file__.__line__.__function__."<pre>".$e); die();
91 // workaround for HTTP-auth in CGI mode
92 if(x($_SERVER,'REDIRECT_REMOTE_USER')) {
93 $userpass = base64_decode(substr($_SERVER["REDIRECT_REMOTE_USER"],6)) ;
94 if(strlen($userpass)) {
95 list($name, $password) = explode(':', $userpass);
96 $_SERVER['PHP_AUTH_USER'] = $name;
97 $_SERVER['PHP_AUTH_PW'] = $password;
101 if (!isset($_SERVER['PHP_AUTH_USER'])) {
102 logger('API_login: ' . print_r($_SERVER,true), LOGGER_DEBUG);
103 header('WWW-Authenticate: Basic realm="Friendica"');
104 header('HTTP/1.0 401 Unauthorized');
105 die((api_error($a, 'json', "This api requires login")));
107 //die('This api requires login');
110 $user = $_SERVER['PHP_AUTH_USER'];
111 $password = $_SERVER['PHP_AUTH_PW'];
112 $encrypted = hash('whirlpool',trim($password));
114 // allow "user@server" login (but ignore 'server' part)
115 $at=strstr($user, "@", true);
116 if ( $at ) $user=$at;
119 * next code from mod/auth.php. needs better solution
124 'username' => trim($user),
125 'password' => trim($password),
126 'authenticated' => 0,
127 'user_record' => null
132 * A plugin indicates successful login by setting 'authenticated' to non-zero value and returning a user record
133 * Plugins should never set 'authenticated' except to indicate success - as hooks may be chained
134 * and later plugins should not interfere with an earlier one that succeeded.
138 call_hooks('authenticate', $addon_auth);
140 if(($addon_auth['authenticated']) && (count($addon_auth['user_record']))) {
141 $record = $addon_auth['user_record'];
144 // process normal login request
146 $r = q("SELECT * FROM `user` WHERE ( `email` = '%s' OR `nickname` = '%s' )
147 AND `password` = '%s' AND `blocked` = 0 AND `account_expired` = 0 AND `account_removed` = 0 AND `verified` = 1 LIMIT 1",
156 if((! $record) || (! count($record))) {
157 logger('API_login failure: ' . print_r($_SERVER,true), LOGGER_DEBUG);
158 header('WWW-Authenticate: Basic realm="Friendica"');
159 header('HTTP/1.0 401 Unauthorized');
160 die('This api requires login');
163 authenticate_success($record); $_SESSION["allow_api"] = true;
165 call_hooks('logged_in', $a->user);
169 /**************************
170 * MAIN API ENTRY POINT *
171 **************************/
172 function api_call(&$a){
173 GLOBAL $API, $called_api;
177 foreach ($API as $p=>$info){
178 if (strpos($a->query_string, $p)===0){
179 $called_api= explode("/",$p);
180 //unset($_SERVER['PHP_AUTH_USER']);
181 if ($info['auth']===true && api_user()===false) {
185 load_contact_links(api_user());
187 logger('API call for ' . $a->user['username'] . ': ' . $a->query_string);
188 logger('API parameters: ' . print_r($_REQUEST,true));
190 if (strpos($a->query_string, ".xml")>0) $type="xml";
191 if (strpos($a->query_string, ".json")>0) $type="json";
192 if (strpos($a->query_string, ".rss")>0) $type="rss";
193 if (strpos($a->query_string, ".atom")>0) $type="atom";
194 if (strpos($a->query_string, ".as")>0) $type="as";
196 $stamp = microtime(true);
197 $r = call_user_func($info['func'], $a, $type);
198 $duration = (float)(microtime(true)-$stamp);
199 logger("API call duration: ".round($duration, 2)."\t".$a->query_string, LOGGER_DEBUG);
201 if ($r===false) return;
205 $r = mb_convert_encoding($r, "UTF-8",mb_detect_encoding($r));
206 header ("Content-Type: text/xml");
207 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
210 header ("Content-Type: application/json");
212 $json = json_encode($rr);
213 if ($_GET['callback'])
214 $json = $_GET['callback']."(".$json.")";
218 header ("Content-Type: application/rss+xml");
219 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
222 header ("Content-Type: application/atom+xml");
223 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
226 //header ("Content-Type: application/json");
228 // return json_encode($rr);
229 return json_encode($r);
233 //echo "<pre>"; var_dump($r); die();
236 header("HTTP/1.1 404 Not Found");
237 logger('API call not implemented: '.$a->query_string." - ".print_r($_REQUEST,true));
238 return(api_error($a, $type, "not implemented"));
242 function api_error(&$a, $type, $error) {
243 # TODO: https://dev.twitter.com/overview/api/response-codes
244 $r = "<status><error>".$error."</error><request>".$a->query_string."</request></status>";
247 header ("Content-Type: text/xml");
248 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
251 header ("Content-Type: application/json");
252 return json_encode(array('error' => $error, 'request' => $a->query_string));
255 header ("Content-Type: application/rss+xml");
256 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
259 header ("Content-Type: application/atom+xml");
260 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
268 function api_rss_extra(&$a, $arr, $user_info){
269 if (is_null($user_info)) $user_info = api_get_user($a);
270 $arr['$user'] = $user_info;
271 $arr['$rss'] = array(
272 'alternate' => $user_info['url'],
273 'self' => $a->get_baseurl(). "/". $a->query_string,
274 'base' => $a->get_baseurl(),
275 'updated' => api_date(null),
276 'atom_updated' => datetime_convert('UTC','UTC','now',ATOM_TIME),
277 'language' => $user_info['language'],
278 'logo' => $a->get_baseurl()."/images/friendica-32.png",
286 * Unique contact to contact url.
288 function api_unique_id_to_url($id){
289 $r = q("SELECT url FROM unique_contacts WHERE id=%d LIMIT 1",
292 return ($r[0]["url"]);
298 * Returns user info array.
300 function api_get_user(&$a, $contact_id = Null, $type = "json"){
307 logger("api_get_user: Fetching user data for user ".$contact_id, LOGGER_DEBUG);
309 // Searching for contact URL
310 if(!is_null($contact_id) AND (intval($contact_id) == 0)){
311 $user = dbesc(normalise_link($contact_id));
313 $extra_query = "AND `contact`.`nurl` = '%s' ";
314 if (api_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(api_user());
317 // Searching for unique contact id
318 if(!is_null($contact_id) AND (intval($contact_id) != 0)){
319 $user = dbesc(api_unique_id_to_url($contact_id));
322 die(api_error($a, $type, t("User not found.")));
325 $extra_query = "AND `contact`.`nurl` = '%s' ";
326 if (api_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(api_user());
329 if(is_null($user) && x($_GET, 'user_id')) {
330 $user = dbesc(api_unique_id_to_url($_GET['user_id']));
333 die(api_error($a, $type, t("User not found.")));
336 $extra_query = "AND `contact`.`nurl` = '%s' ";
337 if (api_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(api_user());
339 if(is_null($user) && x($_GET, 'screen_name')) {
340 $user = dbesc($_GET['screen_name']);
342 $extra_query = "AND `contact`.`nick` = '%s' ";
343 if (api_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(api_user());
346 if (is_null($user) AND ($a->argc > (count($called_api)-1)) AND (count($called_api) > 0)){
347 $argid = count($called_api);
348 list($user, $null) = explode(".",$a->argv[$argid]);
349 if(is_numeric($user)){
350 $user = dbesc(api_unique_id_to_url($user));
356 $extra_query = "AND `contact`.`nurl` = '%s' ";
357 if (api_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(api_user());
359 $user = dbesc($user);
361 $extra_query = "AND `contact`.`nick` = '%s' ";
362 if (api_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(api_user());
366 logger("api_get_user: user ".$user, LOGGER_DEBUG);
369 if (api_user()===false) {
370 api_login($a); return False;
372 $user = $_SESSION['uid'];
373 $extra_query = "AND `contact`.`uid` = %d AND `contact`.`self` = 1 ";
378 logger('api_user: ' . $extra_query . ', user: ' . $user);
380 $uinfo = q("SELECT *, `contact`.`id` as `cid` FROM `contact`
386 // Selecting the id by priority, friendica first
387 api_best_nickname($uinfo);
389 // if the contact wasn't found, fetch it from the unique contacts
390 if (count($uinfo)==0) {
394 $r = q("SELECT * FROM unique_contacts WHERE url='%s' LIMIT 1", $url);
396 $r = q("SELECT * FROM unique_contacts WHERE nick='%s' LIMIT 1", $nick);
399 // If no nick where given, extract it from the address
400 if (($r[0]['nick'] == "") OR ($r[0]['name'] == $r[0]['nick']))
401 $r[0]['nick'] = api_get_nick($r[0]["url"]);
405 'id_str' => (string) $r[0]["id"],
406 'name' => $r[0]["name"],
407 'screen_name' => (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']),
409 'description' => NULL,
410 'url' => $r[0]["url"],
411 'protected' => false,
412 'followers_count' => 0,
413 'friends_count' => 0,
415 'created_at' => api_date(0),
416 'favourites_count' => 0,
418 'time_zone' => 'UTC',
419 'geo_enabled' => false,
421 'statuses_count' => 0,
423 'contributors_enabled' => false,
424 'is_translator' => false,
425 'is_translation_enabled' => false,
426 'profile_image_url' => $r[0]["avatar"],
427 'profile_image_url_https' => $r[0]["avatar"],
428 'following' => false,
429 'follow_request_sent' => false,
430 'notifications' => false,
431 'statusnet_blocking' => false,
432 'notifications' => false,
433 'statusnet_profile_url' => $r[0]["url"],
442 die(api_error($a, $type, t("User not found.")));
446 if($uinfo[0]['self']) {
447 $usr = q("select * from user where uid = %d limit 1",
450 $profile = q("select * from profile where uid = %d and `is-default` = 1 limit 1",
454 //AND `allow_cid`='' AND `allow_gid`='' AND `deny_cid`='' AND `deny_gid`=''",
455 // count public wall messages
456 $r = q("SELECT count(*) as `count` FROM `item`
459 intval($uinfo[0]['uid'])
461 $countitms = $r[0]['count'];
464 //AND `allow_cid`='' AND `allow_gid`='' AND `deny_cid`='' AND `deny_gid`=''",
465 $r = q("SELECT count(*) as `count` FROM `item`
466 WHERE `contact-id` = %d",
467 intval($uinfo[0]['id'])
469 $countitms = $r[0]['count'];
473 $r = q("SELECT count(*) as `count` FROM `contact`
474 WHERE `uid` = %d AND `rel` IN ( %d, %d )
475 AND `self`=0 AND `blocked`=0 AND `pending`=0 AND `hidden`=0",
476 intval($uinfo[0]['uid']),
477 intval(CONTACT_IS_SHARING),
478 intval(CONTACT_IS_FRIEND)
480 $countfriends = $r[0]['count'];
482 $r = q("SELECT count(*) as `count` FROM `contact`
483 WHERE `uid` = %d AND `rel` IN ( %d, %d )
484 AND `self`=0 AND `blocked`=0 AND `pending`=0 AND `hidden`=0",
485 intval($uinfo[0]['uid']),
486 intval(CONTACT_IS_FOLLOWER),
487 intval(CONTACT_IS_FRIEND)
489 $countfollowers = $r[0]['count'];
491 $r = q("SELECT count(*) as `count` FROM item where starred = 1 and uid = %d and deleted = 0",
492 intval($uinfo[0]['uid'])
494 $starred = $r[0]['count'];
497 if(! $uinfo[0]['self']) {
503 // Add a nick if it isn't present there
504 if (($uinfo[0]['nick'] == "") OR ($uinfo[0]['name'] == $uinfo[0]['nick'])) {
505 $uinfo[0]['nick'] = api_get_nick($uinfo[0]["url"]);
508 // Fetching unique id
509 $r = q("SELECT id FROM unique_contacts WHERE url='%s' LIMIT 1", dbesc(normalise_link($uinfo[0]['url'])));
511 // If not there, then add it
512 if (count($r) == 0) {
513 q("INSERT INTO unique_contacts (url, name, nick, avatar) VALUES ('%s', '%s', '%s', '%s')",
514 dbesc(normalise_link($uinfo[0]['url'])), dbesc($uinfo[0]['name']),dbesc($uinfo[0]['nick']), dbesc($uinfo[0]['micro']));
516 $r = q("SELECT id FROM unique_contacts WHERE url='%s' LIMIT 1", dbesc(normalise_link($uinfo[0]['url'])));
519 $network_name = network_to_name($uinfo[0]['network'], $uinfo[0]['url']);
522 'id' => intval($r[0]['id']),
523 'id_str' => (string) intval($r[0]['id']),
524 'name' => (($uinfo[0]['name']) ? $uinfo[0]['name'] : $uinfo[0]['nick']),
525 'screen_name' => (($uinfo[0]['nick']) ? $uinfo[0]['nick'] : $uinfo[0]['name']),
526 'location' => ($usr) ? $usr[0]['default-location'] : $network_name,
527 'description' => (($profile) ? $profile[0]['pdesc'] : NULL),
528 'profile_image_url' => $uinfo[0]['micro'],
529 'profile_image_url_https' => $uinfo[0]['micro'],
530 'url' => $uinfo[0]['url'],
531 'protected' => false,
532 'followers_count' => intval($countfollowers),
533 'friends_count' => intval($countfriends),
534 'created_at' => api_date($uinfo[0]['created']),
535 'favourites_count' => intval($starred),
537 'time_zone' => 'UTC',
538 'statuses_count' => intval($countitms),
539 'following' => (($uinfo[0]['rel'] == CONTACT_IS_FOLLOWER) OR ($uinfo[0]['rel'] == CONTACT_IS_FRIEND)),
541 'statusnet_blocking' => false,
542 'notifications' => false,
543 'statusnet_profile_url' => $a->get_baseurl()."/contacts/".$uinfo[0]['cid'],
544 'uid' => intval($uinfo[0]['uid']),
545 'cid' => intval($uinfo[0]['cid']),
546 'self' => $uinfo[0]['self'],
547 'network' => $uinfo[0]['network'],
554 function api_item_get_user(&$a, $item) {
556 $author = q("SELECT * FROM unique_contacts WHERE url='%s' LIMIT 1",
557 dbesc(normalise_link($item['author-link'])));
559 if (count($author) == 0) {
560 q("INSERT INTO unique_contacts (url, name, avatar) VALUES ('%s', '%s', '%s')",
561 dbesc(normalise_link($item["author-link"])), dbesc($item["author-name"]), dbesc($item["author-avatar"]));
563 $author = q("SELECT id FROM unique_contacts WHERE url='%s' LIMIT 1",
564 dbesc(normalise_link($item['author-link'])));
565 } else if ($item["author-link"].$item["author-name"] != $author[0]["url"].$author[0]["name"]) {
566 q("UPDATE unique_contacts SET name = '%s', avatar = '%s' WHERE url = '%s'",
567 dbesc($item["author-name"]), dbesc($item["author-avatar"]), dbesc(normalise_link($item["author-link"])));
570 $owner = q("SELECT id FROM unique_contacts WHERE url='%s' LIMIT 1",
571 dbesc(normalise_link($item['owner-link'])));
573 if (count($owner) == 0) {
574 q("INSERT INTO unique_contacts (url, name, avatar) VALUES ('%s', '%s', '%s')",
575 dbesc(normalise_link($item["owner-link"])), dbesc($item["owner-name"]), dbesc($item["owner-avatar"]));
577 $owner = q("SELECT id FROM unique_contacts WHERE url='%s' LIMIT 1",
578 dbesc(normalise_link($item['owner-link'])));
579 } else if ($item["owner-link"].$item["owner-name"] != $owner[0]["url"].$owner[0]["name"]) {
580 q("UPDATE unique_contacts SET name = '%s', avatar = '%s' WHERE url = '%s'",
581 dbesc($item["owner-name"]), dbesc($item["owner-avatar"]), dbesc(normalise_link($item["owner-link"])));
584 // Comments in threads may appear as wall-to-wall postings.
585 // So only take the owner at the top posting.
586 if ($item["id"] == $item["parent"])
587 $status_user = api_get_user($a,$item["owner-link"]);
589 $status_user = api_get_user($a,$item["author-link"]);
591 $status_user["protected"] = (($item["allow_cid"] != "") OR
592 ($item["allow_gid"] != "") OR
593 ($item["deny_cid"] != "") OR
594 ($item["deny_gid"] != "") OR
597 return ($status_user);
602 * load api $templatename for $type and replace $data array
604 function api_apply_template($templatename, $type, $data){
612 $data = array_xmlify($data);
613 $tpl = get_markup_template("api_".$templatename."_".$type.".tpl");
615 header ("Content-Type: text/xml");
616 echo '<?xml version="1.0" encoding="UTF-8"?>'."\n".'<status><error>not implemented</error></status>';
619 $ret = replace_macros($tpl, $data);
634 * Returns an HTTP 200 OK response code and a representation of the requesting user if authentication was successful;
635 * returns a 401 status code and an error message if not.
636 * http://developer.twitter.com/doc/get/account/verify_credentials
638 function api_account_verify_credentials(&$a, $type){
639 if (api_user()===false) return false;
641 unset($_REQUEST["user_id"]);
642 unset($_GET["user_id"]);
644 unset($_REQUEST["screen_name"]);
645 unset($_GET["screen_name"]);
647 $skip_status = (x($_REQUEST,'skip_status')?$_REQUEST['skip_status']:false);
649 $user_info = api_get_user($a);
651 // "verified" isn't used here in the standard
652 unset($user_info["verified"]);
654 // - Adding last status
656 $user_info["status"] = api_status_show($a,"raw");
657 if (!count($user_info["status"]))
658 unset($user_info["status"]);
660 unset($user_info["status"]["user"]);
663 // "uid" and "self" are only needed for some internal stuff, so remove it from here
664 unset($user_info["uid"]);
665 unset($user_info["self"]);
667 return api_apply_template("user", $type, array('$user' => $user_info));
670 api_register_func('api/account/verify_credentials','api_account_verify_credentials', true);
674 * get data from $_POST or $_GET
676 function requestdata($k){
677 if (isset($_POST[$k])){
680 if (isset($_GET[$k])){
686 /*Waitman Gobble Mod*/
687 function api_statuses_mediap(&$a, $type) {
688 if (api_user()===false) {
689 logger('api_statuses_update: no user');
692 $user_info = api_get_user($a);
694 $_REQUEST['type'] = 'wall';
695 $_REQUEST['profile_uid'] = api_user();
696 $_REQUEST['api_source'] = true;
697 $txt = requestdata('status');
698 //$txt = urldecode(requestdata('status'));
700 if((strpos($txt,'<') !== false) || (strpos($txt,'>') !== false)) {
701 $txt = html2bb_video($txt);
702 $config = HTMLPurifier_Config::createDefault();
703 $config->set('Cache.DefinitionImpl', null);
704 $purifier = new HTMLPurifier($config);
705 $txt = $purifier->purify($txt);
707 $txt = html2bbcode($txt);
709 $a->argv[1]=$user_info['screen_name']; //should be set to username?
711 $_REQUEST['hush']='yeah'; //tell wall_upload function to return img info instead of echo
712 $bebop = wall_upload_post($a);
714 //now that we have the img url in bbcode we can add it to the status and insert the wall item.
715 $_REQUEST['body']=$txt."\n\n".$bebop;
718 // this should output the last post (the one we just posted).
719 return api_status_show($a,$type);
721 api_register_func('api/statuses/mediap','api_statuses_mediap', true);
722 /*Waitman Gobble Mod*/
725 function api_statuses_update(&$a, $type) {
726 if (api_user()===false) {
727 logger('api_statuses_update: no user');
731 $user_info = api_get_user($a);
733 // convert $_POST array items to the form we use for web posts.
735 // logger('api_post: ' . print_r($_POST,true));
737 if(requestdata('htmlstatus')) {
738 $txt = requestdata('htmlstatus');
739 if((strpos($txt,'<') !== false) || (strpos($txt,'>') !== false)) {
741 $txt = html2bb_video($txt);
743 $config = HTMLPurifier_Config::createDefault();
744 $config->set('Cache.DefinitionImpl', null);
747 $purifier = new HTMLPurifier($config);
748 $txt = $purifier->purify($txt);
750 $_REQUEST['body'] = html2bbcode($txt);
754 $_REQUEST['body'] = requestdata('status');
756 $_REQUEST['title'] = requestdata('title');
758 $parent = requestdata('in_reply_to_status_id');
760 // Twidere sends "-1" if it is no reply ...
764 if(ctype_digit($parent))
765 $_REQUEST['parent'] = $parent;
767 $_REQUEST['parent_uri'] = $parent;
769 if(requestdata('lat') && requestdata('long'))
770 $_REQUEST['coord'] = sprintf("%s %s",requestdata('lat'),requestdata('long'));
771 $_REQUEST['profile_uid'] = api_user();
774 $_REQUEST['type'] = 'net-comment';
776 // Check for throttling (maximum posts per day, week and month)
777 $throttle_day = get_config('system','throttle_limit_day');
778 if ($throttle_day > 0) {
779 $datefrom = date("Y-m-d H:i:s", time() - 24*60*60);
781 $r = q("SELECT COUNT(*) AS `posts_day` FROM `item` WHERE `uid`=%d AND `wall`
782 AND `created` > '%s' AND `id` = `parent`",
783 intval(api_user()), dbesc($datefrom));
786 $posts_day = $r[0]["posts_day"];
790 if ($posts_day > $throttle_day) {
791 logger('Daily posting limit reached for user '.api_user(), LOGGER_DEBUG);
792 die(api_error($a, $type, sprintf(t("Daily posting limit of %d posts reached. The post was rejected."), $throttle_day)));
796 $throttle_week = get_config('system','throttle_limit_week');
797 if ($throttle_week > 0) {
798 $datefrom = date("Y-m-d H:i:s", time() - 24*60*60*7);
800 $r = q("SELECT COUNT(*) AS `posts_week` FROM `item` WHERE `uid`=%d AND `wall`
801 AND `created` > '%s' AND `id` = `parent`",
802 intval(api_user()), dbesc($datefrom));
805 $posts_week = $r[0]["posts_week"];
809 if ($posts_week > $throttle_week) {
810 logger('Weekly posting limit reached for user '.api_user(), LOGGER_DEBUG);
811 die(api_error($a, $type, sprintf(t("Weekly posting limit of %d posts reached. The post was rejected."), $throttle_week)));
815 $throttle_month = get_config('system','throttle_limit_month');
816 if ($throttle_month > 0) {
817 $datefrom = date("Y-m-d H:i:s", time() - 24*60*60*30);
819 $r = q("SELECT COUNT(*) AS `posts_month` FROM `item` WHERE `uid`=%d AND `wall`
820 AND `created` > '%s' AND `id` = `parent`",
821 intval(api_user()), dbesc($datefrom));
824 $posts_month = $r[0]["posts_month"];
828 if ($posts_month > $throttle_month) {
829 logger('Monthly posting limit reached for user '.api_user(), LOGGER_DEBUG);
830 die(api_error($a, $type, sprintf(t("Monthly posting limit of %d posts reached. The post was rejected."), $throttle_month)));
834 $_REQUEST['type'] = 'wall';
837 if(x($_FILES,'media')) {
838 // upload the image if we have one
839 $_REQUEST['hush']='yeah'; //tell wall_upload function to return img info instead of echo
840 $media = wall_upload_post($a);
842 $_REQUEST['body'] .= "\n\n".$media;
845 // To-Do: Multiple IDs
846 if (requestdata('media_ids')) {
847 $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",
848 intval(requestdata('media_ids')), api_user());
850 $phototypes = Photo::supportedTypes();
851 $ext = $phototypes[$r[0]['type']];
852 $_REQUEST['body'] .= "\n\n".'[url='.$a->get_baseurl().'/photos/'.$r[0]['nickname'].'/image/'.$r[0]['resource-id'].']';
853 $_REQUEST['body'] .= '[img]'.$a->get_baseurl()."/photo/".$r[0]['resource-id']."-".$r[0]['scale'].".".$ext."[/img][/url]";
857 // set this so that the item_post() function is quiet and doesn't redirect or emit json
859 $_REQUEST['api_source'] = true;
861 if (!x($_REQUEST, "source"))
862 $_REQUEST["source"] = api_source();
864 // call out normal post function
868 // this should output the last post (the one we just posted).
869 return api_status_show($a,$type);
871 api_register_func('api/statuses/update','api_statuses_update', true);
872 api_register_func('api/statuses/update_with_media','api_statuses_update', true);
875 function api_media_upload(&$a, $type) {
876 if (api_user()===false) {
881 $user_info = api_get_user($a);
883 if(!x($_FILES,'media')) {
888 $media = wall_upload_post($a, false);
894 $returndata = array();
895 $returndata["media_id"] = $media["id"];
896 $returndata["media_id_string"] = (string)$media["id"];
897 $returndata["size"] = $media["size"];
898 $returndata["image"] = array("w" => $media["width"],
899 "h" => $media["height"],
900 "image_type" => $media["type"]);
902 logger("Media uploaded: ".print_r($returndata, true), LOGGER_DEBUG);
904 return array("media" => $returndata);
907 api_register_func('api/media/upload','api_media_upload', true);
909 function api_status_show(&$a, $type){
910 $user_info = api_get_user($a);
912 logger('api_status_show: user_info: '.print_r($user_info, true), LOGGER_DEBUG);
914 // get last public wall message
915 $lastwall = q("SELECT `item`.*, `i`.`contact-id` as `reply_uid`, `i`.`author-link` AS `item-author`
916 FROM `item`, `item` as `i`
917 WHERE `item`.`contact-id` = %d AND `item`.`uid` = %d
918 AND ((`item`.`author-link` IN ('%s', '%s')) OR (`item`.`owner-link` IN ('%s', '%s')))
919 AND `i`.`id` = `item`.`parent`
920 AND `item`.`type`!='activity'
921 AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''
922 ORDER BY `item`.`created` DESC
924 intval($user_info['cid']),
926 dbesc($user_info['url']),
927 dbesc(normalise_link($user_info['url'])),
928 dbesc($user_info['url']),
929 dbesc(normalise_link($user_info['url']))
932 if (count($lastwall)>0){
933 $lastwall = $lastwall[0];
935 $in_reply_to_status_id = NULL;
936 $in_reply_to_user_id = NULL;
937 $in_reply_to_status_id_str = NULL;
938 $in_reply_to_user_id_str = NULL;
939 $in_reply_to_screen_name = NULL;
940 if (intval($lastwall['parent']) != intval($lastwall['id'])) {
941 $in_reply_to_status_id= intval($lastwall['parent']);
942 $in_reply_to_status_id_str = (string) intval($lastwall['parent']);
944 $r = q("SELECT * FROM unique_contacts WHERE `url` = '%s'", dbesc(normalise_link($lastwall['item-author'])));
946 if ($r[0]['nick'] == "")
947 $r[0]['nick'] = api_get_nick($r[0]["url"]);
949 $in_reply_to_screen_name = (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']);
950 $in_reply_to_user_id = intval($r[0]['id']);
951 $in_reply_to_user_id_str = (string) intval($r[0]['id']);
955 // There seems to be situation, where both fields are identical:
956 // https://github.com/friendica/friendica/issues/1010
957 // This is a bugfix for that.
958 if (intval($in_reply_to_status_id) == intval($lastwall['id'])) {
959 logger('api_status_show: this message should never appear: id: '.$lastwall['id'].' similar to reply-to: '.$in_reply_to_status_id, LOGGER_DEBUG);
960 $in_reply_to_status_id = NULL;
961 $in_reply_to_user_id = NULL;
962 $in_reply_to_status_id_str = NULL;
963 $in_reply_to_user_id_str = NULL;
964 $in_reply_to_screen_name = NULL;
967 $converted = api_convert_item($item);
969 $status_info = array(
970 'created_at' => api_date($lastwall['created']),
971 'id' => intval($lastwall['id']),
972 'id_str' => (string) $lastwall['id'],
973 'text' => $converted["text"],
974 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
975 'truncated' => false,
976 'in_reply_to_status_id' => $in_reply_to_status_id,
977 'in_reply_to_status_id_str' => $in_reply_to_status_id_str,
978 'in_reply_to_user_id' => $in_reply_to_user_id,
979 'in_reply_to_user_id_str' => $in_reply_to_user_id_str,
980 'in_reply_to_screen_name' => $in_reply_to_screen_name,
981 'user' => $user_info,
985 'contributors' => "",
986 'is_quote_status' => false,
987 'retweet_count' => 0,
988 'favorite_count' => 0,
989 'favorited' => $lastwall['starred'] ? true : false,
990 'retweeted' => false,
991 'possibly_sensitive' => false,
993 'statusnet_html' => $converted["html"],
994 'statusnet_conversation_id' => $lastwall['parent'],
997 if (count($converted["attachments"]) > 0)
998 $status_info["attachments"] = $converted["attachments"];
1000 if (count($converted["entities"]) > 0)
1001 $status_info["entities"] = $converted["entities"];
1003 if (($lastwall['item_network'] != "") AND ($status["source"] == 'web'))
1004 $status_info["source"] = network_to_name($lastwall['item_network'], $user_info['url']);
1005 elseif (($lastwall['item_network'] != "") AND (network_to_name($lastwall['item_network'], $user_info['url']) != $status_info["source"]))
1006 $status_info["source"] = trim($status_info["source"].' ('.network_to_name($lastwall['item_network'], $user_info['url']).')');
1008 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1009 unset($status_info["user"]["uid"]);
1010 unset($status_info["user"]["self"]);
1014 return($status_info);
1016 return api_apply_template("status", $type, array('$status' => $status_info));
1025 * Returns extended information of a given user, specified by ID or screen name as per the required id parameter.
1026 * The author's most recent status will be returned inline.
1027 * http://developer.twitter.com/doc/get/users/show
1029 function api_users_show(&$a, $type){
1030 $user_info = api_get_user($a);
1032 $lastwall = q("SELECT `item`.*
1033 FROM `item`, `contact`
1034 WHERE `item`.`uid` = %d AND `verb` = '%s' AND `item`.`contact-id` = %d
1035 AND ((`item`.`author-link` IN ('%s', '%s')) OR (`item`.`owner-link` IN ('%s', '%s')))
1036 AND `contact`.`id`=`item`.`contact-id`
1037 AND `type`!='activity'
1038 AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''
1039 ORDER BY `created` DESC
1042 dbesc(ACTIVITY_POST),
1043 intval($user_info['cid']),
1044 dbesc($user_info['url']),
1045 dbesc(normalise_link($user_info['url'])),
1046 dbesc($user_info['url']),
1047 dbesc(normalise_link($user_info['url']))
1049 if (count($lastwall)>0){
1050 $lastwall = $lastwall[0];
1052 $in_reply_to_status_id = NULL;
1053 $in_reply_to_user_id = NULL;
1054 $in_reply_to_status_id_str = NULL;
1055 $in_reply_to_user_id_str = NULL;
1056 $in_reply_to_screen_name = NULL;
1057 if ($lastwall['parent']!=$lastwall['id']) {
1058 $reply = q("SELECT `item`.`id`, `item`.`contact-id` as `reply_uid`, `contact`.`nick` as `reply_author`, `item`.`author-link` AS `item-author`
1059 FROM `item`,`contact` WHERE `contact`.`id`=`item`.`contact-id` AND `item`.`id` = %d", intval($lastwall['parent']));
1060 if (count($reply)>0) {
1061 $in_reply_to_status_id = intval($lastwall['parent']);
1062 $in_reply_to_status_id_str = (string) intval($lastwall['parent']);
1064 $r = q("SELECT * FROM unique_contacts WHERE `url` = '%s'", dbesc(normalise_link($reply[0]['item-author'])));
1066 if ($r[0]['nick'] == "")
1067 $r[0]['nick'] = api_get_nick($r[0]["url"]);
1069 $in_reply_to_screen_name = (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']);
1070 $in_reply_to_user_id = intval($r[0]['id']);
1071 $in_reply_to_user_id_str = (string) intval($r[0]['id']);
1076 $converted = api_convert_item($item);
1078 $user_info['status'] = array(
1079 'text' => $converted["text"],
1080 'truncated' => false,
1081 'created_at' => api_date($lastwall['created']),
1082 'in_reply_to_status_id' => $in_reply_to_status_id,
1083 'in_reply_to_status_id_str' => $in_reply_to_status_id_str,
1084 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
1085 'id' => intval($lastwall['contact-id']),
1086 'id_str' => (string) $lastwall['contact-id'],
1087 'in_reply_to_user_id' => $in_reply_to_user_id,
1088 'in_reply_to_user_id_str' => $in_reply_to_user_id_str,
1089 'in_reply_to_screen_name' => $in_reply_to_screen_name,
1091 'favorited' => $lastwall['starred'] ? true : false,
1092 'statusnet_html' => $converted["html"],
1093 'statusnet_conversation_id' => $lastwall['parent'],
1096 if (count($converted["attachments"]) > 0)
1097 $user_info["status"]["attachments"] = $converted["attachments"];
1099 if (count($converted["entities"]) > 0)
1100 $user_info["status"]["entities"] = $converted["entities"];
1102 if (($lastwall['item_network'] != "") AND ($user_info["status"]["source"] == 'web'))
1103 $user_info["status"]["source"] = network_to_name($lastwall['item_network'], $user_info['url']);
1104 if (($lastwall['item_network'] != "") AND (network_to_name($lastwall['item_network'], $user_info['url']) != $user_info["status"]["source"]))
1105 $user_info["status"]["source"] = trim($user_info["status"]["source"].' ('.network_to_name($lastwall['item_network'], $user_info['url']).')');
1109 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1110 unset($user_info["uid"]);
1111 unset($user_info["self"]);
1113 return api_apply_template("user", $type, array('$user' => $user_info));
1116 api_register_func('api/users/show','api_users_show');
1119 function api_users_search(&$a, $type) {
1120 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1122 $userlist = array();
1124 if (isset($_GET["q"])) {
1125 $r = q("SELECT id FROM unique_contacts WHERE name='%s'", dbesc($_GET["q"]));
1127 $r = q("SELECT id FROM unique_contacts WHERE nick='%s'", dbesc($_GET["q"]));
1130 foreach ($r AS $user) {
1131 $user_info = api_get_user($a, $user["id"]);
1132 //echo print_r($user_info, true)."\n";
1133 $userdata = api_apply_template("user", $type, array('user' => $user_info));
1134 $userlist[] = $userdata["user"];
1136 $userlist = array("users" => $userlist);
1138 die(api_error($a, $type, t("User not found.")));
1140 die(api_error($a, $type, t("User not found.")));
1145 api_register_func('api/users/search','api_users_search');
1149 * http://developer.twitter.com/doc/get/statuses/home_timeline
1151 * TODO: Optional parameters
1152 * TODO: Add reply info
1154 function api_statuses_home_timeline(&$a, $type){
1155 if (api_user()===false) return false;
1157 unset($_REQUEST["user_id"]);
1158 unset($_GET["user_id"]);
1160 unset($_REQUEST["screen_name"]);
1161 unset($_GET["screen_name"]);
1163 $user_info = api_get_user($a);
1164 // get last newtork messages
1168 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1169 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1170 if ($page<0) $page=0;
1171 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1172 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1173 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1174 $exclude_replies = (x($_REQUEST,'exclude_replies')?1:0);
1175 $conversation_id = (x($_REQUEST,'conversation_id')?$_REQUEST['conversation_id']:0);
1177 $start = $page*$count;
1181 $sql_extra .= ' AND `item`.`id` <= '.intval($max_id);
1182 if ($exclude_replies > 0)
1183 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
1184 if ($conversation_id > 0)
1185 $sql_extra .= ' AND `item`.`parent` = '.intval($conversation_id);
1187 $r = q("SELECT STRAIGHT_JOIN `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1188 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1189 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1190 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1191 FROM `item`, `contact`
1192 WHERE `item`.`uid` = %d AND `verb` = '%s'
1193 AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1194 AND `contact`.`id` = `item`.`contact-id`
1195 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1198 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1200 dbesc(ACTIVITY_POST),
1202 intval($start), intval($count)
1205 $ret = api_format_items($r,$user_info);
1207 // Set all posts from the query above to seen
1209 foreach ($r AS $item)
1210 $idarray[] = intval($item["id"]);
1212 $idlist = implode(",", $idarray);
1215 $r = q("UPDATE `item` SET `unseen` = 0 WHERE `unseen` AND `id` IN (%s)", $idlist);
1218 $data = array('$statuses' => $ret);
1222 $data = api_rss_extra($a, $data, $user_info);
1225 $as = api_format_as($a, $ret, $user_info);
1226 $as['title'] = $a->config['sitename']." Home Timeline";
1227 $as['link']['url'] = $a->get_baseurl()."/".$user_info["screen_name"]."/all";
1232 return api_apply_template("timeline", $type, $data);
1234 api_register_func('api/statuses/home_timeline','api_statuses_home_timeline', true);
1235 api_register_func('api/statuses/friends_timeline','api_statuses_home_timeline', true);
1237 function api_statuses_public_timeline(&$a, $type){
1238 if (api_user()===false) return false;
1240 $user_info = api_get_user($a);
1241 // get last newtork messages
1245 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1246 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1247 if ($page<0) $page=0;
1248 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1249 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1250 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1251 $exclude_replies = (x($_REQUEST,'exclude_replies')?1:0);
1252 $conversation_id = (x($_REQUEST,'conversation_id')?$_REQUEST['conversation_id']:0);
1254 $start = $page*$count;
1257 $sql_extra = 'AND `item`.`id` <= '.intval($max_id);
1258 if ($exclude_replies > 0)
1259 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
1260 if ($conversation_id > 0)
1261 $sql_extra .= ' AND `item`.`parent` = '.intval($conversation_id);
1263 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1264 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1265 `contact`.`network`, `contact`.`thumb`, `contact`.`self`, `contact`.`writable`,
1266 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`,
1267 `user`.`nickname`, `user`.`hidewall`
1268 FROM `item` STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
1269 STRAIGHT_JOIN `user` ON `user`.`uid` = `item`.`uid`
1270 WHERE `verb` = '%s' AND `item`.`visible` = 1 AND `item`.`deleted` = 0 and `item`.`moderated` = 0
1271 AND `item`.`allow_cid` = '' AND `item`.`allow_gid` = ''
1272 AND `item`.`deny_cid` = '' AND `item`.`deny_gid` = ''
1273 AND `item`.`private` = 0 AND `item`.`wall` = 1 AND `user`.`hidewall` = 0
1274 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1277 ORDER BY `item`.`id` DESC LIMIT %d, %d ",
1278 dbesc(ACTIVITY_POST),
1283 $ret = api_format_items($r,$user_info);
1286 $data = array('$statuses' => $ret);
1290 $data = api_rss_extra($a, $data, $user_info);
1293 $as = api_format_as($a, $ret, $user_info);
1294 $as['title'] = $a->config['sitename']." Public Timeline";
1295 $as['link']['url'] = $a->get_baseurl()."/";
1300 return api_apply_template("timeline", $type, $data);
1302 api_register_func('api/statuses/public_timeline','api_statuses_public_timeline', true);
1307 function api_statuses_show(&$a, $type){
1308 if (api_user()===false) return false;
1310 $user_info = api_get_user($a);
1313 $id = intval($a->argv[3]);
1316 $id = intval($_REQUEST["id"]);
1320 $id = intval($a->argv[4]);
1322 logger('API: api_statuses_show: '.$id);
1324 $conversation = (x($_REQUEST,'conversation')?1:0);
1328 $sql_extra .= " AND `item`.`parent` = %d ORDER BY `received` ASC ";
1330 $sql_extra .= " AND `item`.`id` = %d";
1332 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1333 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1334 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1335 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1336 FROM `item`, `contact`
1337 WHERE `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1338 AND `contact`.`id` = `item`.`contact-id` AND `item`.`uid` = %d AND `item`.`verb` = '%s'
1339 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1342 dbesc(ACTIVITY_POST),
1347 die(api_error($a, $type, t("There is no status with this id.")));
1349 $ret = api_format_items($r,$user_info);
1351 if ($conversation) {
1352 $data = array('$statuses' => $ret);
1353 return api_apply_template("timeline", $type, $data);
1355 $data = array('$status' => $ret[0]);
1359 $data = api_rss_extra($a, $data, $user_info);
1361 return api_apply_template("status", $type, $data);
1364 api_register_func('api/statuses/show','api_statuses_show', true);
1370 function api_conversation_show(&$a, $type){
1371 if (api_user()===false) return false;
1373 $user_info = api_get_user($a);
1376 $id = intval($a->argv[3]);
1377 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1378 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1379 if ($page<0) $page=0;
1380 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1381 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1383 $start = $page*$count;
1386 $id = intval($_REQUEST["id"]);
1390 $id = intval($a->argv[4]);
1392 logger('API: api_conversation_show: '.$id);
1394 $r = q("SELECT `parent` FROM `item` WHERE `id` = %d", intval($id));
1396 $id = $r[0]["parent"];
1401 $sql_extra = ' AND `item`.`id` <= '.intval($max_id);
1403 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1404 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1405 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1406 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1407 FROM `item` INNER JOIN (SELECT `uri`,`parent` FROM `item` WHERE `id` = %d) AS `temp1`
1408 ON (`item`.`thr-parent` = `temp1`.`uri` AND `item`.`parent` = `temp1`.`parent`), `contact`
1409 WHERE `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1410 AND `item`.`uid` = %d AND `item`.`verb` = '%s' AND `contact`.`id` = `item`.`contact-id`
1411 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1412 AND `item`.`id`>%d $sql_extra
1413 ORDER BY `item`.`id` DESC LIMIT %d ,%d",
1414 intval($id), intval(api_user()),
1415 dbesc(ACTIVITY_POST),
1417 intval($start), intval($count)
1421 die(api_error($a, $type, t("There is no conversation with this id.")));
1423 $ret = api_format_items($r,$user_info);
1425 $data = array('$statuses' => $ret);
1426 return api_apply_template("timeline", $type, $data);
1428 api_register_func('api/conversation/show','api_conversation_show', true);
1434 function api_statuses_repeat(&$a, $type){
1437 if (api_user()===false) return false;
1439 $user_info = api_get_user($a);
1442 $id = intval($a->argv[3]);
1445 $id = intval($_REQUEST["id"]);
1449 $id = intval($a->argv[4]);
1451 logger('API: api_statuses_repeat: '.$id);
1453 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`, `contact`.`nick` as `reply_author`,
1454 `contact`.`name`, `contact`.`photo` as `reply_photo`, `contact`.`url` as `reply_url`, `contact`.`rel`,
1455 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1456 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1457 FROM `item`, `contact`
1458 WHERE `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1459 AND `contact`.`id` = `item`.`contact-id`
1460 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1462 AND `item`.`id`=%d",
1466 if ($r[0]['body'] != "") {
1467 if (!intval(get_config('system','old_share'))) {
1468 if (strpos($r[0]['body'], "[/share]") !== false) {
1469 $pos = strpos($r[0]['body'], "[share");
1470 $post = substr($r[0]['body'], $pos);
1472 $post = share_header($r[0]['author-name'], $r[0]['author-link'], $r[0]['author-avatar'], $r[0]['guid'], $r[0]['created'], $r[0]['plink']);
1474 $post .= $r[0]['body'];
1475 $post .= "[/share]";
1477 $_REQUEST['body'] = $post;
1479 $_REQUEST['body'] = html_entity_decode("♲ ", ENT_QUOTES, 'UTF-8')."[url=".$r[0]['reply_url']."]".$r[0]['reply_author']."[/url] \n".$r[0]['body'];
1481 $_REQUEST['profile_uid'] = api_user();
1482 $_REQUEST['type'] = 'wall';
1483 $_REQUEST['api_source'] = true;
1485 if (!x($_REQUEST, "source"))
1486 $_REQUEST["source"] = api_source();
1491 // this should output the last post (the one we just posted).
1493 return(api_status_show($a,$type));
1495 api_register_func('api/statuses/retweet','api_statuses_repeat', true);
1500 function api_statuses_destroy(&$a, $type){
1501 if (api_user()===false) return false;
1503 $user_info = api_get_user($a);
1506 $id = intval($a->argv[3]);
1509 $id = intval($_REQUEST["id"]);
1513 $id = intval($a->argv[4]);
1515 logger('API: api_statuses_destroy: '.$id);
1517 $ret = api_statuses_show($a, $type);
1519 drop_item($id, false);
1523 api_register_func('api/statuses/destroy','api_statuses_destroy', true);
1527 * http://developer.twitter.com/doc/get/statuses/mentions
1530 function api_statuses_mentions(&$a, $type){
1531 if (api_user()===false) return false;
1533 unset($_REQUEST["user_id"]);
1534 unset($_GET["user_id"]);
1536 unset($_REQUEST["screen_name"]);
1537 unset($_GET["screen_name"]);
1539 $user_info = api_get_user($a);
1540 // get last newtork messages
1544 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1545 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1546 if ($page<0) $page=0;
1547 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1548 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1549 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1551 $start = $page*$count;
1553 // Ugly code - should be changed
1554 $myurl = $a->get_baseurl() . '/profile/'. $a->user['nickname'];
1555 $myurl = substr($myurl,strpos($myurl,'://')+3);
1556 //$myurl = str_replace(array('www.','.'),array('','\\.'),$myurl);
1557 $myurl = str_replace('www.','',$myurl);
1558 $diasp_url = str_replace('/profile/','/u/',$myurl);
1561 $sql_extra = ' AND `item`.`id` <= '.intval($max_id);
1563 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1564 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1565 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1566 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1567 FROM `item`, `contact`
1568 WHERE `item`.`uid` = %d AND `verb` = '%s'
1569 AND NOT (`item`.`author-link` IN ('https://%s', 'http://%s'))
1570 AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1571 AND `contact`.`id` = `item`.`contact-id`
1572 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1573 AND `item`.`parent` IN (SELECT `iid` from thread where uid = %d AND `mention` AND !`ignored`)
1576 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1578 dbesc(ACTIVITY_POST),
1579 dbesc(protect_sprintf($myurl)),
1580 dbesc(protect_sprintf($myurl)),
1583 intval($start), intval($count)
1586 $ret = api_format_items($r,$user_info);
1589 $data = array('$statuses' => $ret);
1593 $data = api_rss_extra($a, $data, $user_info);
1596 $as = api_format_as($a, $ret, $user_info);
1597 $as["title"] = $a->config['sitename']." Mentions";
1598 $as['link']['url'] = $a->get_baseurl()."/";
1603 return api_apply_template("timeline", $type, $data);
1605 api_register_func('api/statuses/mentions','api_statuses_mentions', true);
1606 api_register_func('api/statuses/replies','api_statuses_mentions', true);
1609 function api_statuses_user_timeline(&$a, $type){
1610 if (api_user()===false) return false;
1612 $user_info = api_get_user($a);
1613 // get last network messages
1615 logger("api_statuses_user_timeline: api_user: ". api_user() .
1616 "\nuser_info: ".print_r($user_info, true) .
1617 "\n_REQUEST: ".print_r($_REQUEST, true),
1621 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1622 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1623 if ($page<0) $page=0;
1624 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1625 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1626 $exclude_replies = (x($_REQUEST,'exclude_replies')?1:0);
1627 $conversation_id = (x($_REQUEST,'conversation_id')?$_REQUEST['conversation_id']:0);
1629 $start = $page*$count;
1632 if ($user_info['self']==1)
1633 $sql_extra .= " AND `item`.`wall` = 1 ";
1635 if ($exclude_replies > 0)
1636 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
1637 if ($conversation_id > 0)
1638 $sql_extra .= ' AND `item`.`parent` = '.intval($conversation_id);
1640 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1641 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1642 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1643 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1644 FROM `item`, `contact`
1645 WHERE `item`.`uid` = %d AND `verb` = '%s'
1646 AND `item`.`contact-id` = %d
1647 AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1648 AND `contact`.`id` = `item`.`contact-id`
1649 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1652 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1654 dbesc(ACTIVITY_POST),
1655 intval($user_info['cid']),
1657 intval($start), intval($count)
1660 $ret = api_format_items($r,$user_info, true);
1662 $data = array('$statuses' => $ret);
1666 $data = api_rss_extra($a, $data, $user_info);
1669 return api_apply_template("timeline", $type, $data);
1672 api_register_func('api/statuses/user_timeline','api_statuses_user_timeline', true);
1676 * Star/unstar an item
1677 * param: id : id of the item
1679 * api v1 : https://web.archive.org/web/20131019055350/https://dev.twitter.com/docs/api/1/post/favorites/create/%3Aid
1681 function api_favorites_create_destroy(&$a, $type){
1682 if (api_user()===false) return false;
1684 # for versioned api.
1685 # TODO: we need a better global soluton
1687 if ($a->argv[1]=="1.1") $action_argv_id=3;
1689 if ($a->argc<=$action_argv_id) die(api_error($a, $type, t("Invalid request.")));
1690 $action = str_replace(".".$type,"",$a->argv[$action_argv_id]);
1691 if ($a->argc==$action_argv_id+2) {
1692 $itemid = intval($a->argv[$action_argv_id+1]);
1694 $itemid = intval($_REQUEST['id']);
1697 $item = q("SELECT * FROM item WHERE id=%d AND uid=%d",
1698 $itemid, api_user());
1700 if ($item===false || count($item)==0) die(api_error($a, $type, t("Invalid item.")));
1704 $item[0]['starred']=1;
1707 $item[0]['starred']=0;
1710 die(api_error($a, $type, t("Invalid action. ".$action)));
1712 $r = q("UPDATE item SET starred=%d WHERE id=%d AND uid=%d",
1713 $item[0]['starred'], $itemid, api_user());
1715 q("UPDATE thread SET starred=%d WHERE iid=%d AND uid=%d",
1716 $item[0]['starred'], $itemid, api_user());
1718 if ($r===false) die(api_error($a, $type, t("DB error")));
1721 $user_info = api_get_user($a);
1722 $rets = api_format_items($item,$user_info);
1725 $data = array('$status' => $ret);
1729 $data = api_rss_extra($a, $data, $user_info);
1732 return api_apply_template("status", $type, $data);
1735 api_register_func('api/favorites/create', 'api_favorites_create_destroy', true);
1736 api_register_func('api/favorites/destroy', 'api_favorites_create_destroy', true);
1738 function api_favorites(&$a, $type){
1741 if (api_user()===false) return false;
1743 $called_api= array();
1745 $user_info = api_get_user($a);
1747 // in friendica starred item are private
1748 // return favorites only for self
1749 logger('api_favorites: self:' . $user_info['self']);
1751 if ($user_info['self']==0) {
1757 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1758 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1759 $count = (x($_GET,'count')?$_GET['count']:20);
1760 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1761 if ($page<0) $page=0;
1763 $start = $page*$count;
1766 $sql_extra .= ' AND `item`.`id` <= '.intval($max_id);
1768 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1769 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1770 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1771 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1772 FROM `item`, `contact`
1773 WHERE `item`.`uid` = %d
1774 AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1775 AND `item`.`starred` = 1
1776 AND `contact`.`id` = `item`.`contact-id`
1777 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1780 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1783 intval($start), intval($count)
1786 $ret = api_format_items($r,$user_info);
1790 $data = array('$statuses' => $ret);
1794 $data = api_rss_extra($a, $data, $user_info);
1797 return api_apply_template("timeline", $type, $data);
1800 api_register_func('api/favorites','api_favorites', true);
1805 function api_format_as($a, $ret, $user_info) {
1808 $as['title'] = $a->config['sitename']." Public Timeline";
1810 foreach ($ret as $item) {
1811 $singleitem["actor"]["displayName"] = $item["user"]["name"];
1812 $singleitem["actor"]["id"] = $item["user"]["contact_url"];
1813 $avatar[0]["url"] = $item["user"]["profile_image_url"];
1814 $avatar[0]["rel"] = "avatar";
1815 $avatar[0]["type"] = "";
1816 $avatar[0]["width"] = 96;
1817 $avatar[0]["height"] = 96;
1818 $avatar[1]["url"] = $item["user"]["profile_image_url"];
1819 $avatar[1]["rel"] = "avatar";
1820 $avatar[1]["type"] = "";
1821 $avatar[1]["width"] = 48;
1822 $avatar[1]["height"] = 48;
1823 $avatar[2]["url"] = $item["user"]["profile_image_url"];
1824 $avatar[2]["rel"] = "avatar";
1825 $avatar[2]["type"] = "";
1826 $avatar[2]["width"] = 24;
1827 $avatar[2]["height"] = 24;
1828 $singleitem["actor"]["avatarLinks"] = $avatar;
1830 $singleitem["actor"]["image"]["url"] = $item["user"]["profile_image_url"];
1831 $singleitem["actor"]["image"]["rel"] = "avatar";
1832 $singleitem["actor"]["image"]["type"] = "";
1833 $singleitem["actor"]["image"]["width"] = 96;
1834 $singleitem["actor"]["image"]["height"] = 96;
1835 $singleitem["actor"]["type"] = "person";
1836 $singleitem["actor"]["url"] = $item["person"]["contact_url"];
1837 $singleitem["actor"]["statusnet:profile_info"]["local_id"] = $item["user"]["id"];
1838 $singleitem["actor"]["statusnet:profile_info"]["following"] = $item["user"]["following"] ? "true" : "false";
1839 $singleitem["actor"]["statusnet:profile_info"]["blocking"] = "false";
1840 $singleitem["actor"]["contact"]["preferredUsername"] = $item["user"]["screen_name"];
1841 $singleitem["actor"]["contact"]["displayName"] = $item["user"]["name"];
1842 $singleitem["actor"]["contact"]["addresses"] = "";
1844 $singleitem["body"] = $item["text"];
1845 $singleitem["object"]["displayName"] = $item["text"];
1846 $singleitem["object"]["id"] = $item["url"];
1847 $singleitem["object"]["type"] = "note";
1848 $singleitem["object"]["url"] = $item["url"];
1849 //$singleitem["context"] =;
1850 $singleitem["postedTime"] = date("c", strtotime($item["published"]));
1851 $singleitem["provider"]["objectType"] = "service";
1852 $singleitem["provider"]["displayName"] = "Test";
1853 $singleitem["provider"]["url"] = "http://test.tld";
1854 $singleitem["title"] = $item["text"];
1855 $singleitem["verb"] = "post";
1856 $singleitem["statusnet:notice_info"]["local_id"] = $item["id"];
1857 $singleitem["statusnet:notice_info"]["source"] = $item["source"];
1858 $singleitem["statusnet:notice_info"]["favorite"] = "false";
1859 $singleitem["statusnet:notice_info"]["repeated"] = "false";
1860 //$singleitem["original"] = $item;
1861 $items[] = $singleitem;
1863 $as['items'] = $items;
1864 $as['link']['url'] = $a->get_baseurl()."/".$user_info["screen_name"]."/all";
1865 $as['link']['rel'] = "alternate";
1866 $as['link']['type'] = "text/html";
1870 function api_format_messages($item, $recipient, $sender) {
1871 // standard meta information
1873 'id' => $item['id'],
1874 'sender_id' => $sender['id'] ,
1876 'recipient_id' => $recipient['id'],
1877 'created_at' => api_date($item['created']),
1878 'sender_screen_name' => $sender['screen_name'],
1879 'recipient_screen_name' => $recipient['screen_name'],
1880 'sender' => $sender,
1881 'recipient' => $recipient,
1884 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1885 unset($ret["sender"]["uid"]);
1886 unset($ret["sender"]["self"]);
1887 unset($ret["recipient"]["uid"]);
1888 unset($ret["recipient"]["self"]);
1890 //don't send title to regular StatusNET requests to avoid confusing these apps
1891 if (x($_GET, 'getText')) {
1892 $ret['title'] = $item['title'] ;
1893 if ($_GET["getText"] == "html") {
1894 $ret['text'] = bbcode($item['body'], false, false);
1896 elseif ($_GET["getText"] == "plain") {
1897 //$ret['text'] = html2plain(bbcode($item['body'], false, false, true), 0);
1898 $ret['text'] = trim(html2plain(bbcode(api_clean_plain_items($item['body']), false, false, 2, true), 0));
1902 $ret['text'] = $item['title']."\n".html2plain(bbcode(api_clean_plain_items($item['body']), false, false, 2, true), 0);
1904 if (isset($_GET["getUserObjects"]) && $_GET["getUserObjects"] == "false") {
1905 unset($ret['sender']);
1906 unset($ret['recipient']);
1912 function api_convert_item($item) {
1914 $body = $item['body'];
1915 $attachments = api_get_attachments($body);
1917 // Workaround for ostatus messages where the title is identically to the body
1918 $html = bbcode(api_clean_plain_items($body), false, false, 2, true);
1919 $statusbody = trim(html2plain($html, 0));
1921 // handle data: images
1922 $statusbody = api_format_items_embeded_images($item,$statusbody);
1924 $statustitle = trim($item['title']);
1926 if (($statustitle != '') and (strpos($statusbody, $statustitle) !== false))
1927 $statustext = trim($statusbody);
1929 $statustext = trim($statustitle."\n\n".$statusbody);
1931 if (($item["network"] == NETWORK_FEED) and (strlen($statustext)> 1000))
1932 $statustext = substr($statustext, 0, 1000)."... \n".$item["plink"];
1934 $statushtml = trim(bbcode($body, false, false));
1936 if ($item['title'] != "")
1937 $statushtml = "<h4>".bbcode($item['title'])."</h4>\n".$statushtml;
1939 $entities = api_get_entitities($statustext, $body);
1941 return(array("text" => $statustext, "html" => $statushtml, "attachments" => $attachments, "entities" => $entities));
1944 function api_get_attachments(&$body) {
1947 $text = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $text);
1949 $URLSearchString = "^\[\]";
1950 $ret = preg_match_all("/\[img\]([$URLSearchString]*)\[\/img\]/ism", $text, $images);
1955 $attachments = array();
1957 foreach ($images[1] AS $image) {
1958 $imagedata = get_photo_info($image);
1961 $attachments[] = array("url" => $image, "mimetype" => $imagedata["mime"], "size" => $imagedata["size"]);
1964 if (strstr($_SERVER['HTTP_USER_AGENT'], "AndStatus"))
1965 foreach ($images[0] AS $orig)
1966 $body = str_replace($orig, "", $body);
1968 return $attachments;
1971 function api_get_entitities(&$text, $bbcode) {
1974 * Links at the first character of the post
1979 $include_entities = strtolower(x($_REQUEST,'include_entities')?$_REQUEST['include_entities']:"false");
1981 if ($include_entities != "true") {
1983 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
1985 foreach ($images[1] AS $image) {
1986 $replace = proxy_url($image);
1987 $text = str_replace($image, $replace, $text);
1992 $bbcode = bb_CleanPictureLinks($bbcode);
1994 // Change pure links in text to bbcode uris
1995 $bbcode = preg_replace("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", '$1[url=$2]$2[/url]', $bbcode);
1997 $entities = array();
1998 $entities["hashtags"] = array();
1999 $entities["symbols"] = array();
2000 $entities["urls"] = array();
2001 $entities["user_mentions"] = array();
2003 $URLSearchString = "^\[\]";
2005 $bbcode = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'#$2',$bbcode);
2007 $bbcode = preg_replace("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism",'[url=$1]$2[/url]',$bbcode);
2008 //$bbcode = preg_replace("/\[url\](.*?)\[\/url\]/ism",'[url=$1]$1[/url]',$bbcode);
2009 $bbcode = preg_replace("/\[video\](.*?)\[\/video\]/ism",'[url=$1]$1[/url]',$bbcode);
2011 $bbcode = preg_replace("/\[youtube\]([A-Za-z0-9\-_=]+)(.*?)\[\/youtube\]/ism",
2012 '[url=https://www.youtube.com/watch?v=$1]https://www.youtube.com/watch?v=$1[/url]', $bbcode);
2013 $bbcode = preg_replace("/\[youtube\](.*?)\[\/youtube\]/ism",'[url=$1]$1[/url]',$bbcode);
2015 $bbcode = preg_replace("/\[vimeo\]([0-9]+)(.*?)\[\/vimeo\]/ism",
2016 '[url=https://vimeo.com/$1]https://vimeo.com/$1[/url]', $bbcode);
2017 $bbcode = preg_replace("/\[vimeo\](.*?)\[\/vimeo\]/ism",'[url=$1]$1[/url]',$bbcode);
2019 $bbcode = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $bbcode);
2021 //preg_match_all("/\[url\]([$URLSearchString]*)\[\/url\]/ism", $bbcode, $urls1);
2022 preg_match_all("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $bbcode, $urls);
2024 $ordered_urls = array();
2025 foreach ($urls[1] AS $id=>$url) {
2026 //$start = strpos($text, $url, $offset);
2027 $start = iconv_strpos($text, $url, 0, "UTF-8");
2028 if (!($start === false))
2029 $ordered_urls[$start] = array("url" => $url, "title" => $urls[2][$id]);
2032 ksort($ordered_urls);
2035 //foreach ($urls[1] AS $id=>$url) {
2036 foreach ($ordered_urls AS $url) {
2037 if ((substr($url["title"], 0, 7) != "http://") AND (substr($url["title"], 0, 8) != "https://") AND
2038 !strpos($url["title"], "http://") AND !strpos($url["title"], "https://"))
2039 $display_url = $url["title"];
2041 $display_url = str_replace(array("http://www.", "https://www."), array("", ""), $url["url"]);
2042 $display_url = str_replace(array("http://", "https://"), array("", ""), $display_url);
2044 if (strlen($display_url) > 26)
2045 $display_url = substr($display_url, 0, 25)."…";
2048 //$start = strpos($text, $url, $offset);
2049 $start = iconv_strpos($text, $url["url"], $offset, "UTF-8");
2050 if (!($start === false)) {
2051 $entities["urls"][] = array("url" => $url["url"],
2052 "expanded_url" => $url["url"],
2053 "display_url" => $display_url,
2054 "indices" => array($start, $start+strlen($url["url"])));
2055 $offset = $start + 1;
2059 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2060 $ordered_images = array();
2061 foreach ($images[1] AS $image) {
2062 //$start = strpos($text, $url, $offset);
2063 $start = iconv_strpos($text, $image, 0, "UTF-8");
2064 if (!($start === false))
2065 $ordered_images[$start] = $image;
2067 //$entities["media"] = array();
2070 foreach ($ordered_images AS $url) {
2071 $display_url = str_replace(array("http://www.", "https://www."), array("", ""), $url);
2072 $display_url = str_replace(array("http://", "https://"), array("", ""), $display_url);
2074 if (strlen($display_url) > 26)
2075 $display_url = substr($display_url, 0, 25)."…";
2077 $start = iconv_strpos($text, $url, $offset, "UTF-8");
2078 if (!($start === false)) {
2079 $image = get_photo_info($url);
2081 // If image cache is activated, then use the following sizes:
2082 // thumb (150), small (340), medium (600) and large (1024)
2083 if (!get_config("system", "proxy_disabled")) {
2084 $media_url = proxy_url($url);
2087 $scale = scale_image($image[0], $image[1], 150);
2088 $sizes["thumb"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2090 if (($image[0] > 150) OR ($image[1] > 150)) {
2091 $scale = scale_image($image[0], $image[1], 340);
2092 $sizes["small"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2095 $scale = scale_image($image[0], $image[1], 600);
2096 $sizes["medium"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2098 if (($image[0] > 600) OR ($image[1] > 600)) {
2099 $scale = scale_image($image[0], $image[1], 1024);
2100 $sizes["large"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2104 $sizes["medium"] = array("w" => $image[0], "h" => $image[1], "resize" => "fit");
2107 $entities["media"][] = array(
2109 "id_str" => (string)$start+1,
2110 "indices" => array($start, $start+strlen($url)),
2111 "media_url" => normalise_link($media_url),
2112 "media_url_https" => $media_url,
2114 "display_url" => $display_url,
2115 "expanded_url" => $url,
2119 $offset = $start + 1;
2125 function api_format_items_embeded_images($item, $text){
2127 $text = preg_replace_callback(
2128 "|data:image/([^;]+)[^=]+=*|m",
2129 function($match) use ($a, $item) {
2130 return $a->get_baseurl()."/display/".$item['guid'];
2136 function api_format_items($r,$user_info, $filter_user = false) {
2141 foreach($r as $item) {
2142 api_share_as_retweet($item);
2144 localize_item($item);
2145 $status_user = api_item_get_user($a,$item);
2147 // Look if the posts are matching if they should be filtered by user id
2148 if ($filter_user AND ($status_user["id"] != $user_info["id"]))
2151 if ($item['thr-parent'] != $item['uri']) {
2152 $r = q("SELECT id FROM item WHERE uid=%d AND uri='%s' LIMIT 1",
2154 dbesc($item['thr-parent']));
2156 $in_reply_to_status_id = intval($r[0]['id']);
2158 $in_reply_to_status_id = intval($item['parent']);
2160 $in_reply_to_status_id_str = (string) intval($item['parent']);
2162 $in_reply_to_screen_name = NULL;
2163 $in_reply_to_user_id = NULL;
2164 $in_reply_to_user_id_str = NULL;
2166 $r = q("SELECT `author-link` FROM item WHERE uid=%d AND id=%d LIMIT 1",
2168 intval($in_reply_to_status_id));
2170 $r = q("SELECT * FROM unique_contacts WHERE `url` = '%s'", dbesc(normalise_link($r[0]['author-link'])));
2173 if ($r[0]['nick'] == "")
2174 $r[0]['nick'] = api_get_nick($r[0]["url"]);
2176 $in_reply_to_screen_name = (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']);
2177 $in_reply_to_user_id = intval($r[0]['id']);
2178 $in_reply_to_user_id_str = (string) intval($r[0]['id']);
2182 $in_reply_to_screen_name = NULL;
2183 $in_reply_to_user_id = NULL;
2184 $in_reply_to_status_id = NULL;
2185 $in_reply_to_user_id_str = NULL;
2186 $in_reply_to_status_id_str = NULL;
2189 $converted = api_convert_item($item);
2192 'text' => $converted["text"],
2193 'truncated' => False,
2194 'created_at'=> api_date($item['created']),
2195 'in_reply_to_status_id' => $in_reply_to_status_id,
2196 'in_reply_to_status_id_str' => $in_reply_to_status_id_str,
2197 'source' => (($item['app']) ? $item['app'] : 'web'),
2198 'id' => intval($item['id']),
2199 'id_str' => (string) intval($item['id']),
2200 'in_reply_to_user_id' => $in_reply_to_user_id,
2201 'in_reply_to_user_id_str' => $in_reply_to_user_id_str,
2202 'in_reply_to_screen_name' => $in_reply_to_screen_name,
2204 'favorited' => $item['starred'] ? true : false,
2205 'user' => $status_user ,
2206 //'entities' => NULL,
2207 'statusnet_html' => $converted["html"],
2208 'statusnet_conversation_id' => $item['parent'],
2211 if (count($converted["attachments"]) > 0)
2212 $status["attachments"] = $converted["attachments"];
2214 if (count($converted["entities"]) > 0)
2215 $status["entities"] = $converted["entities"];
2217 if (($item['item_network'] != "") AND ($status["source"] == 'web'))
2218 $status["source"] = network_to_name($item['item_network'], $user_info['url']);
2219 else if (($item['item_network'] != "") AND (network_to_name($item['item_network'], $user_info['url']) != $status["source"]))
2220 $status["source"] = trim($status["source"].' ('.network_to_name($item['item_network'], $user_info['url']).')');
2223 // Retweets are only valid for top postings
2224 // It doesn't work reliable with the link if its a feed
2225 $IsRetweet = ($item['owner-link'] != $item['author-link']);
2227 $IsRetweet = (($item['owner-name'] != $item['author-name']) OR ($item['owner-avatar'] != $item['author-avatar']));
2229 if ($IsRetweet AND ($item["id"] == $item["parent"])) {
2230 $retweeted_status = $status;
2231 $retweeted_status["user"] = api_get_user($a,$item["author-link"]);
2233 $status["retweeted_status"] = $retweeted_status;
2236 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2237 unset($status["user"]["uid"]);
2238 unset($status["user"]["self"]);
2240 if ($item["coord"] != "") {
2241 $coords = explode(' ',$item["coord"]);
2242 if (count($coords) == 2) {
2243 $status["geo"] = array('type' => 'Point',
2244 'coordinates' => array((float) $coords[0],
2245 (float) $coords[1]));
2255 function api_account_rate_limit_status(&$a,$type) {
2258 'reset_time_in_seconds' => strtotime('now + 1 hour'),
2259 'remaining_hits' => (string) 150,
2260 'hourly_limit' => (string) 150,
2261 'reset_time' => api_date(datetime_convert('UTC','UTC','now + 1 hour',ATOM_TIME)),
2264 $hash['resettime_in_seconds'] = $hash['reset_time_in_seconds'];
2266 return api_apply_template('ratelimit', $type, array('$hash' => $hash));
2269 api_register_func('api/account/rate_limit_status','api_account_rate_limit_status',true);
2271 function api_help_test(&$a,$type) {
2278 return api_apply_template('test', $type, array("$ok" => $ok));
2281 api_register_func('api/help/test','api_help_test',false);
2283 function api_lists(&$a,$type) {
2288 api_register_func('api/lists','api_lists',true);
2290 function api_lists_list(&$a,$type) {
2295 api_register_func('api/lists/list','api_lists_list',true);
2298 * https://dev.twitter.com/docs/api/1/get/statuses/friends
2299 * This function is deprecated by Twitter
2300 * returns: json, xml
2302 function api_statuses_f(&$a, $type, $qtype) {
2303 if (api_user()===false) return false;
2304 $user_info = api_get_user($a);
2306 if (x($_GET,'cursor') && $_GET['cursor']=='undefined'){
2307 /* this is to stop Hotot to load friends multiple times
2308 * I'm not sure if I'm missing return something or
2309 * is a bug in hotot. Workaround, meantime
2313 return array('$users' => $ret);*/
2317 if($qtype == 'friends')
2318 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
2319 if($qtype == 'followers')
2320 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
2322 // friends and followers only for self
2323 if ($user_info['self'] == 0)
2324 $sql_extra = " AND false ";
2326 $r = q("SELECT `nurl` FROM `contact` WHERE `uid` = %d AND `self` = 0 AND `blocked` = 0 AND `pending` = 0 $sql_extra",
2331 foreach($r as $cid){
2332 $user = api_get_user($a, $cid['nurl']);
2333 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2334 unset($user["uid"]);
2335 unset($user["self"]);
2341 return array('$users' => $ret);
2344 function api_statuses_friends(&$a, $type){
2345 $data = api_statuses_f($a,$type,"friends");
2346 if ($data===false) return false;
2347 return api_apply_template("friends", $type, $data);
2349 function api_statuses_followers(&$a, $type){
2350 $data = api_statuses_f($a,$type,"followers");
2351 if ($data===false) return false;
2352 return api_apply_template("friends", $type, $data);
2354 api_register_func('api/statuses/friends','api_statuses_friends',true);
2355 api_register_func('api/statuses/followers','api_statuses_followers',true);
2362 function api_statusnet_config(&$a,$type) {
2363 $name = $a->config['sitename'];
2364 $server = $a->get_hostname();
2365 $logo = $a->get_baseurl() . '/images/friendica-64.png';
2366 $email = $a->config['admin_email'];
2367 $closed = (($a->config['register_policy'] == REGISTER_CLOSED) ? 'true' : 'false');
2368 $private = (($a->config['system']['block_public']) ? 'true' : 'false');
2369 $textlimit = (string) (($a->config['max_import_size']) ? $a->config['max_import_size'] : 200000);
2370 if($a->config['api_import_size'])
2371 $texlimit = string($a->config['api_import_size']);
2372 $ssl = (($a->config['system']['have_ssl']) ? 'true' : 'false');
2373 $sslserver = (($ssl === 'true') ? str_replace('http:','https:',$a->get_baseurl()) : '');
2376 'site' => array('name' => $name,'server' => $server, 'theme' => 'default', 'path' => '',
2377 'logo' => $logo, 'fancy' => true, 'language' => 'en', 'email' => $email, 'broughtby' => '',
2378 'broughtbyurl' => '', 'timezone' => 'UTC', 'closed' => $closed, 'inviteonly' => false,
2379 'private' => $private, 'textlimit' => $textlimit, 'sslserver' => $sslserver, 'ssl' => $ssl,
2380 'shorturllength' => '30',
2381 'friendica' => array(
2382 'FRIENDICA_PLATFORM' => FRIENDICA_PLATFORM,
2383 'FRIENDICA_VERSION' => FRIENDICA_VERSION,
2384 'DFRN_PROTOCOL_VERSION' => DFRN_PROTOCOL_VERSION,
2385 'DB_UPDATE_VERSION' => DB_UPDATE_VERSION
2390 return api_apply_template('config', $type, array('$config' => $config));
2393 api_register_func('api/statusnet/config','api_statusnet_config',false);
2395 function api_statusnet_version(&$a,$type) {
2399 if($type === 'xml') {
2400 header("Content-type: application/xml");
2401 echo '<?xml version="1.0" encoding="UTF-8"?>' . "\r\n" . '<version>0.9.7</version>' . "\r\n";
2404 elseif($type === 'json') {
2405 header("Content-type: application/json");
2410 api_register_func('api/statusnet/version','api_statusnet_version',false);
2413 function api_ff_ids(&$a,$type,$qtype) {
2417 $user_info = api_get_user($a);
2419 if($qtype == 'friends')
2420 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
2421 if($qtype == 'followers')
2422 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
2424 if (!$user_info["self"])
2425 $sql_extra = " AND false ";
2427 $stringify_ids = (x($_REQUEST,'stringify_ids')?$_REQUEST['stringify_ids']:false);
2429 $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",
2435 if($type === 'xml') {
2436 header("Content-type: application/xml");
2437 echo '<?xml version="1.0" encoding="UTF-8"?>' . "\r\n" . '<ids>' . "\r\n";
2439 echo '<id>' . $rr['id'] . '</id>' . "\r\n";
2440 echo '</ids>' . "\r\n";
2443 elseif($type === 'json') {
2445 header("Content-type: application/json");
2450 $ret[] = intval($rr['id']);
2452 echo json_encode($ret);
2458 function api_friends_ids(&$a,$type) {
2459 api_ff_ids($a,$type,'friends');
2461 function api_followers_ids(&$a,$type) {
2462 api_ff_ids($a,$type,'followers');
2464 api_register_func('api/friends/ids','api_friends_ids',true);
2465 api_register_func('api/followers/ids','api_followers_ids',true);
2468 function api_direct_messages_new(&$a, $type) {
2469 if (api_user()===false) return false;
2471 if (!x($_POST, "text") OR (!x($_POST,"screen_name") AND !x($_POST,"user_id"))) return;
2473 $sender = api_get_user($a);
2475 if ($_POST['screen_name']) {
2476 $r = q("SELECT `id`, `nurl`, `network` FROM `contact` WHERE `uid`=%d AND `nick`='%s'",
2478 dbesc($_POST['screen_name']));
2480 // Selecting the id by priority, friendica first
2481 api_best_nickname($r);
2483 $recipient = api_get_user($a, $r[0]['nurl']);
2485 $recipient = api_get_user($a, $_POST['user_id']);
2489 if (x($_REQUEST,'replyto')) {
2490 $r = q('SELECT `parent-uri`, `title` FROM `mail` WHERE `uid`=%d AND `id`=%d',
2492 intval($_REQUEST['replyto']));
2493 $replyto = $r[0]['parent-uri'];
2494 $sub = $r[0]['title'];
2497 if (x($_REQUEST,'title')) {
2498 $sub = $_REQUEST['title'];
2501 $sub = ((strlen($_POST['text'])>10)?substr($_POST['text'],0,10)."...":$_POST['text']);
2505 $id = send_message($recipient['cid'], $_POST['text'], $sub, $replyto);
2508 $r = q("SELECT * FROM `mail` WHERE id=%d", intval($id));
2509 $ret = api_format_messages($r[0], $recipient, $sender);
2512 $ret = array("error"=>$id);
2515 $data = Array('$messages'=>$ret);
2520 $data = api_rss_extra($a, $data, $user_info);
2523 return api_apply_template("direct_messages", $type, $data);
2526 api_register_func('api/direct_messages/new','api_direct_messages_new',true);
2528 function api_direct_messages_box(&$a, $type, $box) {
2529 if (api_user()===false) return false;
2533 $count = (x($_GET,'count')?$_GET['count']:20);
2534 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
2535 if ($page<0) $page=0;
2537 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
2538 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
2540 $user_id = (x($_REQUEST,'user_id')?$_REQUEST['user_id']:"");
2541 $screen_name = (x($_REQUEST,'screen_name')?$_REQUEST['screen_name']:"");
2544 unset($_REQUEST["user_id"]);
2545 unset($_GET["user_id"]);
2547 unset($_REQUEST["screen_name"]);
2548 unset($_GET["screen_name"]);
2550 $user_info = api_get_user($a);
2551 //$profile_url = $a->get_baseurl() . '/profile/' . $a->user['nickname'];
2552 $profile_url = $user_info["url"];
2556 $start = $page*$count;
2559 if ($box=="sentbox") {
2560 $sql_extra = "`mail`.`from-url`='".dbesc( $profile_url )."'";
2562 elseif ($box=="conversation") {
2563 $sql_extra = "`mail`.`parent-uri`='".dbesc( $_GET["uri"] ) ."'";
2565 elseif ($box=="all") {
2566 $sql_extra = "true";
2568 elseif ($box=="inbox") {
2569 $sql_extra = "`mail`.`from-url`!='".dbesc( $profile_url )."'";
2573 $sql_extra .= ' AND `mail`.`id` <= '.intval($max_id);
2575 if ($user_id !="") {
2576 $sql_extra .= ' AND `mail`.`contact-id` = ' . intval($user_id);
2578 elseif($screen_name !=""){
2579 $sql_extra .= " AND `contact`.`nick` = '" . dbesc($screen_name). "'";
2582 $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",
2585 intval($start), intval($count)
2590 foreach($r as $item) {
2591 if ($box == "inbox" || $item['from-url'] != $profile_url){
2592 $recipient = $user_info;
2593 $sender = api_get_user($a,normalise_link($item['contact-url']));
2595 elseif ($box == "sentbox" || $item['from-url'] == $profile_url){
2596 $recipient = api_get_user($a,normalise_link($item['contact-url']));
2597 $sender = $user_info;
2600 $ret[]=api_format_messages($item, $recipient, $sender);
2604 $data = array('$messages' => $ret);
2608 $data = api_rss_extra($a, $data, $user_info);
2611 return api_apply_template("direct_messages", $type, $data);
2615 function api_direct_messages_sentbox(&$a, $type){
2616 return api_direct_messages_box($a, $type, "sentbox");
2618 function api_direct_messages_inbox(&$a, $type){
2619 return api_direct_messages_box($a, $type, "inbox");
2621 function api_direct_messages_all(&$a, $type){
2622 return api_direct_messages_box($a, $type, "all");
2624 function api_direct_messages_conversation(&$a, $type){
2625 return api_direct_messages_box($a, $type, "conversation");
2627 api_register_func('api/direct_messages/conversation','api_direct_messages_conversation',true);
2628 api_register_func('api/direct_messages/all','api_direct_messages_all',true);
2629 api_register_func('api/direct_messages/sent','api_direct_messages_sentbox',true);
2630 api_register_func('api/direct_messages','api_direct_messages_inbox',true);
2634 function api_oauth_request_token(&$a, $type){
2636 $oauth = new FKOAuth1();
2637 $r = $oauth->fetch_request_token(OAuthRequest::from_request());
2638 }catch(Exception $e){
2639 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage()); killme();
2644 function api_oauth_access_token(&$a, $type){
2646 $oauth = new FKOAuth1();
2647 $r = $oauth->fetch_access_token(OAuthRequest::from_request());
2648 }catch(Exception $e){
2649 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage()); killme();
2655 api_register_func('api/oauth/request_token', 'api_oauth_request_token', false);
2656 api_register_func('api/oauth/access_token', 'api_oauth_access_token', false);
2659 function api_fr_photos_list(&$a,$type) {
2660 if (api_user()===false) return false;
2661 $r = q("select distinct `resource-id` from photo where uid = %d and album != 'Contact Photos' ",
2662 intval(local_user())
2667 $ret[] = $rr['resource-id'];
2668 header("Content-type: application/json");
2669 echo json_encode($ret);
2674 function api_fr_photo_detail(&$a,$type) {
2675 if (api_user()===false) return false;
2676 if(! $_REQUEST['photo_id']) return false;
2677 $scale = ((array_key_exists('scale',$_REQUEST)) ? intval($_REQUEST['scale']) : 0);
2678 $r = q("select * from photo where uid = %d and `resource-id` = '%s' and scale = %d limit 1",
2679 intval(local_user()),
2680 dbesc($_REQUEST['photo_id']),
2684 header("Content-type: application/json");
2685 $r[0]['data'] = base64_encode($r[0]['data']);
2686 echo json_encode($r[0]);
2692 api_register_func('api/friendica/photos/list', 'api_fr_photos_list', true);
2693 api_register_func('api/friendica/photo', 'api_fr_photo_detail', true);
2698 * similar as /mod/redir.php
2699 * redirect to 'url' after dfrn auth
2701 * why this when there is mod/redir.php already?
2702 * This use api_user() and api_login()
2705 * c_url: url of remote contact to auth to
2706 * url: string, url to redirect after auth
2708 function api_friendica_remoteauth(&$a) {
2709 $url = ((x($_GET,'url')) ? $_GET['url'] : '');
2710 $c_url = ((x($_GET,'c_url')) ? $_GET['c_url'] : '');
2712 if ($url === '' || $c_url === '')
2713 die((api_error($a, 'json', "Wrong parameters")));
2715 $c_url = normalise_link($c_url);
2719 $r = q("SELECT * FROM `contact` WHERE `id` = %d AND `nurl` = '%s' LIMIT 1",
2724 if ((! count($r)) || ($r[0]['network'] !== NETWORK_DFRN))
2725 die((api_error($a, 'json', "Unknown contact")));
2729 $dfrn_id = $orig_id = (($r[0]['issued-id']) ? $r[0]['issued-id'] : $r[0]['dfrn-id']);
2731 if($r[0]['duplex'] && $r[0]['issued-id']) {
2732 $orig_id = $r[0]['issued-id'];
2733 $dfrn_id = '1:' . $orig_id;
2735 if($r[0]['duplex'] && $r[0]['dfrn-id']) {
2736 $orig_id = $r[0]['dfrn-id'];
2737 $dfrn_id = '0:' . $orig_id;
2740 $sec = random_string();
2742 q("INSERT INTO `profile_check` ( `uid`, `cid`, `dfrn_id`, `sec`, `expire`)
2743 VALUES( %d, %s, '%s', '%s', %d )",
2751 logger($r[0]['name'] . ' ' . $sec, LOGGER_DEBUG);
2752 $dest = (($url) ? '&destination_url=' . $url : '');
2753 goaway ($r[0]['poll'] . '?dfrn_id=' . $dfrn_id
2754 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
2755 . '&type=profile&sec=' . $sec . $dest . $quiet );
2757 api_register_func('api/friendica/remoteauth', 'api_friendica_remoteauth', true);
2761 function api_share_as_retweet(&$item) {
2762 $body = trim($item["body"]);
2764 // Skip if it isn't a pure repeated messages
2765 // Does it start with a share?
2766 if (strpos($body, "[share") > 0)
2769 // Does it end with a share?
2770 if (strlen($body) > (strrpos($body, "[/share]") + 8))
2773 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$1",$body);
2774 // Skip if there is no shared message in there
2775 if ($body == $attributes)
2779 preg_match("/author='(.*?)'/ism", $attributes, $matches);
2780 if ($matches[1] != "")
2781 $author = html_entity_decode($matches[1],ENT_QUOTES,'UTF-8');
2783 preg_match('/author="(.*?)"/ism', $attributes, $matches);
2784 if ($matches[1] != "")
2785 $author = $matches[1];
2788 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
2789 if ($matches[1] != "")
2790 $profile = $matches[1];
2792 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
2793 if ($matches[1] != "")
2794 $profile = $matches[1];
2797 preg_match("/avatar='(.*?)'/ism", $attributes, $matches);
2798 if ($matches[1] != "")
2799 $avatar = $matches[1];
2801 preg_match('/avatar="(.*?)"/ism', $attributes, $matches);
2802 if ($matches[1] != "")
2803 $avatar = $matches[1];
2806 preg_match("/link='(.*?)'/ism", $attributes, $matches);
2807 if ($matches[1] != "")
2808 $link = $matches[1];
2810 preg_match('/link="(.*?)"/ism', $attributes, $matches);
2811 if ($matches[1] != "")
2812 $link = $matches[1];
2814 $shared_body = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$2",$body);
2816 if (($shared_body == "") OR ($profile == "") OR ($author == "") OR ($avatar == ""))
2819 $item["body"] = $shared_body;
2820 $item["author-name"] = $author;
2821 $item["author-link"] = $profile;
2822 $item["author-avatar"] = $avatar;
2823 $item["plink"] = $link;
2829 function api_get_nick($profile) {
2831 - remove trailing jung from profile url
2832 - pump.io check has to check the website
2837 $friendica = preg_replace("=https?://(.*)/profile/(.*)=ism", "$2", $profile);
2838 if ($friendica != $profile)
2842 $diaspora = preg_replace("=https?://(.*)/u/(.*)=ism", "$2", $profile);
2843 if ($diaspora != $profile)
2848 $twitter = preg_replace("=https?://twitter.com/(.*)=ism", "$1", $profile);
2849 if ($twitter != $profile)
2855 $StatusnetHost = preg_replace("=https?://(.*)/user/(.*)=ism", "$1", $profile);
2856 if ($StatusnetHost != $profile) {
2857 $StatusnetUser = preg_replace("=https?://(.*)/user/(.*)=ism", "$2", $profile);
2858 if ($StatusnetUser != $profile) {
2859 $UserData = fetch_url("http://".$StatusnetHost."/api/users/show.json?user_id=".$StatusnetUser);
2860 $user = json_decode($UserData);
2862 $nick = $user->screen_name;
2867 // To-Do: look at the page if its really a pumpio site
2868 //if (!$nick == "") {
2869 // $pumpio = preg_replace("=https?://(.*)/(.*)/=ism", "$2", $profile."/");
2870 // if ($pumpio != $profile)
2872 // <div class="media" id="profile-block" data-profile-id="acct:kabniel@microca.st">
2877 q("UPDATE unique_contacts SET nick = '%s' WHERE url = '%s'",
2878 dbesc($nick), dbesc(normalise_link($profile)));
2885 function api_clean_plain_items($Text) {
2886 $include_entities = strtolower(x($_REQUEST,'include_entities')?$_REQUEST['include_entities']:"false");
2888 $Text = bb_CleanPictureLinks($Text);
2890 $URLSearchString = "^\[\]";
2892 $Text = preg_replace("/([!#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'$1$3',$Text);
2894 if ($include_entities == "true") {
2895 $Text = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'[url=$1]$1[/url]',$Text);
2898 $Text = preg_replace_callback("((.*?)\[class=(.*?)\](.*?)\[\/class\])ism","api_cleanup_share",$Text);
2902 function api_cleanup_share($shared) {
2903 if ($shared[2] != "type-link")
2906 if (!preg_match_all("/\[bookmark\=([^\]]*)\](.*?)\[\/bookmark\]/ism",$shared[3], $bookmark))
2912 if (isset($bookmark[2][0]))
2913 $title = $bookmark[2][0];
2915 if (isset($bookmark[1][0]))
2916 $link = $bookmark[1][0];
2918 if (strpos($shared[1],$title) !== false)
2921 if (strpos($shared[1],$link) !== false)
2924 $text = trim($shared[1]);
2926 //if (strlen($text) < strlen($title))
2927 if (($text == "") AND ($title != ""))
2928 $text .= "\n\n".trim($title);
2931 $text .= "\n".trim($link);
2933 return(trim($text));
2936 function api_best_nickname(&$contacts) {
2937 $best_contact = array();
2939 if (count($contact) == 0)
2942 foreach ($contacts AS $contact)
2943 if ($contact["network"] == "") {
2944 $contact["network"] = "dfrn";
2945 $best_contact = array($contact);
2948 if (sizeof($best_contact) == 0)
2949 foreach ($contacts AS $contact)
2950 if ($contact["network"] == "dfrn")
2951 $best_contact = array($contact);
2953 if (sizeof($best_contact) == 0)
2954 foreach ($contacts AS $contact)
2955 if ($contact["network"] == "dspr")
2956 $best_contact = array($contact);
2958 if (sizeof($best_contact) == 0)
2959 foreach ($contacts AS $contact)
2960 if ($contact["network"] == "stat")
2961 $best_contact = array($contact);
2963 if (sizeof($best_contact) == 0)
2964 foreach ($contacts AS $contact)
2965 if ($contact["network"] == "pump")
2966 $best_contact = array($contact);
2968 if (sizeof($best_contact) == 0)
2969 foreach ($contacts AS $contact)
2970 if ($contact["network"] == "twit")
2971 $best_contact = array($contact);
2973 if (sizeof($best_contact) == 1)
2974 $contacts = $best_contact;
2976 $contacts = array($contacts[0]);
2982 [pagename] => api/1.1/statuses/lookup.json
2983 [id] => 605138389168451584
2984 [include_cards] => true
2985 [cards_platform] => Android-12
2986 [include_entities] => true
2987 [include_my_retweet] => 1
2989 [include_reply_count] => true
2990 [include_descendent_reply_count] => true
2994 Not implemented by now:
2995 statuses/retweets_of_me
3000 account/update_location
3001 account/update_profile_background_image
3002 account/update_profile_image
3006 Not implemented in status.net:
3007 statuses/retweeted_to_me
3008 statuses/retweeted_by_me
3009 direct_messages/destroy
3011 account/update_delivery_device
3012 notifications/follow