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 'url' => $r[0]["url"],
399 'protected' => false,
400 'followers_count' => 0,
401 'friends_count' => 0,
403 'created_at' => api_date(0),
404 'favourites_count' => 0,
406 'time_zone' => 'UTC',
407 'geo_enabled' => false,
409 'statuses_count' => 0,
411 'contributors_enabled' => false,
412 'is_translator' => false,
413 'is_translation_enabled' => false,
414 'profile_image_url' => $r[0]["avatar"],
415 'profile_image_url_https' => $r[0]["avatar"],
416 'following' => false,
417 'follow_request_sent' => false,
418 'notifications' => false,
419 'statusnet_blocking' => false,
420 'notifications' => false,
421 'statusnet_profile_url' => $r[0]["url"],
430 die(api_error($a, $type, t("User not found.")));
434 if($uinfo[0]['self']) {
435 $usr = q("select * from user where uid = %d limit 1",
438 $profile = q("select * from profile where uid = %d and `is-default` = 1 limit 1",
442 //AND `allow_cid`='' AND `allow_gid`='' AND `deny_cid`='' AND `deny_gid`=''",
443 // count public wall messages
444 $r = q("SELECT count(*) as `count` FROM `item`
447 intval($uinfo[0]['uid'])
449 $countitms = $r[0]['count'];
452 //AND `allow_cid`='' AND `allow_gid`='' AND `deny_cid`='' AND `deny_gid`=''",
453 $r = q("SELECT count(*) as `count` FROM `item`
454 WHERE `contact-id` = %d",
455 intval($uinfo[0]['id'])
457 $countitms = $r[0]['count'];
461 $r = q("SELECT count(*) as `count` FROM `contact`
462 WHERE `uid` = %d AND `rel` IN ( %d, %d )
463 AND `self`=0 AND `blocked`=0 AND `pending`=0 AND `hidden`=0",
464 intval($uinfo[0]['uid']),
465 intval(CONTACT_IS_SHARING),
466 intval(CONTACT_IS_FRIEND)
468 $countfriends = $r[0]['count'];
470 $r = q("SELECT count(*) as `count` FROM `contact`
471 WHERE `uid` = %d AND `rel` IN ( %d, %d )
472 AND `self`=0 AND `blocked`=0 AND `pending`=0 AND `hidden`=0",
473 intval($uinfo[0]['uid']),
474 intval(CONTACT_IS_FOLLOWER),
475 intval(CONTACT_IS_FRIEND)
477 $countfollowers = $r[0]['count'];
479 $r = q("SELECT count(*) as `count` FROM item where starred = 1 and uid = %d and deleted = 0",
480 intval($uinfo[0]['uid'])
482 $starred = $r[0]['count'];
485 if(! $uinfo[0]['self']) {
491 // Add a nick if it isn't present there
492 if (($uinfo[0]['nick'] == "") OR ($uinfo[0]['name'] == $uinfo[0]['nick'])) {
493 $uinfo[0]['nick'] = api_get_nick($uinfo[0]["url"]);
496 // Fetching unique id
497 $r = q("SELECT id FROM unique_contacts WHERE url='%s' LIMIT 1", dbesc(normalise_link($uinfo[0]['url'])));
499 // If not there, then add it
500 if (count($r) == 0) {
501 q("INSERT INTO unique_contacts (url, name, nick, avatar) VALUES ('%s', '%s', '%s', '%s')",
502 dbesc(normalise_link($uinfo[0]['url'])), dbesc($uinfo[0]['name']),dbesc($uinfo[0]['nick']), dbesc($uinfo[0]['micro']));
504 $r = q("SELECT id FROM unique_contacts WHERE url='%s' LIMIT 1", dbesc(normalise_link($uinfo[0]['url'])));
507 require_once('include/contact_selectors.php');
508 $network_name = network_to_name($uinfo[0]['network']);
511 'id' => intval($r[0]['id']),
512 'id_str' => (string) intval($r[0]['id']),
513 'name' => (($uinfo[0]['name']) ? $uinfo[0]['name'] : $uinfo[0]['nick']),
514 'screen_name' => (($uinfo[0]['nick']) ? $uinfo[0]['nick'] : $uinfo[0]['name']),
515 'location' => ($usr) ? $usr[0]['default-location'] : $network_name,
516 'description' => (($profile) ? $profile[0]['pdesc'] : NULL),
517 'profile_image_url' => $uinfo[0]['micro'],
518 'profile_image_url_https' => $uinfo[0]['micro'],
519 'url' => $uinfo[0]['url'],
520 'protected' => false,
521 'followers_count' => intval($countfollowers),
522 'friends_count' => intval($countfriends),
523 'created_at' => api_date($uinfo[0]['created']),
524 'favourites_count' => intval($starred),
526 'time_zone' => 'UTC',
527 'statuses_count' => intval($countitms),
528 'following' => (($uinfo[0]['rel'] == CONTACT_IS_FOLLOWER) OR ($uinfo[0]['rel'] == CONTACT_IS_FRIEND)),
530 'statusnet_blocking' => false,
531 'notifications' => false,
532 'statusnet_profile_url' => $a->get_baseurl()."/contacts/".$uinfo[0]['cid'],
533 'uid' => intval($uinfo[0]['uid']),
534 'cid' => intval($uinfo[0]['cid']),
535 'self' => $uinfo[0]['self'],
536 'network' => $uinfo[0]['network'],
543 function api_item_get_user(&$a, $item) {
545 $author = q("SELECT * FROM unique_contacts WHERE url='%s' LIMIT 1",
546 dbesc(normalise_link($item['author-link'])));
548 if (count($author) == 0) {
549 q("INSERT INTO unique_contacts (url, name, avatar) VALUES ('%s', '%s', '%s')",
550 dbesc(normalise_link($item["author-link"])), dbesc($item["author-name"]), dbesc($item["author-avatar"]));
552 $author = q("SELECT id FROM unique_contacts WHERE url='%s' LIMIT 1",
553 dbesc(normalise_link($item['author-link'])));
554 } else if ($item["author-link"].$item["author-name"] != $author[0]["url"].$author[0]["name"]) {
555 q("UPDATE unique_contacts SET name = '%s', avatar = '%s' WHERE url = '%s'",
556 dbesc($item["author-name"]), dbesc($item["author-avatar"]), dbesc(normalise_link($item["author-link"])));
559 $owner = q("SELECT id FROM unique_contacts WHERE url='%s' LIMIT 1",
560 dbesc(normalise_link($item['owner-link'])));
562 if (count($owner) == 0) {
563 q("INSERT INTO unique_contacts (url, name, avatar) VALUES ('%s', '%s', '%s')",
564 dbesc(normalise_link($item["owner-link"])), dbesc($item["owner-name"]), dbesc($item["owner-avatar"]));
566 $owner = q("SELECT id FROM unique_contacts WHERE url='%s' LIMIT 1",
567 dbesc(normalise_link($item['owner-link'])));
568 } else if ($item["owner-link"].$item["owner-name"] != $owner[0]["url"].$owner[0]["name"]) {
569 q("UPDATE unique_contacts SET name = '%s', avatar = '%s' WHERE url = '%s'",
570 dbesc($item["owner-name"]), dbesc($item["owner-avatar"]), dbesc(normalise_link($item["owner-link"])));
573 // Comments in threads may appear as wall-to-wall postings.
574 // So only take the owner at the top posting.
575 if ($item["id"] == $item["parent"])
576 $status_user = api_get_user($a,$item["owner-link"]);
578 $status_user = api_get_user($a,$item["author-link"]);
580 $status_user["protected"] = (($item["allow_cid"] != "") OR
581 ($item["allow_gid"] != "") OR
582 ($item["deny_cid"] != "") OR
583 ($item["deny_gid"] != "") OR
586 return ($status_user);
591 * load api $templatename for $type and replace $data array
593 function api_apply_template($templatename, $type, $data){
601 $data = array_xmlify($data);
602 $tpl = get_markup_template("api_".$templatename."_".$type.".tpl");
604 header ("Content-Type: text/xml");
605 echo '<?xml version="1.0" encoding="UTF-8"?>'."\n".'<status><error>not implemented</error></status>';
608 $ret = replace_macros($tpl, $data);
623 * Returns an HTTP 200 OK response code and a representation of the requesting user if authentication was successful;
624 * returns a 401 status code and an error message if not.
625 * http://developer.twitter.com/doc/get/account/verify_credentials
627 function api_account_verify_credentials(&$a, $type){
628 if (api_user()===false) return false;
630 unset($_REQUEST["user_id"]);
631 unset($_GET["user_id"]);
633 unset($_REQUEST["screen_name"]);
634 unset($_GET["screen_name"]);
636 $skip_status = (x($_REQUEST,'skip_status')?$_REQUEST['skip_status']:false);
638 $user_info = api_get_user($a);
640 // "verified" isn't used here in the standard
641 unset($user_info["verified"]);
643 // - Adding last status
645 $user_info["status"] = api_status_show($a,"raw");
646 if (!count($user_info["status"]))
647 unset($user_info["status"]);
649 unset($user_info["status"]["user"]);
652 // "uid" and "self" are only needed for some internal stuff, so remove it from here
653 unset($user_info["uid"]);
654 unset($user_info["self"]);
656 return api_apply_template("user", $type, array('$user' => $user_info));
659 api_register_func('api/account/verify_credentials','api_account_verify_credentials', true);
663 * get data from $_POST or $_GET
665 function requestdata($k){
666 if (isset($_POST[$k])){
669 if (isset($_GET[$k])){
675 /*Waitman Gobble Mod*/
676 function api_statuses_mediap(&$a, $type) {
677 if (api_user()===false) {
678 logger('api_statuses_update: no user');
681 $user_info = api_get_user($a);
683 $_REQUEST['type'] = 'wall';
684 $_REQUEST['profile_uid'] = api_user();
685 $_REQUEST['api_source'] = true;
686 $txt = requestdata('status');
687 //$txt = urldecode(requestdata('status'));
689 require_once('library/HTMLPurifier.auto.php');
690 require_once('include/html2bbcode.php');
692 if((strpos($txt,'<') !== false) || (strpos($txt,'>') !== false)) {
693 $txt = html2bb_video($txt);
694 $config = HTMLPurifier_Config::createDefault();
695 $config->set('Cache.DefinitionImpl', null);
696 $purifier = new HTMLPurifier($config);
697 $txt = $purifier->purify($txt);
699 $txt = html2bbcode($txt);
701 $a->argv[1]=$user_info['screen_name']; //should be set to username?
703 $_REQUEST['hush']='yeah'; //tell wall_upload function to return img info instead of echo
704 require_once('mod/wall_upload.php');
705 $bebop = wall_upload_post($a);
707 //now that we have the img url in bbcode we can add it to the status and insert the wall item.
708 $_REQUEST['body']=$txt."\n\n".$bebop;
709 require_once('mod/item.php');
712 // this should output the last post (the one we just posted).
713 return api_status_show($a,$type);
715 api_register_func('api/statuses/mediap','api_statuses_mediap', true);
716 /*Waitman Gobble Mod*/
719 function api_statuses_update(&$a, $type) {
720 if (api_user()===false) {
721 logger('api_statuses_update: no user');
725 $user_info = api_get_user($a);
727 // convert $_POST array items to the form we use for web posts.
729 // logger('api_post: ' . print_r($_POST,true));
731 if(requestdata('htmlstatus')) {
732 require_once('library/HTMLPurifier.auto.php');
733 require_once('include/html2bbcode.php');
735 $txt = requestdata('htmlstatus');
736 if((strpos($txt,'<') !== false) || (strpos($txt,'>') !== false)) {
738 $txt = html2bb_video($txt);
740 $config = HTMLPurifier_Config::createDefault();
741 $config->set('Cache.DefinitionImpl', null);
744 $purifier = new HTMLPurifier($config);
745 $txt = $purifier->purify($txt);
747 $_REQUEST['body'] = html2bbcode($txt);
751 $_REQUEST['body'] = requestdata('status');
753 $_REQUEST['title'] = requestdata('title');
755 $parent = requestdata('in_reply_to_status_id');
756 if(ctype_digit($parent))
757 $_REQUEST['parent'] = $parent;
759 $_REQUEST['parent_uri'] = $parent;
761 if(requestdata('lat') && requestdata('long'))
762 $_REQUEST['coord'] = sprintf("%s %s",requestdata('lat'),requestdata('long'));
763 $_REQUEST['profile_uid'] = api_user();
766 $_REQUEST['type'] = 'net-comment';
768 // Check for throttling (maximum posts per day, week and month)
769 $throttle_day = get_config('system','throttle_limit_day');
770 if ($throttle_day > 0) {
771 $datefrom = date("Y-m-d H:i:s", time() - 24*60*60);
773 $r = q("SELECT COUNT(*) AS `posts_day` FROM `item` WHERE `uid`=%d AND `wall`
774 AND `created` > '%s' AND `id` = `parent`",
775 intval(api_user()), dbesc($datefrom));
778 $posts_day = $r[0]["posts_day"];
782 if ($posts_day > $throttle_day) {
783 logger('Daily posting limit reached for user '.api_user(), LOGGER_DEBUG);
784 die(api_error($a, $type, sprintf(t("Daily posting limit of %d posts reached. The post was rejected."), $throttle_day)));
788 $throttle_week = get_config('system','throttle_limit_week');
789 if ($throttle_week > 0) {
790 $datefrom = date("Y-m-d H:i:s", time() - 24*60*60*7);
792 $r = q("SELECT COUNT(*) AS `posts_week` FROM `item` WHERE `uid`=%d AND `wall`
793 AND `created` > '%s' AND `id` = `parent`",
794 intval(api_user()), dbesc($datefrom));
797 $posts_week = $r[0]["posts_week"];
801 if ($posts_week > $throttle_week) {
802 logger('Weekly posting limit reached for user '.api_user(), LOGGER_DEBUG);
803 die(api_error($a, $type, sprintf(t("Weekly posting limit of %d posts reached. The post was rejected."), $throttle_week)));
807 $throttle_month = get_config('system','throttle_limit_month');
808 if ($throttle_month > 0) {
809 $datefrom = date("Y-m-d H:i:s", time() - 24*60*60*30);
811 $r = q("SELECT COUNT(*) AS `posts_month` FROM `item` WHERE `uid`=%d AND `wall`
812 AND `created` > '%s' AND `id` = `parent`",
813 intval(api_user()), dbesc($datefrom));
816 $posts_month = $r[0]["posts_month"];
820 if ($posts_month > $throttle_month) {
821 logger('Monthly posting limit reached for user '.api_user(), LOGGER_DEBUG);
822 die(api_error($a, $type, sprintf(t("Monthly posting limit of %d posts reached. The post was rejected."), $throttle_month)));
826 $_REQUEST['type'] = 'wall';
829 if(x($_FILES,'media')) {
830 // upload the image if we have one
831 $_REQUEST['hush']='yeah'; //tell wall_upload function to return img info instead of echo
832 require_once('mod/wall_upload.php');
833 $media = wall_upload_post($a);
835 $_REQUEST['body'] .= "\n\n".$media;
838 // To-Do: Multiple IDs
839 if (requestdata('media_ids')) {
840 $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",
841 intval(requestdata('media_ids')), api_user());
843 $phototypes = Photo::supportedTypes();
844 $ext = $phototypes[$r[0]['type']];
845 $_REQUEST['body'] .= "\n\n".'[url='.$a->get_baseurl().'/photos/'.$r[0]['nickname'].'/image/'.$r[0]['resource-id'].']';
846 $_REQUEST['body'] .= '[img]'.$a->get_baseurl()."/photo/".$r[0]['resource-id']."-".$r[0]['scale'].".".$ext."[/img][/url]";
850 // set this so that the item_post() function is quiet and doesn't redirect or emit json
852 $_REQUEST['api_source'] = true;
854 if (!x($_REQUEST, "source"))
855 $_REQUEST["source"] = api_source();
857 // call out normal post function
859 require_once('mod/item.php');
862 // this should output the last post (the one we just posted).
863 return api_status_show($a,$type);
865 api_register_func('api/statuses/update','api_statuses_update', true);
866 api_register_func('api/statuses/update_with_media','api_statuses_update', true);
869 function api_media_upload(&$a, $type) {
870 if (api_user()===false) {
875 $user_info = api_get_user($a);
877 if(!x($_FILES,'media')) {
882 require_once('mod/wall_upload.php');
883 $media = wall_upload_post($a, false);
889 $returndata = array();
890 $returndata["media_id"] = $media["id"];
891 $returndata["media_id_string"] = (string)$media["id"];
892 $returndata["size"] = $media["size"];
893 $returndata["image"] = array("w" => $media["width"],
894 "h" => $media["height"],
895 "image_type" => $media["type"]);
897 logger("Media uploaded: ".print_r($returndata, true), LOGGER_DEBUG);
899 return array("media" => $returndata);
902 api_register_func('api/media/upload','api_media_upload', true);
904 function api_status_show(&$a, $type){
905 $user_info = api_get_user($a);
907 logger('api_status_show: user_info: '.print_r($user_info, true), LOGGER_DEBUG);
909 // get last public wall message
910 $lastwall = q("SELECT `item`.*, `i`.`contact-id` as `reply_uid`, `i`.`author-link` AS `item-author`
911 FROM `item`, `item` as `i`
912 WHERE `item`.`contact-id` = %d AND `item`.`uid` = %d
913 AND ((`item`.`author-link` IN ('%s', '%s')) OR (`item`.`owner-link` IN ('%s', '%s')))
914 AND `i`.`id` = `item`.`parent`
915 AND `item`.`type`!='activity'
916 AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''
917 ORDER BY `item`.`created` DESC
919 intval($user_info['cid']),
921 dbesc($user_info['url']),
922 dbesc(normalise_link($user_info['url'])),
923 dbesc($user_info['url']),
924 dbesc(normalise_link($user_info['url']))
927 if (count($lastwall)>0){
928 $lastwall = $lastwall[0];
930 $in_reply_to_status_id = NULL;
931 $in_reply_to_user_id = NULL;
932 $in_reply_to_status_id_str = NULL;
933 $in_reply_to_user_id_str = NULL;
934 $in_reply_to_screen_name = NULL;
935 if (intval($lastwall['parent']) != intval($lastwall['id'])) {
936 $in_reply_to_status_id= intval($lastwall['parent']);
937 $in_reply_to_status_id_str = (string) intval($lastwall['parent']);
939 $r = q("SELECT * FROM unique_contacts WHERE `url` = '%s'", dbesc(normalise_link($lastwall['item-author'])));
941 if ($r[0]['nick'] == "")
942 $r[0]['nick'] = api_get_nick($r[0]["url"]);
944 $in_reply_to_screen_name = (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']);
945 $in_reply_to_user_id = intval($r[0]['id']);
946 $in_reply_to_user_id_str = (string) intval($r[0]['id']);
950 // There seems to be situation, where both fields are identical:
951 // https://github.com/friendica/friendica/issues/1010
952 // This is a bugfix for that.
953 if (intval($in_reply_to_status_id) == intval($lastwall['id'])) {
954 logger('api_status_show: this message should never appear: id: '.$lastwall['id'].' similar to reply-to: '.$in_reply_to_status_id, LOGGER_DEBUG);
955 $in_reply_to_status_id = NULL;
956 $in_reply_to_user_id = NULL;
957 $in_reply_to_status_id_str = NULL;
958 $in_reply_to_user_id_str = NULL;
959 $in_reply_to_screen_name = NULL;
962 $converted = api_convert_item($item);
964 $status_info = array(
965 'created_at' => api_date($lastwall['created']),
966 'id' => intval($lastwall['id']),
967 'id_str' => (string) $lastwall['id'],
968 'text' => $converted["text"],
969 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
970 'truncated' => false,
971 'in_reply_to_status_id' => $in_reply_to_status_id,
972 'in_reply_to_status_id_str' => $in_reply_to_status_id_str,
973 'in_reply_to_user_id' => $in_reply_to_user_id,
974 'in_reply_to_user_id_str' => $in_reply_to_user_id_str,
975 'in_reply_to_screen_name' => $in_reply_to_screen_name,
976 'user' => $user_info,
980 'contributors' => "",
981 'is_quote_status' => false,
982 'retweet_count' => 0,
983 'favorite_count' => 0,
984 'favorited' => $lastwall['starred'] ? true : false,
985 'retweeted' => false,
986 'possibly_sensitive' => false,
988 'statusnet_html' => $converted["html"],
989 'statusnet_conversation_id' => $lastwall['parent'],
992 if (count($converted["attachments"]) > 0)
993 $status_info["attachments"] = $converted["attachments"];
995 if (count($converted["entities"]) > 0)
996 $status_info["entities"] = $converted["entities"];
998 if (($lastwall['item_network'] != "") AND ($status["source"] == 'web'))
999 $status_info["source"] = network_to_name($lastwall['item_network']);
1000 elseif (($lastwall['item_network'] != "") AND (network_to_name($lastwall['item_network']) != $status_info["source"]))
1001 $status_info["source"] = trim($status_info["source"].' ('.network_to_name($lastwall['item_network']).')');
1003 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1004 unset($status_info["user"]["uid"]);
1005 unset($status_info["user"]["self"]);
1009 return($status_info);
1011 return api_apply_template("status", $type, array('$status' => $status_info));
1020 * Returns extended information of a given user, specified by ID or screen name as per the required id parameter.
1021 * The author's most recent status will be returned inline.
1022 * http://developer.twitter.com/doc/get/users/show
1024 function api_users_show(&$a, $type){
1025 $user_info = api_get_user($a);
1027 $lastwall = q("SELECT `item`.*
1028 FROM `item`, `contact`
1029 WHERE `item`.`uid` = %d AND `verb` = '%s' AND `item`.`contact-id` = %d
1030 AND ((`item`.`author-link` IN ('%s', '%s')) OR (`item`.`owner-link` IN ('%s', '%s')))
1031 AND `contact`.`id`=`item`.`contact-id`
1032 AND `type`!='activity'
1033 AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''
1034 ORDER BY `created` DESC
1037 dbesc(ACTIVITY_POST),
1038 intval($user_info['cid']),
1039 dbesc($user_info['url']),
1040 dbesc(normalise_link($user_info['url'])),
1041 dbesc($user_info['url']),
1042 dbesc(normalise_link($user_info['url']))
1044 if (count($lastwall)>0){
1045 $lastwall = $lastwall[0];
1047 $in_reply_to_status_id = NULL;
1048 $in_reply_to_user_id = NULL;
1049 $in_reply_to_status_id_str = NULL;
1050 $in_reply_to_user_id_str = NULL;
1051 $in_reply_to_screen_name = NULL;
1052 if ($lastwall['parent']!=$lastwall['id']) {
1053 $reply = q("SELECT `item`.`id`, `item`.`contact-id` as `reply_uid`, `contact`.`nick` as `reply_author`, `item`.`author-link` AS `item-author`
1054 FROM `item`,`contact` WHERE `contact`.`id`=`item`.`contact-id` AND `item`.`id` = %d", intval($lastwall['parent']));
1055 if (count($reply)>0) {
1056 $in_reply_to_status_id = intval($lastwall['parent']);
1057 $in_reply_to_status_id_str = (string) intval($lastwall['parent']);
1059 $r = q("SELECT * FROM unique_contacts WHERE `url` = '%s'", dbesc(normalise_link($reply[0]['item-author'])));
1061 if ($r[0]['nick'] == "")
1062 $r[0]['nick'] = api_get_nick($r[0]["url"]);
1064 $in_reply_to_screen_name = (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']);
1065 $in_reply_to_user_id = intval($r[0]['id']);
1066 $in_reply_to_user_id_str = (string) intval($r[0]['id']);
1071 $converted = api_convert_item($item);
1073 $user_info['status'] = array(
1074 'text' => $converted["text"],
1075 'truncated' => false,
1076 'created_at' => api_date($lastwall['created']),
1077 'in_reply_to_status_id' => $in_reply_to_status_id,
1078 'in_reply_to_status_id_str' => $in_reply_to_status_id_str,
1079 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
1080 'id' => intval($lastwall['contact-id']),
1081 'id_str' => (string) $lastwall['contact-id'],
1082 'in_reply_to_user_id' => $in_reply_to_user_id,
1083 'in_reply_to_user_id_str' => $in_reply_to_user_id_str,
1084 'in_reply_to_screen_name' => $in_reply_to_screen_name,
1086 'favorited' => $lastwall['starred'] ? true : false,
1087 'statusnet_html' => $converted["html"],
1088 'statusnet_conversation_id' => $lastwall['parent'],
1091 if (count($converted["attachments"]) > 0)
1092 $user_info["status"]["attachments"] = $converted["attachments"];
1094 if (count($converted["entities"]) > 0)
1095 $user_info["status"]["entities"] = $converted["entities"];
1097 if (($lastwall['item_network'] != "") AND ($user_info["status"]["source"] == 'web'))
1098 $user_info["status"]["source"] = network_to_name($lastwall['item_network']);
1099 if (($lastwall['item_network'] != "") AND (network_to_name($lastwall['item_network']) != $user_info["status"]["source"]))
1100 $user_info["status"]["source"] = trim($user_info["status"]["source"].' ('.network_to_name($lastwall['item_network']).')');
1104 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1105 unset($user_info["uid"]);
1106 unset($user_info["self"]);
1108 return api_apply_template("user", $type, array('$user' => $user_info));
1111 api_register_func('api/users/show','api_users_show');
1114 function api_users_search(&$a, $type) {
1115 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1117 $userlist = array();
1119 if (isset($_GET["q"])) {
1120 $r = q("SELECT id FROM unique_contacts WHERE name='%s'", dbesc($_GET["q"]));
1122 $r = q("SELECT id FROM unique_contacts WHERE nick='%s'", dbesc($_GET["q"]));
1125 foreach ($r AS $user) {
1126 $user_info = api_get_user($a, $user["id"]);
1127 //echo print_r($user_info, true)."\n";
1128 $userdata = api_apply_template("user", $type, array('user' => $user_info));
1129 $userlist[] = $userdata["user"];
1131 $userlist = array("users" => $userlist);
1133 die(api_error($a, $type, t("User not found.")));
1135 die(api_error($a, $type, t("User not found.")));
1140 api_register_func('api/users/search','api_users_search');
1144 * http://developer.twitter.com/doc/get/statuses/home_timeline
1146 * TODO: Optional parameters
1147 * TODO: Add reply info
1149 function api_statuses_home_timeline(&$a, $type){
1150 if (api_user()===false) return false;
1152 unset($_REQUEST["user_id"]);
1153 unset($_GET["user_id"]);
1155 unset($_REQUEST["screen_name"]);
1156 unset($_GET["screen_name"]);
1158 $user_info = api_get_user($a);
1159 // get last newtork messages
1163 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1164 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1165 if ($page<0) $page=0;
1166 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1167 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1168 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1169 $exclude_replies = (x($_REQUEST,'exclude_replies')?1:0);
1170 $conversation_id = (x($_REQUEST,'conversation_id')?$_REQUEST['conversation_id']:0);
1172 $start = $page*$count;
1176 $sql_extra .= ' AND `item`.`id` <= '.intval($max_id);
1177 if ($exclude_replies > 0)
1178 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
1179 if ($conversation_id > 0)
1180 $sql_extra .= ' AND `item`.`parent` = '.intval($conversation_id);
1182 $r = q("SELECT STRAIGHT_JOIN `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1183 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1184 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1185 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1186 FROM `item`, `contact`
1187 WHERE `item`.`uid` = %d AND `verb` = '%s'
1188 AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1189 AND `contact`.`id` = `item`.`contact-id`
1190 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1193 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1195 dbesc(ACTIVITY_POST),
1197 intval($start), intval($count)
1200 $ret = api_format_items($r,$user_info);
1202 // Set all posts from the query above to seen
1204 foreach ($r AS $item)
1205 $idarray[] = intval($item["id"]);
1207 $idlist = implode(",", $idarray);
1210 $r = q("UPDATE `item` SET `unseen` = 0 WHERE `unseen` AND `id` IN (%s)", $idlist);
1213 $data = array('$statuses' => $ret);
1217 $data = api_rss_extra($a, $data, $user_info);
1220 $as = api_format_as($a, $ret, $user_info);
1221 $as['title'] = $a->config['sitename']." Home Timeline";
1222 $as['link']['url'] = $a->get_baseurl()."/".$user_info["screen_name"]."/all";
1227 return api_apply_template("timeline", $type, $data);
1229 api_register_func('api/statuses/home_timeline','api_statuses_home_timeline', true);
1230 api_register_func('api/statuses/friends_timeline','api_statuses_home_timeline', true);
1232 function api_statuses_public_timeline(&$a, $type){
1233 if (api_user()===false) return false;
1235 $user_info = api_get_user($a);
1236 // get last newtork messages
1240 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1241 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1242 if ($page<0) $page=0;
1243 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1244 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1245 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1246 $exclude_replies = (x($_REQUEST,'exclude_replies')?1:0);
1247 $conversation_id = (x($_REQUEST,'conversation_id')?$_REQUEST['conversation_id']:0);
1249 $start = $page*$count;
1252 $sql_extra = 'AND `item`.`id` <= '.intval($max_id);
1253 if ($exclude_replies > 0)
1254 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
1255 if ($conversation_id > 0)
1256 $sql_extra .= ' AND `item`.`parent` = '.intval($conversation_id);
1258 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1259 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1260 `contact`.`network`, `contact`.`thumb`, `contact`.`self`, `contact`.`writable`,
1261 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`,
1262 `user`.`nickname`, `user`.`hidewall`
1263 FROM `item` STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
1264 STRAIGHT_JOIN `user` ON `user`.`uid` = `item`.`uid`
1265 WHERE `verb` = '%s' AND `item`.`visible` = 1 AND `item`.`deleted` = 0 and `item`.`moderated` = 0
1266 AND `item`.`allow_cid` = '' AND `item`.`allow_gid` = ''
1267 AND `item`.`deny_cid` = '' AND `item`.`deny_gid` = ''
1268 AND `item`.`private` = 0 AND `item`.`wall` = 1 AND `user`.`hidewall` = 0
1269 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1272 ORDER BY `item`.`id` DESC LIMIT %d, %d ",
1273 dbesc(ACTIVITY_POST),
1278 $ret = api_format_items($r,$user_info);
1281 $data = array('$statuses' => $ret);
1285 $data = api_rss_extra($a, $data, $user_info);
1288 $as = api_format_as($a, $ret, $user_info);
1289 $as['title'] = $a->config['sitename']." Public Timeline";
1290 $as['link']['url'] = $a->get_baseurl()."/";
1295 return api_apply_template("timeline", $type, $data);
1297 api_register_func('api/statuses/public_timeline','api_statuses_public_timeline', true);
1302 function api_statuses_show(&$a, $type){
1303 if (api_user()===false) return false;
1305 $user_info = api_get_user($a);
1308 $id = intval($a->argv[3]);
1311 $id = intval($_REQUEST["id"]);
1315 $id = intval($a->argv[4]);
1317 logger('API: api_statuses_show: '.$id);
1319 $conversation = (x($_REQUEST,'conversation')?1:0);
1323 $sql_extra .= " AND `item`.`parent` = %d ORDER BY `received` ASC ";
1325 $sql_extra .= " AND `item`.`id` = %d";
1327 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1328 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1329 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1330 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1331 FROM `item`, `contact`
1332 WHERE `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1333 AND `contact`.`id` = `item`.`contact-id` AND `item`.`uid` = %d AND `item`.`verb` = '%s'
1334 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1337 dbesc(ACTIVITY_POST),
1342 die(api_error($a, $type, t("There is no status with this id.")));
1344 $ret = api_format_items($r,$user_info);
1346 if ($conversation) {
1347 $data = array('$statuses' => $ret);
1348 return api_apply_template("timeline", $type, $data);
1350 $data = array('$status' => $ret[0]);
1354 $data = api_rss_extra($a, $data, $user_info);
1356 return api_apply_template("status", $type, $data);
1359 api_register_func('api/statuses/show','api_statuses_show', true);
1365 function api_conversation_show(&$a, $type){
1366 if (api_user()===false) return false;
1368 $user_info = api_get_user($a);
1371 $id = intval($a->argv[3]);
1372 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1373 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1374 if ($page<0) $page=0;
1375 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1376 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1378 $start = $page*$count;
1381 $id = intval($_REQUEST["id"]);
1385 $id = intval($a->argv[4]);
1387 logger('API: api_conversation_show: '.$id);
1389 $r = q("SELECT `parent` FROM `item` WHERE `id` = %d", intval($id));
1391 $id = $r[0]["parent"];
1396 $sql_extra = ' AND `item`.`id` <= '.intval($max_id);
1398 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1399 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1400 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1401 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1402 FROM `item` INNER JOIN (SELECT `uri`,`parent` FROM `item` WHERE `id` = %d) AS `temp1`
1403 ON (`item`.`thr-parent` = `temp1`.`uri` AND `item`.`parent` = `temp1`.`parent`), `contact`
1404 WHERE `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1405 AND `item`.`uid` = %d AND `item`.`verb` = '%s' AND `contact`.`id` = `item`.`contact-id`
1406 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1407 AND `item`.`id`>%d $sql_extra
1408 ORDER BY `item`.`id` DESC LIMIT %d ,%d",
1409 intval($id), intval(api_user()),
1410 dbesc(ACTIVITY_POST),
1412 intval($start), intval($count)
1416 die(api_error($a, $type, t("There is no conversation with this id.")));
1418 $ret = api_format_items($r,$user_info);
1420 $data = array('$statuses' => $ret);
1421 return api_apply_template("timeline", $type, $data);
1423 api_register_func('api/conversation/show','api_conversation_show', true);
1429 function api_statuses_repeat(&$a, $type){
1432 if (api_user()===false) return false;
1434 $user_info = api_get_user($a);
1437 $id = intval($a->argv[3]);
1440 $id = intval($_REQUEST["id"]);
1444 $id = intval($a->argv[4]);
1446 logger('API: api_statuses_repeat: '.$id);
1448 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`, `contact`.`nick` as `reply_author`,
1449 `contact`.`name`, `contact`.`photo` as `reply_photo`, `contact`.`url` as `reply_url`, `contact`.`rel`,
1450 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1451 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1452 FROM `item`, `contact`
1453 WHERE `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1454 AND `contact`.`id` = `item`.`contact-id`
1455 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1457 AND `item`.`id`=%d",
1461 if ($r[0]['body'] != "") {
1462 if (!intval(get_config('system','old_share'))) {
1463 if (strpos($r[0]['body'], "[/share]") !== false) {
1464 $pos = strpos($r[0]['body'], "[share");
1465 $post = substr($r[0]['body'], $pos);
1467 $post = share_header($r[0]['author-name'], $r[0]['author-link'], $r[0]['author-avatar'], $r[0]['guid'], $r[0]['created'], $r[0]['plink']);
1469 $post .= $r[0]['body'];
1470 $post .= "[/share]";
1472 $_REQUEST['body'] = $post;
1474 $_REQUEST['body'] = html_entity_decode("♲ ", ENT_QUOTES, 'UTF-8')."[url=".$r[0]['reply_url']."]".$r[0]['reply_author']."[/url] \n".$r[0]['body'];
1476 $_REQUEST['profile_uid'] = api_user();
1477 $_REQUEST['type'] = 'wall';
1478 $_REQUEST['api_source'] = true;
1480 if (!x($_REQUEST, "source"))
1481 $_REQUEST["source"] = api_source();
1483 require_once('mod/item.php');
1487 // this should output the last post (the one we just posted).
1489 return(api_status_show($a,$type));
1491 api_register_func('api/statuses/retweet','api_statuses_repeat', true);
1496 function api_statuses_destroy(&$a, $type){
1497 if (api_user()===false) return false;
1499 $user_info = api_get_user($a);
1502 $id = intval($a->argv[3]);
1505 $id = intval($_REQUEST["id"]);
1509 $id = intval($a->argv[4]);
1511 logger('API: api_statuses_destroy: '.$id);
1513 $ret = api_statuses_show($a, $type);
1515 require_once('include/items.php');
1516 drop_item($id, false);
1520 api_register_func('api/statuses/destroy','api_statuses_destroy', true);
1524 * http://developer.twitter.com/doc/get/statuses/mentions
1527 function api_statuses_mentions(&$a, $type){
1528 if (api_user()===false) return false;
1530 unset($_REQUEST["user_id"]);
1531 unset($_GET["user_id"]);
1533 unset($_REQUEST["screen_name"]);
1534 unset($_GET["screen_name"]);
1536 $user_info = api_get_user($a);
1537 // get last newtork messages
1541 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1542 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1543 if ($page<0) $page=0;
1544 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1545 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1546 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1548 $start = $page*$count;
1550 // Ugly code - should be changed
1551 $myurl = $a->get_baseurl() . '/profile/'. $a->user['nickname'];
1552 $myurl = substr($myurl,strpos($myurl,'://')+3);
1553 //$myurl = str_replace(array('www.','.'),array('','\\.'),$myurl);
1554 $myurl = str_replace('www.','',$myurl);
1555 $diasp_url = str_replace('/profile/','/u/',$myurl);
1558 $sql_extra = ' AND `item`.`id` <= '.intval($max_id);
1560 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1561 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1562 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1563 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1564 FROM `item`, `contact`
1565 WHERE `item`.`uid` = %d AND `verb` = '%s'
1566 AND NOT (`item`.`author-link` IN ('https://%s', 'http://%s'))
1567 AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1568 AND `contact`.`id` = `item`.`contact-id`
1569 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1570 AND `item`.`parent` IN (SELECT `iid` from thread where uid = %d AND `mention` AND !`ignored`)
1573 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1575 dbesc(ACTIVITY_POST),
1576 dbesc(protect_sprintf($myurl)),
1577 dbesc(protect_sprintf($myurl)),
1580 intval($start), intval($count)
1583 $ret = api_format_items($r,$user_info);
1586 $data = array('$statuses' => $ret);
1590 $data = api_rss_extra($a, $data, $user_info);
1593 $as = api_format_as($a, $ret, $user_info);
1594 $as["title"] = $a->config['sitename']." Mentions";
1595 $as['link']['url'] = $a->get_baseurl()."/";
1600 return api_apply_template("timeline", $type, $data);
1602 api_register_func('api/statuses/mentions','api_statuses_mentions', true);
1603 api_register_func('api/statuses/replies','api_statuses_mentions', true);
1606 function api_statuses_user_timeline(&$a, $type){
1607 if (api_user()===false) return false;
1609 $user_info = api_get_user($a);
1610 // get last network messages
1612 logger("api_statuses_user_timeline: api_user: ". api_user() .
1613 "\nuser_info: ".print_r($user_info, true) .
1614 "\n_REQUEST: ".print_r($_REQUEST, true),
1618 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1619 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1620 if ($page<0) $page=0;
1621 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1622 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1623 $exclude_replies = (x($_REQUEST,'exclude_replies')?1:0);
1624 $conversation_id = (x($_REQUEST,'conversation_id')?$_REQUEST['conversation_id']:0);
1626 $start = $page*$count;
1629 if ($user_info['self']==1)
1630 $sql_extra .= " AND `item`.`wall` = 1 ";
1632 if ($exclude_replies > 0)
1633 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
1634 if ($conversation_id > 0)
1635 $sql_extra .= ' AND `item`.`parent` = '.intval($conversation_id);
1637 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1638 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1639 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1640 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1641 FROM `item`, `contact`
1642 WHERE `item`.`uid` = %d AND `verb` = '%s'
1643 AND `item`.`contact-id` = %d
1644 AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1645 AND `contact`.`id` = `item`.`contact-id`
1646 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1649 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1651 dbesc(ACTIVITY_POST),
1652 intval($user_info['cid']),
1654 intval($start), intval($count)
1657 $ret = api_format_items($r,$user_info, true);
1659 $data = array('$statuses' => $ret);
1663 $data = api_rss_extra($a, $data, $user_info);
1666 return api_apply_template("timeline", $type, $data);
1669 api_register_func('api/statuses/user_timeline','api_statuses_user_timeline', true);
1673 * Star/unstar an item
1674 * param: id : id of the item
1676 * api v1 : https://web.archive.org/web/20131019055350/https://dev.twitter.com/docs/api/1/post/favorites/create/%3Aid
1678 function api_favorites_create_destroy(&$a, $type){
1679 if (api_user()===false) return false;
1681 # for versioned api.
1682 # TODO: we need a better global soluton
1684 if ($a->argv[1]=="1.1") $action_argv_id=3;
1686 if ($a->argc<=$action_argv_id) die(api_error($a, $type, t("Invalid request.")));
1687 $action = str_replace(".".$type,"",$a->argv[$action_argv_id]);
1688 if ($a->argc==$action_argv_id+2) {
1689 $itemid = intval($a->argv[$action_argv_id+1]);
1691 $itemid = intval($_REQUEST['id']);
1694 $item = q("SELECT * FROM item WHERE id=%d AND uid=%d",
1695 $itemid, api_user());
1697 if ($item===false || count($item)==0) die(api_error($a, $type, t("Invalid item.")));
1701 $item[0]['starred']=1;
1704 $item[0]['starred']=0;
1707 die(api_error($a, $type, t("Invalid action. ".$action)));
1709 $r = q("UPDATE item SET starred=%d WHERE id=%d AND uid=%d",
1710 $item[0]['starred'], $itemid, api_user());
1712 q("UPDATE thread SET starred=%d WHERE iid=%d AND uid=%d",
1713 $item[0]['starred'], $itemid, api_user());
1715 if ($r===false) die(api_error($a, $type, t("DB error")));
1718 $user_info = api_get_user($a);
1719 $rets = api_format_items($item,$user_info);
1722 $data = array('$status' => $ret);
1726 $data = api_rss_extra($a, $data, $user_info);
1729 return api_apply_template("status", $type, $data);
1732 api_register_func('api/favorites/create', 'api_favorites_create_destroy', true);
1733 api_register_func('api/favorites/destroy', 'api_favorites_create_destroy', true);
1735 function api_favorites(&$a, $type){
1738 if (api_user()===false) return false;
1740 $called_api= array();
1742 $user_info = api_get_user($a);
1744 // in friendica starred item are private
1745 // return favorites only for self
1746 logger('api_favorites: self:' . $user_info['self']);
1748 if ($user_info['self']==0) {
1754 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1755 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1756 $count = (x($_GET,'count')?$_GET['count']:20);
1757 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1758 if ($page<0) $page=0;
1760 $start = $page*$count;
1763 $sql_extra .= ' AND `item`.`id` <= '.intval($max_id);
1765 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1766 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1767 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1768 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1769 FROM `item`, `contact`
1770 WHERE `item`.`uid` = %d
1771 AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1772 AND `item`.`starred` = 1
1773 AND `contact`.`id` = `item`.`contact-id`
1774 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1777 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1780 intval($start), intval($count)
1783 $ret = api_format_items($r,$user_info);
1787 $data = array('$statuses' => $ret);
1791 $data = api_rss_extra($a, $data, $user_info);
1794 return api_apply_template("timeline", $type, $data);
1797 api_register_func('api/favorites','api_favorites', true);
1802 function api_format_as($a, $ret, $user_info) {
1805 $as['title'] = $a->config['sitename']." Public Timeline";
1807 foreach ($ret as $item) {
1808 $singleitem["actor"]["displayName"] = $item["user"]["name"];
1809 $singleitem["actor"]["id"] = $item["user"]["contact_url"];
1810 $avatar[0]["url"] = $item["user"]["profile_image_url"];
1811 $avatar[0]["rel"] = "avatar";
1812 $avatar[0]["type"] = "";
1813 $avatar[0]["width"] = 96;
1814 $avatar[0]["height"] = 96;
1815 $avatar[1]["url"] = $item["user"]["profile_image_url"];
1816 $avatar[1]["rel"] = "avatar";
1817 $avatar[1]["type"] = "";
1818 $avatar[1]["width"] = 48;
1819 $avatar[1]["height"] = 48;
1820 $avatar[2]["url"] = $item["user"]["profile_image_url"];
1821 $avatar[2]["rel"] = "avatar";
1822 $avatar[2]["type"] = "";
1823 $avatar[2]["width"] = 24;
1824 $avatar[2]["height"] = 24;
1825 $singleitem["actor"]["avatarLinks"] = $avatar;
1827 $singleitem["actor"]["image"]["url"] = $item["user"]["profile_image_url"];
1828 $singleitem["actor"]["image"]["rel"] = "avatar";
1829 $singleitem["actor"]["image"]["type"] = "";
1830 $singleitem["actor"]["image"]["width"] = 96;
1831 $singleitem["actor"]["image"]["height"] = 96;
1832 $singleitem["actor"]["type"] = "person";
1833 $singleitem["actor"]["url"] = $item["person"]["contact_url"];
1834 $singleitem["actor"]["statusnet:profile_info"]["local_id"] = $item["user"]["id"];
1835 $singleitem["actor"]["statusnet:profile_info"]["following"] = $item["user"]["following"] ? "true" : "false";
1836 $singleitem["actor"]["statusnet:profile_info"]["blocking"] = "false";
1837 $singleitem["actor"]["contact"]["preferredUsername"] = $item["user"]["screen_name"];
1838 $singleitem["actor"]["contact"]["displayName"] = $item["user"]["name"];
1839 $singleitem["actor"]["contact"]["addresses"] = "";
1841 $singleitem["body"] = $item["text"];
1842 $singleitem["object"]["displayName"] = $item["text"];
1843 $singleitem["object"]["id"] = $item["url"];
1844 $singleitem["object"]["type"] = "note";
1845 $singleitem["object"]["url"] = $item["url"];
1846 //$singleitem["context"] =;
1847 $singleitem["postedTime"] = date("c", strtotime($item["published"]));
1848 $singleitem["provider"]["objectType"] = "service";
1849 $singleitem["provider"]["displayName"] = "Test";
1850 $singleitem["provider"]["url"] = "http://test.tld";
1851 $singleitem["title"] = $item["text"];
1852 $singleitem["verb"] = "post";
1853 $singleitem["statusnet:notice_info"]["local_id"] = $item["id"];
1854 $singleitem["statusnet:notice_info"]["source"] = $item["source"];
1855 $singleitem["statusnet:notice_info"]["favorite"] = "false";
1856 $singleitem["statusnet:notice_info"]["repeated"] = "false";
1857 //$singleitem["original"] = $item;
1858 $items[] = $singleitem;
1860 $as['items'] = $items;
1861 $as['link']['url'] = $a->get_baseurl()."/".$user_info["screen_name"]."/all";
1862 $as['link']['rel'] = "alternate";
1863 $as['link']['type'] = "text/html";
1867 function api_format_messages($item, $recipient, $sender) {
1868 // standard meta information
1870 'id' => $item['id'],
1871 'sender_id' => $sender['id'] ,
1873 'recipient_id' => $recipient['id'],
1874 'created_at' => api_date($item['created']),
1875 'sender_screen_name' => $sender['screen_name'],
1876 'recipient_screen_name' => $recipient['screen_name'],
1877 'sender' => $sender,
1878 'recipient' => $recipient,
1881 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1882 unset($ret["sender"]["uid"]);
1883 unset($ret["sender"]["self"]);
1884 unset($ret["recipient"]["uid"]);
1885 unset($ret["recipient"]["self"]);
1887 //don't send title to regular StatusNET requests to avoid confusing these apps
1888 if (x($_GET, 'getText')) {
1889 $ret['title'] = $item['title'] ;
1890 if ($_GET["getText"] == "html") {
1891 $ret['text'] = bbcode($item['body'], false, false);
1893 elseif ($_GET["getText"] == "plain") {
1894 //$ret['text'] = html2plain(bbcode($item['body'], false, false, true), 0);
1895 $ret['text'] = trim(html2plain(bbcode(api_clean_plain_items($item['body']), false, false, 2, true), 0));
1899 $ret['text'] = $item['title']."\n".html2plain(bbcode(api_clean_plain_items($item['body']), false, false, 2, true), 0);
1901 if (isset($_GET["getUserObjects"]) && $_GET["getUserObjects"] == "false") {
1902 unset($ret['sender']);
1903 unset($ret['recipient']);
1909 function api_convert_item($item) {
1911 $body = $item['body'];
1912 $attachments = api_get_attachments($body);
1914 // Workaround for ostatus messages where the title is identically to the body
1915 $html = bbcode(api_clean_plain_items($body), false, false, 2, true);
1916 $statusbody = trim(html2plain($html, 0));
1918 // handle data: images
1919 $statusbody = api_format_items_embeded_images($item,$statusbody);
1921 $statustitle = trim($item['title']);
1923 if (($statustitle != '') and (strpos($statusbody, $statustitle) !== false))
1924 $statustext = trim($statusbody);
1926 $statustext = trim($statustitle."\n\n".$statusbody);
1928 if (($item["network"] == NETWORK_FEED) and (strlen($statustext)> 1000))
1929 $statustext = substr($statustext, 0, 1000)."... \n".$item["plink"];
1931 $statushtml = trim(bbcode($body, false, false));
1933 if ($item['title'] != "")
1934 $statushtml = "<h4>".bbcode($item['title'])."</h4>\n".$statushtml;
1936 $entities = api_get_entitities($statustext, $body);
1938 return(array("text" => $statustext, "html" => $statushtml, "attachments" => $attachments, "entities" => $entities));
1941 function api_get_attachments(&$body) {
1944 $text = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $text);
1946 $URLSearchString = "^\[\]";
1947 $ret = preg_match_all("/\[img\]([$URLSearchString]*)\[\/img\]/ism", $text, $images);
1952 $attachments = array();
1954 foreach ($images[1] AS $image) {
1955 $imagedata = get_photo_info($image);
1958 $attachments[] = array("url" => $image, "mimetype" => $imagedata["mime"], "size" => $imagedata["size"]);
1961 if (strstr($_SERVER['HTTP_USER_AGENT'], "AndStatus"))
1962 foreach ($images[0] AS $orig)
1963 $body = str_replace($orig, "", $body);
1965 return $attachments;
1968 function api_get_entitities(&$text, $bbcode) {
1971 * Links at the first character of the post
1976 $include_entities = strtolower(x($_REQUEST,'include_entities')?$_REQUEST['include_entities']:"false");
1978 if ($include_entities != "true") {
1979 require_once("mod/proxy.php");
1981 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
1983 foreach ($images[1] AS $image) {
1984 $replace = proxy_url($image);
1985 $text = str_replace($image, $replace, $text);
1990 $bbcode = bb_CleanPictureLinks($bbcode);
1992 // Change pure links in text to bbcode uris
1993 $bbcode = preg_replace("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", '$1[url=$2]$2[/url]', $bbcode);
1995 $entities = array();
1996 $entities["hashtags"] = array();
1997 $entities["symbols"] = array();
1998 $entities["urls"] = array();
1999 $entities["user_mentions"] = array();
2001 $URLSearchString = "^\[\]";
2003 $bbcode = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'#$2',$bbcode);
2005 $bbcode = preg_replace("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism",'[url=$1]$2[/url]',$bbcode);
2006 //$bbcode = preg_replace("/\[url\](.*?)\[\/url\]/ism",'[url=$1]$1[/url]',$bbcode);
2007 $bbcode = preg_replace("/\[video\](.*?)\[\/video\]/ism",'[url=$1]$1[/url]',$bbcode);
2009 $bbcode = preg_replace("/\[youtube\]([A-Za-z0-9\-_=]+)(.*?)\[\/youtube\]/ism",
2010 '[url=https://www.youtube.com/watch?v=$1]https://www.youtube.com/watch?v=$1[/url]', $bbcode);
2011 $bbcode = preg_replace("/\[youtube\](.*?)\[\/youtube\]/ism",'[url=$1]$1[/url]',$bbcode);
2013 $bbcode = preg_replace("/\[vimeo\]([0-9]+)(.*?)\[\/vimeo\]/ism",
2014 '[url=https://vimeo.com/$1]https://vimeo.com/$1[/url]', $bbcode);
2015 $bbcode = preg_replace("/\[vimeo\](.*?)\[\/vimeo\]/ism",'[url=$1]$1[/url]',$bbcode);
2017 $bbcode = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $bbcode);
2019 //preg_match_all("/\[url\]([$URLSearchString]*)\[\/url\]/ism", $bbcode, $urls1);
2020 preg_match_all("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $bbcode, $urls);
2022 $ordered_urls = array();
2023 foreach ($urls[1] AS $id=>$url) {
2024 //$start = strpos($text, $url, $offset);
2025 $start = iconv_strpos($text, $url, 0, "UTF-8");
2026 if (!($start === false))
2027 $ordered_urls[$start] = array("url" => $url, "title" => $urls[2][$id]);
2030 ksort($ordered_urls);
2033 //foreach ($urls[1] AS $id=>$url) {
2034 foreach ($ordered_urls AS $url) {
2035 if ((substr($url["title"], 0, 7) != "http://") AND (substr($url["title"], 0, 8) != "https://") AND
2036 !strpos($url["title"], "http://") AND !strpos($url["title"], "https://"))
2037 $display_url = $url["title"];
2039 $display_url = str_replace(array("http://www.", "https://www."), array("", ""), $url["url"]);
2040 $display_url = str_replace(array("http://", "https://"), array("", ""), $display_url);
2042 if (strlen($display_url) > 26)
2043 $display_url = substr($display_url, 0, 25)."…";
2046 //$start = strpos($text, $url, $offset);
2047 $start = iconv_strpos($text, $url["url"], $offset, "UTF-8");
2048 if (!($start === false)) {
2049 $entities["urls"][] = array("url" => $url["url"],
2050 "expanded_url" => $url["url"],
2051 "display_url" => $display_url,
2052 "indices" => array($start, $start+strlen($url["url"])));
2053 $offset = $start + 1;
2057 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2058 $ordered_images = array();
2059 foreach ($images[1] AS $image) {
2060 //$start = strpos($text, $url, $offset);
2061 $start = iconv_strpos($text, $image, 0, "UTF-8");
2062 if (!($start === false))
2063 $ordered_images[$start] = $image;
2065 //$entities["media"] = array();
2068 foreach ($ordered_images AS $url) {
2069 $display_url = str_replace(array("http://www.", "https://www."), array("", ""), $url);
2070 $display_url = str_replace(array("http://", "https://"), array("", ""), $display_url);
2072 if (strlen($display_url) > 26)
2073 $display_url = substr($display_url, 0, 25)."…";
2075 $start = iconv_strpos($text, $url, $offset, "UTF-8");
2076 if (!($start === false)) {
2077 $image = get_photo_info($url);
2079 // If image cache is activated, then use the following sizes:
2080 // thumb (150), small (340), medium (600) and large (1024)
2081 if (!get_config("system", "proxy_disabled")) {
2082 require_once("mod/proxy.php");
2083 $media_url = proxy_url($url);
2086 $scale = scale_image($image[0], $image[1], 150);
2087 $sizes["thumb"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2089 if (($image[0] > 150) OR ($image[1] > 150)) {
2090 $scale = scale_image($image[0], $image[1], 340);
2091 $sizes["small"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2094 $scale = scale_image($image[0], $image[1], 600);
2095 $sizes["medium"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2097 if (($image[0] > 600) OR ($image[1] > 600)) {
2098 $scale = scale_image($image[0], $image[1], 1024);
2099 $sizes["large"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2103 $sizes["medium"] = array("w" => $image[0], "h" => $image[1], "resize" => "fit");
2106 $entities["media"][] = array(
2108 "id_str" => (string)$start+1,
2109 "indices" => array($start, $start+strlen($url)),
2110 "media_url" => normalise_link($media_url),
2111 "media_url_https" => $media_url,
2113 "display_url" => $display_url,
2114 "expanded_url" => $url,
2118 $offset = $start + 1;
2124 function api_format_items_embeded_images($item, $text){
2126 $text = preg_replace_callback(
2127 "|data:image/([^;]+)[^=]+=*|m",
2128 function($match) use ($a, $item) {
2129 return $a->get_baseurl()."/display/".$item['guid'];
2135 function api_format_items($r,$user_info, $filter_user = false) {
2140 foreach($r as $item) {
2141 api_share_as_retweet($item);
2143 localize_item($item);
2144 $status_user = api_item_get_user($a,$item);
2146 // Look if the posts are matching if they should be filtered by user id
2147 if ($filter_user AND ($status_user["id"] != $user_info["id"]))
2150 if ($item['thr-parent'] != $item['uri']) {
2151 $r = q("SELECT id FROM item WHERE uid=%d AND uri='%s' LIMIT 1",
2153 dbesc($item['thr-parent']));
2155 $in_reply_to_status_id = intval($r[0]['id']);
2157 $in_reply_to_status_id = intval($item['parent']);
2159 $in_reply_to_status_id_str = (string) intval($item['parent']);
2161 $in_reply_to_screen_name = NULL;
2162 $in_reply_to_user_id = NULL;
2163 $in_reply_to_user_id_str = NULL;
2165 $r = q("SELECT `author-link` FROM item WHERE uid=%d AND id=%d LIMIT 1",
2167 intval($in_reply_to_status_id));
2169 $r = q("SELECT * FROM unique_contacts WHERE `url` = '%s'", dbesc(normalise_link($r[0]['author-link'])));
2172 if ($r[0]['nick'] == "")
2173 $r[0]['nick'] = api_get_nick($r[0]["url"]);
2175 $in_reply_to_screen_name = (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']);
2176 $in_reply_to_user_id = intval($r[0]['id']);
2177 $in_reply_to_user_id_str = (string) intval($r[0]['id']);
2181 $in_reply_to_screen_name = NULL;
2182 $in_reply_to_user_id = NULL;
2183 $in_reply_to_status_id = NULL;
2184 $in_reply_to_user_id_str = NULL;
2185 $in_reply_to_status_id_str = NULL;
2188 $converted = api_convert_item($item);
2191 'text' => $converted["text"],
2192 'truncated' => False,
2193 'created_at'=> api_date($item['created']),
2194 'in_reply_to_status_id' => $in_reply_to_status_id,
2195 'in_reply_to_status_id_str' => $in_reply_to_status_id_str,
2196 'source' => (($item['app']) ? $item['app'] : 'web'),
2197 'id' => intval($item['id']),
2198 'id_str' => (string) intval($item['id']),
2199 'in_reply_to_user_id' => $in_reply_to_user_id,
2200 'in_reply_to_user_id_str' => $in_reply_to_user_id_str,
2201 'in_reply_to_screen_name' => $in_reply_to_screen_name,
2203 'favorited' => $item['starred'] ? true : false,
2204 'user' => $status_user ,
2205 //'entities' => NULL,
2206 'statusnet_html' => $converted["html"],
2207 'statusnet_conversation_id' => $item['parent'],
2210 if (count($converted["attachments"]) > 0)
2211 $status["attachments"] = $converted["attachments"];
2213 if (count($converted["entities"]) > 0)
2214 $status["entities"] = $converted["entities"];
2216 if (($item['item_network'] != "") AND ($status["source"] == 'web'))
2217 $status["source"] = network_to_name($item['item_network']);
2218 else if (($item['item_network'] != "") AND (network_to_name($item['item_network']) != $status["source"]))
2219 $status["source"] = trim($status["source"].' ('.network_to_name($item['item_network']).')');
2222 // Retweets are only valid for top postings
2223 // It doesn't work reliable with the link if its a feed
2224 $IsRetweet = ($item['owner-link'] != $item['author-link']);
2226 $IsRetweet = (($item['owner-name'] != $item['author-name']) OR ($item['owner-avatar'] != $item['author-avatar']));
2228 if ($IsRetweet AND ($item["id"] == $item["parent"])) {
2229 $retweeted_status = $status;
2230 $retweeted_status["user"] = api_get_user($a,$item["author-link"]);
2232 $status["retweeted_status"] = $retweeted_status;
2235 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2236 unset($status["user"]["uid"]);
2237 unset($status["user"]["self"]);
2239 if ($item["coord"] != "") {
2240 $coords = explode(' ',$item["coord"]);
2241 if (count($coords) == 2) {
2242 $status["geo"] = array('type' => 'Point',
2243 'coordinates' => array((float) $coords[0],
2244 (float) $coords[1]));
2254 function api_account_rate_limit_status(&$a,$type) {
2257 'reset_time_in_seconds' => strtotime('now + 1 hour'),
2258 'remaining_hits' => (string) 150,
2259 'hourly_limit' => (string) 150,
2260 'reset_time' => api_date(datetime_convert('UTC','UTC','now + 1 hour',ATOM_TIME)),
2263 $hash['resettime_in_seconds'] = $hash['reset_time_in_seconds'];
2265 return api_apply_template('ratelimit', $type, array('$hash' => $hash));
2268 api_register_func('api/account/rate_limit_status','api_account_rate_limit_status',true);
2270 function api_help_test(&$a,$type) {
2277 return api_apply_template('test', $type, array("$ok" => $ok));
2280 api_register_func('api/help/test','api_help_test',false);
2282 function api_lists(&$a,$type) {
2287 api_register_func('api/lists','api_lists',true);
2289 function api_lists_list(&$a,$type) {
2294 api_register_func('api/lists/list','api_lists_list',true);
2297 * https://dev.twitter.com/docs/api/1/get/statuses/friends
2298 * This function is deprecated by Twitter
2299 * returns: json, xml
2301 function api_statuses_f(&$a, $type, $qtype) {
2302 if (api_user()===false) return false;
2303 $user_info = api_get_user($a);
2305 if (x($_GET,'cursor') && $_GET['cursor']=='undefined'){
2306 /* this is to stop Hotot to load friends multiple times
2307 * I'm not sure if I'm missing return something or
2308 * is a bug in hotot. Workaround, meantime
2312 return array('$users' => $ret);*/
2316 if($qtype == 'friends')
2317 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
2318 if($qtype == 'followers')
2319 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
2321 // friends and followers only for self
2322 if ($user_info['self'] == 0)
2323 $sql_extra = " AND false ";
2325 $r = q("SELECT `nurl` FROM `contact` WHERE `uid` = %d AND `self` = 0 AND `blocked` = 0 AND `pending` = 0 $sql_extra",
2330 foreach($r as $cid){
2331 $user = api_get_user($a, $cid['nurl']);
2332 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2333 unset($user["uid"]);
2334 unset($user["self"]);
2340 return array('$users' => $ret);
2343 function api_statuses_friends(&$a, $type){
2344 $data = api_statuses_f($a,$type,"friends");
2345 if ($data===false) return false;
2346 return api_apply_template("friends", $type, $data);
2348 function api_statuses_followers(&$a, $type){
2349 $data = api_statuses_f($a,$type,"followers");
2350 if ($data===false) return false;
2351 return api_apply_template("friends", $type, $data);
2353 api_register_func('api/statuses/friends','api_statuses_friends',true);
2354 api_register_func('api/statuses/followers','api_statuses_followers',true);
2361 function api_statusnet_config(&$a,$type) {
2362 $name = $a->config['sitename'];
2363 $server = $a->get_hostname();
2364 $logo = $a->get_baseurl() . '/images/friendica-64.png';
2365 $email = $a->config['admin_email'];
2366 $closed = (($a->config['register_policy'] == REGISTER_CLOSED) ? 'true' : 'false');
2367 $private = (($a->config['system']['block_public']) ? 'true' : 'false');
2368 $textlimit = (string) (($a->config['max_import_size']) ? $a->config['max_import_size'] : 200000);
2369 if($a->config['api_import_size'])
2370 $texlimit = string($a->config['api_import_size']);
2371 $ssl = (($a->config['system']['have_ssl']) ? 'true' : 'false');
2372 $sslserver = (($ssl === 'true') ? str_replace('http:','https:',$a->get_baseurl()) : '');
2375 'site' => array('name' => $name,'server' => $server, 'theme' => 'default', 'path' => '',
2376 'logo' => $logo, 'fancy' => true, 'language' => 'en', 'email' => $email, 'broughtby' => '',
2377 'broughtbyurl' => '', 'timezone' => 'UTC', 'closed' => $closed, 'inviteonly' => false,
2378 'private' => $private, 'textlimit' => $textlimit, 'sslserver' => $sslserver, 'ssl' => $ssl,
2379 'shorturllength' => '30',
2380 'friendica' => array(
2381 'FRIENDICA_PLATFORM' => FRIENDICA_PLATFORM,
2382 'FRIENDICA_VERSION' => FRIENDICA_VERSION,
2383 'DFRN_PROTOCOL_VERSION' => DFRN_PROTOCOL_VERSION,
2384 'DB_UPDATE_VERSION' => DB_UPDATE_VERSION
2389 return api_apply_template('config', $type, array('$config' => $config));
2392 api_register_func('api/statusnet/config','api_statusnet_config',false);
2394 function api_statusnet_version(&$a,$type) {
2398 if($type === 'xml') {
2399 header("Content-type: application/xml");
2400 echo '<?xml version="1.0" encoding="UTF-8"?>' . "\r\n" . '<version>0.9.7</version>' . "\r\n";
2403 elseif($type === 'json') {
2404 header("Content-type: application/json");
2409 api_register_func('api/statusnet/version','api_statusnet_version',false);
2412 function api_ff_ids(&$a,$type,$qtype) {
2416 $user_info = api_get_user($a);
2418 if($qtype == 'friends')
2419 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
2420 if($qtype == 'followers')
2421 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
2423 if (!$user_info["self"])
2424 $sql_extra = " AND false ";
2426 $stringify_ids = (x($_REQUEST,'stringify_ids')?$_REQUEST['stringify_ids']:false);
2428 $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",
2434 if($type === 'xml') {
2435 header("Content-type: application/xml");
2436 echo '<?xml version="1.0" encoding="UTF-8"?>' . "\r\n" . '<ids>' . "\r\n";
2438 echo '<id>' . $rr['id'] . '</id>' . "\r\n";
2439 echo '</ids>' . "\r\n";
2442 elseif($type === 'json') {
2444 header("Content-type: application/json");
2449 $ret[] = intval($rr['id']);
2451 echo json_encode($ret);
2457 function api_friends_ids(&$a,$type) {
2458 api_ff_ids($a,$type,'friends');
2460 function api_followers_ids(&$a,$type) {
2461 api_ff_ids($a,$type,'followers');
2463 api_register_func('api/friends/ids','api_friends_ids',true);
2464 api_register_func('api/followers/ids','api_followers_ids',true);
2467 function api_direct_messages_new(&$a, $type) {
2468 if (api_user()===false) return false;
2470 if (!x($_POST, "text") OR (!x($_POST,"screen_name") AND !x($_POST,"user_id"))) return;
2472 $sender = api_get_user($a);
2474 require_once("include/message.php");
2476 if ($_POST['screen_name']) {
2477 $r = q("SELECT `id`, `nurl`, `network` FROM `contact` WHERE `uid`=%d AND `nick`='%s'",
2479 dbesc($_POST['screen_name']));
2481 // Selecting the id by priority, friendica first
2482 api_best_nickname($r);
2484 $recipient = api_get_user($a, $r[0]['nurl']);
2486 $recipient = api_get_user($a, $_POST['user_id']);
2490 if (x($_REQUEST,'replyto')) {
2491 $r = q('SELECT `parent-uri`, `title` FROM `mail` WHERE `uid`=%d AND `id`=%d',
2493 intval($_REQUEST['replyto']));
2494 $replyto = $r[0]['parent-uri'];
2495 $sub = $r[0]['title'];
2498 if (x($_REQUEST,'title')) {
2499 $sub = $_REQUEST['title'];
2502 $sub = ((strlen($_POST['text'])>10)?substr($_POST['text'],0,10)."...":$_POST['text']);
2506 $id = send_message($recipient['cid'], $_POST['text'], $sub, $replyto);
2509 $r = q("SELECT * FROM `mail` WHERE id=%d", intval($id));
2510 $ret = api_format_messages($r[0], $recipient, $sender);
2513 $ret = array("error"=>$id);
2516 $data = Array('$messages'=>$ret);
2521 $data = api_rss_extra($a, $data, $user_info);
2524 return api_apply_template("direct_messages", $type, $data);
2527 api_register_func('api/direct_messages/new','api_direct_messages_new',true);
2529 function api_direct_messages_box(&$a, $type, $box) {
2530 if (api_user()===false) return false;
2534 $count = (x($_GET,'count')?$_GET['count']:20);
2535 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
2536 if ($page<0) $page=0;
2538 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
2539 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
2541 $user_id = (x($_REQUEST,'user_id')?$_REQUEST['user_id']:"");
2542 $screen_name = (x($_REQUEST,'screen_name')?$_REQUEST['screen_name']:"");
2545 unset($_REQUEST["user_id"]);
2546 unset($_GET["user_id"]);
2548 unset($_REQUEST["screen_name"]);
2549 unset($_GET["screen_name"]);
2551 $user_info = api_get_user($a);
2552 //$profile_url = $a->get_baseurl() . '/profile/' . $a->user['nickname'];
2553 $profile_url = $user_info["url"];
2557 $start = $page*$count;
2560 if ($box=="sentbox") {
2561 $sql_extra = "`mail`.`from-url`='".dbesc( $profile_url )."'";
2563 elseif ($box=="conversation") {
2564 $sql_extra = "`mail`.`parent-uri`='".dbesc( $_GET["uri"] ) ."'";
2566 elseif ($box=="all") {
2567 $sql_extra = "true";
2569 elseif ($box=="inbox") {
2570 $sql_extra = "`mail`.`from-url`!='".dbesc( $profile_url )."'";
2574 $sql_extra .= ' AND `mail`.`id` <= '.intval($max_id);
2576 if ($user_id !="") {
2577 $sql_extra .= ' AND `mail`.`contact-id` = ' . intval($user_id);
2579 elseif($screen_name !=""){
2580 $sql_extra .= " AND `contact`.`nick` = '" . dbesc($screen_name). "'";
2583 $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",
2586 intval($start), intval($count)
2591 foreach($r as $item) {
2592 if ($box == "inbox" || $item['from-url'] != $profile_url){
2593 $recipient = $user_info;
2594 $sender = api_get_user($a,normalise_link($item['contact-url']));
2596 elseif ($box == "sentbox" || $item['from-url'] == $profile_url){
2597 $recipient = api_get_user($a,normalise_link($item['contact-url']));
2598 $sender = $user_info;
2601 $ret[]=api_format_messages($item, $recipient, $sender);
2605 $data = array('$messages' => $ret);
2609 $data = api_rss_extra($a, $data, $user_info);
2612 return api_apply_template("direct_messages", $type, $data);
2616 function api_direct_messages_sentbox(&$a, $type){
2617 return api_direct_messages_box($a, $type, "sentbox");
2619 function api_direct_messages_inbox(&$a, $type){
2620 return api_direct_messages_box($a, $type, "inbox");
2622 function api_direct_messages_all(&$a, $type){
2623 return api_direct_messages_box($a, $type, "all");
2625 function api_direct_messages_conversation(&$a, $type){
2626 return api_direct_messages_box($a, $type, "conversation");
2628 api_register_func('api/direct_messages/conversation','api_direct_messages_conversation',true);
2629 api_register_func('api/direct_messages/all','api_direct_messages_all',true);
2630 api_register_func('api/direct_messages/sent','api_direct_messages_sentbox',true);
2631 api_register_func('api/direct_messages','api_direct_messages_inbox',true);
2635 function api_oauth_request_token(&$a, $type){
2637 $oauth = new FKOAuth1();
2638 $r = $oauth->fetch_request_token(OAuthRequest::from_request());
2639 }catch(Exception $e){
2640 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage()); killme();
2645 function api_oauth_access_token(&$a, $type){
2647 $oauth = new FKOAuth1();
2648 $r = $oauth->fetch_access_token(OAuthRequest::from_request());
2649 }catch(Exception $e){
2650 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage()); killme();
2656 api_register_func('api/oauth/request_token', 'api_oauth_request_token', false);
2657 api_register_func('api/oauth/access_token', 'api_oauth_access_token', false);
2660 function api_fr_photos_list(&$a,$type) {
2661 if (api_user()===false) return false;
2662 $r = q("select distinct `resource-id` from photo where uid = %d and album != 'Contact Photos' ",
2663 intval(local_user())
2668 $ret[] = $rr['resource-id'];
2669 header("Content-type: application/json");
2670 echo json_encode($ret);
2675 function api_fr_photo_detail(&$a,$type) {
2676 if (api_user()===false) return false;
2677 if(! $_REQUEST['photo_id']) return false;
2678 $scale = ((array_key_exists('scale',$_REQUEST)) ? intval($_REQUEST['scale']) : 0);
2679 $r = q("select * from photo where uid = %d and `resource-id` = '%s' and scale = %d limit 1",
2680 intval(local_user()),
2681 dbesc($_REQUEST['photo_id']),
2685 header("Content-type: application/json");
2686 $r[0]['data'] = base64_encode($r[0]['data']);
2687 echo json_encode($r[0]);
2693 api_register_func('api/friendica/photos/list', 'api_fr_photos_list', true);
2694 api_register_func('api/friendica/photo', 'api_fr_photo_detail', true);
2699 * similar as /mod/redir.php
2700 * redirect to 'url' after dfrn auth
2702 * why this when there is mod/redir.php already?
2703 * This use api_user() and api_login()
2706 * c_url: url of remote contact to auth to
2707 * url: string, url to redirect after auth
2709 function api_friendica_remoteauth(&$a) {
2710 $url = ((x($_GET,'url')) ? $_GET['url'] : '');
2711 $c_url = ((x($_GET,'c_url')) ? $_GET['c_url'] : '');
2713 if ($url === '' || $c_url === '')
2714 die((api_error($a, 'json', "Wrong parameters")));
2716 $c_url = normalise_link($c_url);
2720 $r = q("SELECT * FROM `contact` WHERE `id` = %d AND `nurl` = '%s' LIMIT 1",
2725 if ((! count($r)) || ($r[0]['network'] !== NETWORK_DFRN))
2726 die((api_error($a, 'json', "Unknown contact")));
2730 $dfrn_id = $orig_id = (($r[0]['issued-id']) ? $r[0]['issued-id'] : $r[0]['dfrn-id']);
2732 if($r[0]['duplex'] && $r[0]['issued-id']) {
2733 $orig_id = $r[0]['issued-id'];
2734 $dfrn_id = '1:' . $orig_id;
2736 if($r[0]['duplex'] && $r[0]['dfrn-id']) {
2737 $orig_id = $r[0]['dfrn-id'];
2738 $dfrn_id = '0:' . $orig_id;
2741 $sec = random_string();
2743 q("INSERT INTO `profile_check` ( `uid`, `cid`, `dfrn_id`, `sec`, `expire`)
2744 VALUES( %d, %s, '%s', '%s', %d )",
2752 logger($r[0]['name'] . ' ' . $sec, LOGGER_DEBUG);
2753 $dest = (($url) ? '&destination_url=' . $url : '');
2754 goaway ($r[0]['poll'] . '?dfrn_id=' . $dfrn_id
2755 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
2756 . '&type=profile&sec=' . $sec . $dest . $quiet );
2758 api_register_func('api/friendica/remoteauth', 'api_friendica_remoteauth', true);
2762 function api_share_as_retweet(&$item) {
2763 $body = trim($item["body"]);
2765 // Skip if it isn't a pure repeated messages
2766 // Does it start with a share?
2767 if (strpos($body, "[share") > 0)
2770 // Does it end with a share?
2771 if (strlen($body) > (strrpos($body, "[/share]") + 8))
2774 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$1",$body);
2775 // Skip if there is no shared message in there
2776 if ($body == $attributes)
2780 preg_match("/author='(.*?)'/ism", $attributes, $matches);
2781 if ($matches[1] != "")
2782 $author = html_entity_decode($matches[1],ENT_QUOTES,'UTF-8');
2784 preg_match('/author="(.*?)"/ism', $attributes, $matches);
2785 if ($matches[1] != "")
2786 $author = $matches[1];
2789 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
2790 if ($matches[1] != "")
2791 $profile = $matches[1];
2793 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
2794 if ($matches[1] != "")
2795 $profile = $matches[1];
2798 preg_match("/avatar='(.*?)'/ism", $attributes, $matches);
2799 if ($matches[1] != "")
2800 $avatar = $matches[1];
2802 preg_match('/avatar="(.*?)"/ism', $attributes, $matches);
2803 if ($matches[1] != "")
2804 $avatar = $matches[1];
2807 preg_match("/link='(.*?)'/ism", $attributes, $matches);
2808 if ($matches[1] != "")
2809 $link = $matches[1];
2811 preg_match('/link="(.*?)"/ism', $attributes, $matches);
2812 if ($matches[1] != "")
2813 $link = $matches[1];
2815 $shared_body = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$2",$body);
2817 if (($shared_body == "") OR ($profile == "") OR ($author == "") OR ($avatar == ""))
2820 $item["body"] = $shared_body;
2821 $item["author-name"] = $author;
2822 $item["author-link"] = $profile;
2823 $item["author-avatar"] = $avatar;
2824 $item["plink"] = $link;
2830 function api_get_nick($profile) {
2832 - remove trailing jung from profile url
2833 - pump.io check has to check the website
2838 $friendica = preg_replace("=https?://(.*)/profile/(.*)=ism", "$2", $profile);
2839 if ($friendica != $profile)
2843 $diaspora = preg_replace("=https?://(.*)/u/(.*)=ism", "$2", $profile);
2844 if ($diaspora != $profile)
2849 $twitter = preg_replace("=https?://twitter.com/(.*)=ism", "$1", $profile);
2850 if ($twitter != $profile)
2856 $StatusnetHost = preg_replace("=https?://(.*)/user/(.*)=ism", "$1", $profile);
2857 if ($StatusnetHost != $profile) {
2858 $StatusnetUser = preg_replace("=https?://(.*)/user/(.*)=ism", "$2", $profile);
2859 if ($StatusnetUser != $profile) {
2860 $UserData = fetch_url("http://".$StatusnetHost."/api/users/show.json?user_id=".$StatusnetUser);
2861 $user = json_decode($UserData);
2863 $nick = $user->screen_name;
2868 // To-Do: look at the page if its really a pumpio site
2869 //if (!$nick == "") {
2870 // $pumpio = preg_replace("=https?://(.*)/(.*)/=ism", "$2", $profile."/");
2871 // if ($pumpio != $profile)
2873 // <div class="media" id="profile-block" data-profile-id="acct:kabniel@microca.st">
2878 q("UPDATE unique_contacts SET nick = '%s' WHERE url = '%s'",
2879 dbesc($nick), dbesc(normalise_link($profile)));
2886 function api_clean_plain_items($Text) {
2887 $include_entities = strtolower(x($_REQUEST,'include_entities')?$_REQUEST['include_entities']:"false");
2889 $Text = bb_CleanPictureLinks($Text);
2891 $URLSearchString = "^\[\]";
2893 $Text = preg_replace("/([!#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'$1$3',$Text);
2895 if ($include_entities == "true") {
2896 $Text = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'[url=$1]$1[/url]',$Text);
2899 $Text = preg_replace_callback("((.*?)\[class=(.*?)\](.*?)\[\/class\])ism","api_cleanup_share",$Text);
2903 function api_cleanup_share($shared) {
2904 if ($shared[2] != "type-link")
2907 if (!preg_match_all("/\[bookmark\=([^\]]*)\](.*?)\[\/bookmark\]/ism",$shared[3], $bookmark))
2913 if (isset($bookmark[2][0]))
2914 $title = $bookmark[2][0];
2916 if (isset($bookmark[1][0]))
2917 $link = $bookmark[1][0];
2919 if (strpos($shared[1],$title) !== false)
2922 if (strpos($shared[1],$link) !== false)
2925 $text = trim($shared[1]);
2927 //if (strlen($text) < strlen($title))
2928 if (($text == "") AND ($title != ""))
2929 $text .= "\n\n".trim($title);
2932 $text .= "\n".trim($link);
2934 return(trim($text));
2937 function api_best_nickname(&$contacts) {
2938 $best_contact = array();
2940 if (count($contact) == 0)
2943 foreach ($contacts AS $contact)
2944 if ($contact["network"] == "") {
2945 $contact["network"] = "dfrn";
2946 $best_contact = array($contact);
2949 if (sizeof($best_contact) == 0)
2950 foreach ($contacts AS $contact)
2951 if ($contact["network"] == "dfrn")
2952 $best_contact = array($contact);
2954 if (sizeof($best_contact) == 0)
2955 foreach ($contacts AS $contact)
2956 if ($contact["network"] == "dspr")
2957 $best_contact = array($contact);
2959 if (sizeof($best_contact) == 0)
2960 foreach ($contacts AS $contact)
2961 if ($contact["network"] == "stat")
2962 $best_contact = array($contact);
2964 if (sizeof($best_contact) == 0)
2965 foreach ($contacts AS $contact)
2966 if ($contact["network"] == "pump")
2967 $best_contact = array($contact);
2969 if (sizeof($best_contact) == 0)
2970 foreach ($contacts AS $contact)
2971 if ($contact["network"] == "twit")
2972 $best_contact = array($contact);
2974 if (sizeof($best_contact) == 1)
2975 $contacts = $best_contact;
2977 $contacts = array($contacts[0]);
2983 [pagename] => api/1.1/statuses/lookup.json
2984 [id] => 605138389168451584
2985 [include_cards] => true
2986 [cards_platform] => Android-12
2987 [include_entities] => true
2988 [include_my_retweet] => 1
2990 [include_reply_count] => true
2991 [include_descendent_reply_count] => true
2995 Not implemented by now:
2996 statuses/retweets_of_me
3001 account/update_location
3002 account/update_profile_background_image
3003 account/update_profile_image
3007 Not implemented in status.net:
3008 statuses/retweeted_to_me
3009 statuses/retweeted_by_me
3010 direct_messages/destroy
3012 account/update_delivery_device
3013 notifications/follow