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('include/html2bbcode.php');
16 require_once('mod/wall_upload.php');
17 require_once("mod/proxy.php");
18 require_once("include/message.php");
30 // It is not sufficient to use local_user() to check whether someone is allowed to use the API,
31 // because this will open CSRF holes (just embed an image with src=friendicasite.com/api/statuses/update?status=CSRF
32 // into a page, and visitors will post something without noticing it).
33 // Instead, use this function.
34 if ($_SESSION["allow_api"])
40 function api_source() {
41 if (requestdata('source'))
42 return (requestdata('source'));
44 // Support for known clients that doesn't send a source name
45 if (strstr($_SERVER['HTTP_USER_AGENT'], "Twidere"))
48 logger("Unrecognized user-agent ".$_SERVER['HTTP_USER_AGENT'], LOGGER_DEBUG);
53 function api_date($str){
54 //Wed May 23 06:01:13 +0000 2007
55 return datetime_convert('UTC', 'UTC', $str, "D M d H:i:s +0000 Y" );
59 function api_register_func($path, $func, $auth=false){
61 $API[$path] = array('func'=>$func, 'auth'=>$auth);
63 // Workaround for hotot
64 $path = str_replace("api/", "api/1.1/", $path);
65 $API[$path] = array('func'=>$func, 'auth'=>$auth);
72 function api_login(&$a){
75 $oauth = new FKOAuth1();
76 list($consumer,$token) = $oauth->verify_request(OAuthRequest::from_request());
77 if (!is_null($token)){
78 $oauth->loginUser($token->uid);
79 call_hooks('logged_in', $a->user);
82 echo __file__.__line__.__function__."<pre>"; var_dump($consumer, $token); die();
84 logger(__file__.__line__.__function__."\n".$e);
85 //die(__file__.__line__.__function__."<pre>".$e); die();
90 // workaround for HTTP-auth in CGI mode
91 if(x($_SERVER,'REDIRECT_REMOTE_USER')) {
92 $userpass = base64_decode(substr($_SERVER["REDIRECT_REMOTE_USER"],6)) ;
93 if(strlen($userpass)) {
94 list($name, $password) = explode(':', $userpass);
95 $_SERVER['PHP_AUTH_USER'] = $name;
96 $_SERVER['PHP_AUTH_PW'] = $password;
100 if (!isset($_SERVER['PHP_AUTH_USER'])) {
101 logger('API_login: ' . print_r($_SERVER,true), LOGGER_DEBUG);
102 header('WWW-Authenticate: Basic realm="Friendica"');
103 header('HTTP/1.0 401 Unauthorized');
104 die((api_error($a, 'json', "This api requires login")));
106 //die('This api requires login');
109 $user = $_SERVER['PHP_AUTH_USER'];
110 $password = $_SERVER['PHP_AUTH_PW'];
111 $encrypted = hash('whirlpool',trim($password));
113 // allow "user@server" login (but ignore 'server' part)
114 $at=strstr($user, "@", true);
115 if ( $at ) $user=$at;
118 * next code from mod/auth.php. needs better solution
123 'username' => trim($user),
124 'password' => trim($password),
125 'authenticated' => 0,
126 'user_record' => null
131 * A plugin indicates successful login by setting 'authenticated' to non-zero value and returning a user record
132 * Plugins should never set 'authenticated' except to indicate success - as hooks may be chained
133 * and later plugins should not interfere with an earlier one that succeeded.
137 call_hooks('authenticate', $addon_auth);
139 if(($addon_auth['authenticated']) && (count($addon_auth['user_record']))) {
140 $record = $addon_auth['user_record'];
143 // process normal login request
145 $r = q("SELECT * FROM `user` WHERE ( `email` = '%s' OR `nickname` = '%s' )
146 AND `password` = '%s' AND `blocked` = 0 AND `account_expired` = 0 AND `account_removed` = 0 AND `verified` = 1 LIMIT 1",
155 if((! $record) || (! count($record))) {
156 logger('API_login failure: ' . print_r($_SERVER,true), LOGGER_DEBUG);
157 header('WWW-Authenticate: Basic realm="Friendica"');
158 header('HTTP/1.0 401 Unauthorized');
159 die('This api requires login');
162 authenticate_success($record); $_SESSION["allow_api"] = true;
164 call_hooks('logged_in', $a->user);
168 /**************************
169 * MAIN API ENTRY POINT *
170 **************************/
171 function api_call(&$a){
172 GLOBAL $API, $called_api;
176 foreach ($API as $p=>$info){
177 if (strpos($a->query_string, $p)===0){
178 $called_api= explode("/",$p);
179 //unset($_SERVER['PHP_AUTH_USER']);
180 if ($info['auth']===true && api_user()===false) {
184 load_contact_links(api_user());
186 logger('API call for ' . $a->user['username'] . ': ' . $a->query_string);
187 logger('API parameters: ' . print_r($_REQUEST,true));
189 if (strpos($a->query_string, ".xml")>0) $type="xml";
190 if (strpos($a->query_string, ".json")>0) $type="json";
191 if (strpos($a->query_string, ".rss")>0) $type="rss";
192 if (strpos($a->query_string, ".atom")>0) $type="atom";
193 if (strpos($a->query_string, ".as")>0) $type="as";
195 $stamp = microtime(true);
196 $r = call_user_func($info['func'], $a, $type);
197 $duration = (float)(microtime(true)-$stamp);
198 logger("API call duration: ".round($duration, 2)."\t".$a->query_string, LOGGER_DEBUG);
200 if ($r===false) return;
204 $r = mb_convert_encoding($r, "UTF-8",mb_detect_encoding($r));
205 header ("Content-Type: text/xml");
206 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
209 header ("Content-Type: application/json");
211 $json = json_encode($rr);
212 if ($_GET['callback'])
213 $json = $_GET['callback']."(".$json.")";
217 header ("Content-Type: application/rss+xml");
218 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
221 header ("Content-Type: application/atom+xml");
222 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
225 //header ("Content-Type: application/json");
227 // return json_encode($rr);
228 return json_encode($r);
232 //echo "<pre>"; var_dump($r); die();
235 header("HTTP/1.1 404 Not Found");
236 logger('API call not implemented: '.$a->query_string." - ".print_r($_REQUEST,true));
237 return(api_error($a, $type, "not implemented"));
241 function api_error(&$a, $type, $error) {
242 # TODO: https://dev.twitter.com/overview/api/response-codes
243 $r = "<status><error>".$error."</error><request>".$a->query_string."</request></status>";
246 header ("Content-Type: text/xml");
247 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
250 header ("Content-Type: application/json");
251 return json_encode(array('error' => $error, 'request' => $a->query_string));
254 header ("Content-Type: application/rss+xml");
255 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
258 header ("Content-Type: application/atom+xml");
259 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
267 function api_rss_extra(&$a, $arr, $user_info){
268 if (is_null($user_info)) $user_info = api_get_user($a);
269 $arr['$user'] = $user_info;
270 $arr['$rss'] = array(
271 'alternate' => $user_info['url'],
272 'self' => $a->get_baseurl(). "/". $a->query_string,
273 'base' => $a->get_baseurl(),
274 'updated' => api_date(null),
275 'atom_updated' => datetime_convert('UTC','UTC','now',ATOM_TIME),
276 'language' => $user_info['language'],
277 'logo' => $a->get_baseurl()."/images/friendica-32.png",
285 * Unique contact to contact url.
287 function api_unique_id_to_url($id){
288 $r = q("SELECT `url` FROM `unique_contacts` WHERE `id`=%d LIMIT 1",
291 return ($r[0]["url"]);
297 * Returns user info array.
299 function api_get_user(&$a, $contact_id = Null, $type = "json"){
306 logger("api_get_user: Fetching user data for user ".$contact_id, LOGGER_DEBUG);
308 // Searching for contact URL
309 if(!is_null($contact_id) AND (intval($contact_id) == 0)){
310 $user = dbesc(normalise_link($contact_id));
312 $extra_query = "AND `contact`.`nurl` = '%s' ";
313 if (api_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(api_user());
316 // Searching for unique contact id
317 if(!is_null($contact_id) AND (intval($contact_id) != 0)){
318 $user = dbesc(api_unique_id_to_url($contact_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());
328 if(is_null($user) && x($_GET, 'user_id')) {
329 $user = dbesc(api_unique_id_to_url($_GET['user_id']));
332 die(api_error($a, $type, t("User not found.")));
335 $extra_query = "AND `contact`.`nurl` = '%s' ";
336 if (api_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(api_user());
338 if(is_null($user) && x($_GET, 'screen_name')) {
339 $user = dbesc($_GET['screen_name']);
341 $extra_query = "AND `contact`.`nick` = '%s' ";
342 if (api_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(api_user());
345 if (is_null($user) AND ($a->argc > (count($called_api)-1)) AND (count($called_api) > 0)){
346 $argid = count($called_api);
347 list($user, $null) = explode(".",$a->argv[$argid]);
348 if(is_numeric($user)){
349 $user = dbesc(api_unique_id_to_url($user));
355 $extra_query = "AND `contact`.`nurl` = '%s' ";
356 if (api_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(api_user());
358 $user = dbesc($user);
360 $extra_query = "AND `contact`.`nick` = '%s' ";
361 if (api_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(api_user());
365 logger("api_get_user: user ".$user, LOGGER_DEBUG);
368 if (api_user()===false) {
369 api_login($a); return False;
371 $user = $_SESSION['uid'];
372 $extra_query = "AND `contact`.`uid` = %d AND `contact`.`self` = 1 ";
377 logger('api_user: ' . $extra_query . ', user: ' . $user);
379 $uinfo = q("SELECT *, `contact`.`id` as `cid` FROM `contact`
385 // Selecting the id by priority, friendica first
386 api_best_nickname($uinfo);
388 // if the contact wasn't found, fetch it from the unique contacts
389 if (count($uinfo)==0) {
393 $r = q("SELECT * FROM `unique_contacts` WHERE `url`='%s' LIMIT 1", $url);
395 $r = q("SELECT * FROM `unique_contacts` WHERE `nick`='%s' LIMIT 1", $nick);
398 // If no nick where given, extract it from the address
399 if (($r[0]['nick'] == "") OR ($r[0]['name'] == $r[0]['nick']))
400 $r[0]['nick'] = api_get_nick($r[0]["url"]);
404 'id_str' => (string) $r[0]["id"],
405 'name' => $r[0]["name"],
406 'screen_name' => (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']),
408 'description' => NULL,
409 'url' => $r[0]["url"],
410 'protected' => false,
411 'followers_count' => 0,
412 'friends_count' => 0,
414 'created_at' => api_date(0),
415 'favourites_count' => 0,
417 'time_zone' => 'UTC',
418 'geo_enabled' => false,
420 'statuses_count' => 0,
422 'contributors_enabled' => false,
423 'is_translator' => false,
424 'is_translation_enabled' => false,
425 'profile_image_url' => $r[0]["avatar"],
426 'profile_image_url_https' => $r[0]["avatar"],
427 'following' => false,
428 'follow_request_sent' => false,
429 'notifications' => false,
430 'statusnet_blocking' => false,
431 'notifications' => false,
432 'statusnet_profile_url' => $r[0]["url"],
441 die(api_error($a, $type, t("User not found.")));
445 if($uinfo[0]['self']) {
446 $usr = q("select * from user where uid = %d limit 1",
449 $profile = q("select * from profile where uid = %d and `is-default` = 1 limit 1",
453 //AND `allow_cid`='' AND `allow_gid`='' AND `deny_cid`='' AND `deny_gid`=''",
454 // count public wall messages
455 $r = q("SELECT count(*) as `count` FROM `item`
458 intval($uinfo[0]['uid'])
460 $countitms = $r[0]['count'];
463 //AND `allow_cid`='' AND `allow_gid`='' AND `deny_cid`='' AND `deny_gid`=''",
464 $r = q("SELECT count(*) as `count` FROM `item`
465 WHERE `contact-id` = %d",
466 intval($uinfo[0]['id'])
468 $countitms = $r[0]['count'];
472 $r = q("SELECT count(*) as `count` FROM `contact`
473 WHERE `uid` = %d AND `rel` IN ( %d, %d )
474 AND `self`=0 AND `blocked`=0 AND `pending`=0 AND `hidden`=0",
475 intval($uinfo[0]['uid']),
476 intval(CONTACT_IS_SHARING),
477 intval(CONTACT_IS_FRIEND)
479 $countfriends = $r[0]['count'];
481 $r = q("SELECT count(*) as `count` FROM `contact`
482 WHERE `uid` = %d AND `rel` IN ( %d, %d )
483 AND `self`=0 AND `blocked`=0 AND `pending`=0 AND `hidden`=0",
484 intval($uinfo[0]['uid']),
485 intval(CONTACT_IS_FOLLOWER),
486 intval(CONTACT_IS_FRIEND)
488 $countfollowers = $r[0]['count'];
490 $r = q("SELECT count(*) as `count` FROM item where starred = 1 and uid = %d and deleted = 0",
491 intval($uinfo[0]['uid'])
493 $starred = $r[0]['count'];
496 if(! $uinfo[0]['self']) {
502 // Add a nick if it isn't present there
503 if (($uinfo[0]['nick'] == "") OR ($uinfo[0]['name'] == $uinfo[0]['nick'])) {
504 $uinfo[0]['nick'] = api_get_nick($uinfo[0]["url"]);
507 // Fetching unique id
508 $r = q("SELECT id FROM `unique_contacts` WHERE `url`='%s' LIMIT 1", dbesc(normalise_link($uinfo[0]['url'])));
510 // If not there, then add it
511 if (count($r) == 0) {
512 q("INSERT INTO `unique_contacts` (`url`, `name`, `nick`, `avatar`) VALUES ('%s', '%s', '%s', '%s')",
513 dbesc(normalise_link($uinfo[0]['url'])), dbesc($uinfo[0]['name']),dbesc($uinfo[0]['nick']), dbesc($uinfo[0]['micro']));
515 $r = q("SELECT `id` FROM `unique_contacts` WHERE `url`='%s' LIMIT 1", dbesc(normalise_link($uinfo[0]['url'])));
518 $network_name = network_to_name($uinfo[0]['network'], $uinfo[0]['url']);
521 'id' => intval($r[0]['id']),
522 'id_str' => (string) intval($r[0]['id']),
523 'name' => (($uinfo[0]['name']) ? $uinfo[0]['name'] : $uinfo[0]['nick']),
524 'screen_name' => (($uinfo[0]['nick']) ? $uinfo[0]['nick'] : $uinfo[0]['name']),
525 'location' => ($usr) ? $usr[0]['default-location'] : $network_name,
526 'description' => (($profile) ? $profile[0]['pdesc'] : NULL),
527 'profile_image_url' => $uinfo[0]['micro'],
528 'profile_image_url_https' => $uinfo[0]['micro'],
529 'url' => $uinfo[0]['url'],
530 'protected' => false,
531 'followers_count' => intval($countfollowers),
532 'friends_count' => intval($countfriends),
533 'created_at' => api_date($uinfo[0]['created']),
534 'favourites_count' => intval($starred),
536 'time_zone' => 'UTC',
537 'statuses_count' => intval($countitms),
538 'following' => (($uinfo[0]['rel'] == CONTACT_IS_FOLLOWER) OR ($uinfo[0]['rel'] == CONTACT_IS_FRIEND)),
540 'statusnet_blocking' => false,
541 'notifications' => false,
542 //'statusnet_profile_url' => $a->get_baseurl()."/contacts/".$uinfo[0]['cid'],
543 'statusnet_profile_url' => $uinfo[0]['url'],
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 $r = q("SELECT `id` FROM `unique_contacts` WHERE `name` = '%s' AND `avatar` = '%s' AND url = '%s'",
567 dbesc($item["author-name"]), dbesc($item["author-avatar"]),
568 dbesc(normalise_link($item["author-link"])));
571 q("UPDATE `unique_contacts` SET `name` = '%s', `avatar` = '%s' WHERE `url` = '%s'",
572 dbesc($item["author-name"]), dbesc($item["author-avatar"]),
573 dbesc(normalise_link($item["author-link"])));
576 $owner = q("SELECT `id` FROM `unique_contacts` WHERE `url`='%s' LIMIT 1",
577 dbesc(normalise_link($item['owner-link'])));
579 if (count($owner) == 0) {
580 q("INSERT INTO `unique_contacts` (`url`, `name`, `avatar`) VALUES ('%s', '%s', '%s')",
581 dbesc(normalise_link($item["owner-link"])), dbesc($item["owner-name"]), dbesc($item["owner-avatar"]));
583 $owner = q("SELECT `id` FROM `unique_contacts` WHERE `url`='%s' LIMIT 1",
584 dbesc(normalise_link($item['owner-link'])));
585 } else if ($item["owner-link"].$item["owner-name"] != $owner[0]["url"].$owner[0]["name"]) {
586 $r = q("SELECT `id` FROM `unique_contacts` WHERE `name` = '%s' AND `avatar` = '%s' AND url = '%s'",
587 dbesc($item["owner-name"]), dbesc($item["owner-avatar"]),
588 dbesc(normalise_link($item["owner-link"])));
591 q("UPDATE `unique_contacts` SET `name` = '%s', `avatar` = '%s' WHERE `url` = '%s'",
592 dbesc($item["owner-name"]), dbesc($item["owner-avatar"]),
593 dbesc(normalise_link($item["owner-link"])));
596 // Comments in threads may appear as wall-to-wall postings.
597 // So only take the owner at the top posting.
598 if ($item["id"] == $item["parent"])
599 $status_user = api_get_user($a,$item["owner-link"]);
601 $status_user = api_get_user($a,$item["author-link"]);
603 $status_user["protected"] = (($item["allow_cid"] != "") OR
604 ($item["allow_gid"] != "") OR
605 ($item["deny_cid"] != "") OR
606 ($item["deny_gid"] != "") OR
609 return ($status_user);
614 * load api $templatename for $type and replace $data array
616 function api_apply_template($templatename, $type, $data){
624 $data = array_xmlify($data);
625 $tpl = get_markup_template("api_".$templatename."_".$type.".tpl");
627 header ("Content-Type: text/xml");
628 echo '<?xml version="1.0" encoding="UTF-8"?>'."\n".'<status><error>not implemented</error></status>';
631 $ret = replace_macros($tpl, $data);
646 * Returns an HTTP 200 OK response code and a representation of the requesting user if authentication was successful;
647 * returns a 401 status code and an error message if not.
648 * http://developer.twitter.com/doc/get/account/verify_credentials
650 function api_account_verify_credentials(&$a, $type){
651 if (api_user()===false) return false;
653 unset($_REQUEST["user_id"]);
654 unset($_GET["user_id"]);
656 unset($_REQUEST["screen_name"]);
657 unset($_GET["screen_name"]);
659 $skip_status = (x($_REQUEST,'skip_status')?$_REQUEST['skip_status']:false);
661 $user_info = api_get_user($a);
663 // "verified" isn't used here in the standard
664 unset($user_info["verified"]);
666 // - Adding last status
668 $user_info["status"] = api_status_show($a,"raw");
669 if (!count($user_info["status"]))
670 unset($user_info["status"]);
672 unset($user_info["status"]["user"]);
675 // "uid" and "self" are only needed for some internal stuff, so remove it from here
676 unset($user_info["uid"]);
677 unset($user_info["self"]);
679 return api_apply_template("user", $type, array('$user' => $user_info));
682 api_register_func('api/account/verify_credentials','api_account_verify_credentials', true);
686 * get data from $_POST or $_GET
688 function requestdata($k){
689 if (isset($_POST[$k])){
692 if (isset($_GET[$k])){
698 /*Waitman Gobble Mod*/
699 function api_statuses_mediap(&$a, $type) {
700 if (api_user()===false) {
701 logger('api_statuses_update: no user');
704 $user_info = api_get_user($a);
706 $_REQUEST['type'] = 'wall';
707 $_REQUEST['profile_uid'] = api_user();
708 $_REQUEST['api_source'] = true;
709 $txt = requestdata('status');
710 //$txt = urldecode(requestdata('status'));
712 if((strpos($txt,'<') !== false) || (strpos($txt,'>') !== false)) {
714 require_once('library/HTMLPurifier.auto.php');
716 $txt = html2bb_video($txt);
717 $config = HTMLPurifier_Config::createDefault();
718 $config->set('Cache.DefinitionImpl', null);
719 $purifier = new HTMLPurifier($config);
720 $txt = $purifier->purify($txt);
722 $txt = html2bbcode($txt);
724 $a->argv[1]=$user_info['screen_name']; //should be set to username?
726 $_REQUEST['hush']='yeah'; //tell wall_upload function to return img info instead of echo
727 $bebop = wall_upload_post($a);
729 //now that we have the img url in bbcode we can add it to the status and insert the wall item.
730 $_REQUEST['body']=$txt."\n\n".$bebop;
733 // this should output the last post (the one we just posted).
734 return api_status_show($a,$type);
736 api_register_func('api/statuses/mediap','api_statuses_mediap', true);
737 /*Waitman Gobble Mod*/
740 function api_statuses_update(&$a, $type) {
741 if (api_user()===false) {
742 logger('api_statuses_update: no user');
746 $user_info = api_get_user($a);
748 // convert $_POST array items to the form we use for web posts.
750 // logger('api_post: ' . print_r($_POST,true));
752 if(requestdata('htmlstatus')) {
753 $txt = requestdata('htmlstatus');
754 if((strpos($txt,'<') !== false) || (strpos($txt,'>') !== false)) {
756 require_once('library/HTMLPurifier.auto.php');
758 $txt = html2bb_video($txt);
760 $config = HTMLPurifier_Config::createDefault();
761 $config->set('Cache.DefinitionImpl', null);
763 $purifier = new HTMLPurifier($config);
764 $txt = $purifier->purify($txt);
766 $_REQUEST['body'] = html2bbcode($txt);
770 $_REQUEST['body'] = requestdata('status');
772 $_REQUEST['title'] = requestdata('title');
774 $parent = requestdata('in_reply_to_status_id');
776 // Twidere sends "-1" if it is no reply ...
780 if(ctype_digit($parent))
781 $_REQUEST['parent'] = $parent;
783 $_REQUEST['parent_uri'] = $parent;
785 if(requestdata('lat') && requestdata('long'))
786 $_REQUEST['coord'] = sprintf("%s %s",requestdata('lat'),requestdata('long'));
787 $_REQUEST['profile_uid'] = api_user();
790 $_REQUEST['type'] = 'net-comment';
792 // Check for throttling (maximum posts per day, week and month)
793 $throttle_day = get_config('system','throttle_limit_day');
794 if ($throttle_day > 0) {
795 $datefrom = date("Y-m-d H:i:s", time() - 24*60*60);
797 $r = q("SELECT COUNT(*) AS `posts_day` FROM `item` WHERE `uid`=%d AND `wall`
798 AND `created` > '%s' AND `id` = `parent`",
799 intval(api_user()), dbesc($datefrom));
802 $posts_day = $r[0]["posts_day"];
806 if ($posts_day > $throttle_day) {
807 logger('Daily posting limit reached for user '.api_user(), LOGGER_DEBUG);
808 die(api_error($a, $type, sprintf(t("Daily posting limit of %d posts reached. The post was rejected."), $throttle_day)));
812 $throttle_week = get_config('system','throttle_limit_week');
813 if ($throttle_week > 0) {
814 $datefrom = date("Y-m-d H:i:s", time() - 24*60*60*7);
816 $r = q("SELECT COUNT(*) AS `posts_week` FROM `item` WHERE `uid`=%d AND `wall`
817 AND `created` > '%s' AND `id` = `parent`",
818 intval(api_user()), dbesc($datefrom));
821 $posts_week = $r[0]["posts_week"];
825 if ($posts_week > $throttle_week) {
826 logger('Weekly posting limit reached for user '.api_user(), LOGGER_DEBUG);
827 die(api_error($a, $type, sprintf(t("Weekly posting limit of %d posts reached. The post was rejected."), $throttle_week)));
831 $throttle_month = get_config('system','throttle_limit_month');
832 if ($throttle_month > 0) {
833 $datefrom = date("Y-m-d H:i:s", time() - 24*60*60*30);
835 $r = q("SELECT COUNT(*) AS `posts_month` FROM `item` WHERE `uid`=%d AND `wall`
836 AND `created` > '%s' AND `id` = `parent`",
837 intval(api_user()), dbesc($datefrom));
840 $posts_month = $r[0]["posts_month"];
844 if ($posts_month > $throttle_month) {
845 logger('Monthly posting limit reached for user '.api_user(), LOGGER_DEBUG);
846 die(api_error($a, $type, sprintf(t("Monthly posting limit of %d posts reached. The post was rejected."), $throttle_month)));
850 $_REQUEST['type'] = 'wall';
853 if(x($_FILES,'media')) {
854 // upload the image if we have one
855 $_REQUEST['hush']='yeah'; //tell wall_upload function to return img info instead of echo
856 $media = wall_upload_post($a);
858 $_REQUEST['body'] .= "\n\n".$media;
861 // To-Do: Multiple IDs
862 if (requestdata('media_ids')) {
863 $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",
864 intval(requestdata('media_ids')), api_user());
866 $phototypes = Photo::supportedTypes();
867 $ext = $phototypes[$r[0]['type']];
868 $_REQUEST['body'] .= "\n\n".'[url='.$a->get_baseurl().'/photos/'.$r[0]['nickname'].'/image/'.$r[0]['resource-id'].']';
869 $_REQUEST['body'] .= '[img]'.$a->get_baseurl()."/photo/".$r[0]['resource-id']."-".$r[0]['scale'].".".$ext."[/img][/url]";
873 // set this so that the item_post() function is quiet and doesn't redirect or emit json
875 $_REQUEST['api_source'] = true;
877 if (!x($_REQUEST, "source"))
878 $_REQUEST["source"] = api_source();
880 // call out normal post function
884 // this should output the last post (the one we just posted).
885 return api_status_show($a,$type);
887 api_register_func('api/statuses/update','api_statuses_update', true);
888 api_register_func('api/statuses/update_with_media','api_statuses_update', true);
891 function api_media_upload(&$a, $type) {
892 if (api_user()===false) {
897 $user_info = api_get_user($a);
899 if(!x($_FILES,'media')) {
904 $media = wall_upload_post($a, false);
910 $returndata = array();
911 $returndata["media_id"] = $media["id"];
912 $returndata["media_id_string"] = (string)$media["id"];
913 $returndata["size"] = $media["size"];
914 $returndata["image"] = array("w" => $media["width"],
915 "h" => $media["height"],
916 "image_type" => $media["type"]);
918 logger("Media uploaded: ".print_r($returndata, true), LOGGER_DEBUG);
920 return array("media" => $returndata);
923 api_register_func('api/media/upload','api_media_upload', true);
925 function api_status_show(&$a, $type){
926 $user_info = api_get_user($a);
928 logger('api_status_show: user_info: '.print_r($user_info, true), LOGGER_DEBUG);
931 $privacy_sql = "AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''";
935 // get last public wall message
936 $lastwall = q("SELECT `item`.*, `i`.`contact-id` as `reply_uid`, `i`.`author-link` AS `item-author`
937 FROM `item`, `item` as `i`
938 WHERE `item`.`contact-id` = %d AND `item`.`uid` = %d
939 AND ((`item`.`author-link` IN ('%s', '%s')) OR (`item`.`owner-link` IN ('%s', '%s')))
940 AND `i`.`id` = `item`.`parent`
941 AND `item`.`type`!='activity' $privacy_sql
942 ORDER BY `item`.`created` DESC
944 intval($user_info['cid']),
946 dbesc($user_info['url']),
947 dbesc(normalise_link($user_info['url'])),
948 dbesc($user_info['url']),
949 dbesc(normalise_link($user_info['url']))
952 if (count($lastwall)>0){
953 $lastwall = $lastwall[0];
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;
960 if (intval($lastwall['parent']) != intval($lastwall['id'])) {
961 $in_reply_to_status_id= intval($lastwall['parent']);
962 $in_reply_to_status_id_str = (string) intval($lastwall['parent']);
964 $r = q("SELECT * FROM `unique_contacts` WHERE `url` = '%s'", dbesc(normalise_link($lastwall['item-author'])));
966 if ($r[0]['nick'] == "")
967 $r[0]['nick'] = api_get_nick($r[0]["url"]);
969 $in_reply_to_screen_name = (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']);
970 $in_reply_to_user_id = intval($r[0]['id']);
971 $in_reply_to_user_id_str = (string) intval($r[0]['id']);
975 // There seems to be situation, where both fields are identical:
976 // https://github.com/friendica/friendica/issues/1010
977 // This is a bugfix for that.
978 if (intval($in_reply_to_status_id) == intval($lastwall['id'])) {
979 logger('api_status_show: this message should never appear: id: '.$lastwall['id'].' similar to reply-to: '.$in_reply_to_status_id, LOGGER_DEBUG);
980 $in_reply_to_status_id = NULL;
981 $in_reply_to_user_id = NULL;
982 $in_reply_to_status_id_str = NULL;
983 $in_reply_to_user_id_str = NULL;
984 $in_reply_to_screen_name = NULL;
987 $converted = api_convert_item($lastwall);
989 $status_info = array(
990 'created_at' => api_date($lastwall['created']),
991 'id' => intval($lastwall['id']),
992 'id_str' => (string) $lastwall['id'],
993 'text' => $converted["text"],
994 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
995 'truncated' => false,
996 'in_reply_to_status_id' => $in_reply_to_status_id,
997 'in_reply_to_status_id_str' => $in_reply_to_status_id_str,
998 'in_reply_to_user_id' => $in_reply_to_user_id,
999 'in_reply_to_user_id_str' => $in_reply_to_user_id_str,
1000 'in_reply_to_screen_name' => $in_reply_to_screen_name,
1001 'user' => $user_info,
1003 'coordinates' => "",
1005 'contributors' => "",
1006 'is_quote_status' => false,
1007 'retweet_count' => 0,
1008 'favorite_count' => 0,
1009 'favorited' => $lastwall['starred'] ? true : false,
1010 'retweeted' => false,
1011 'possibly_sensitive' => false,
1013 'statusnet_html' => $converted["html"],
1014 'statusnet_conversation_id' => $lastwall['parent'],
1017 if (count($converted["attachments"]) > 0)
1018 $status_info["attachments"] = $converted["attachments"];
1020 if (count($converted["entities"]) > 0)
1021 $status_info["entities"] = $converted["entities"];
1023 if (($lastwall['item_network'] != "") AND ($status["source"] == 'web'))
1024 $status_info["source"] = network_to_name($lastwall['item_network'], $user_info['url']);
1025 elseif (($lastwall['item_network'] != "") AND (network_to_name($lastwall['item_network'], $user_info['url']) != $status_info["source"]))
1026 $status_info["source"] = trim($status_info["source"].' ('.network_to_name($lastwall['item_network'], $user_info['url']).')');
1028 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1029 unset($status_info["user"]["uid"]);
1030 unset($status_info["user"]["self"]);
1033 logger('status_info: '.print_r($status_info, true), LOGGER_DEBUG);
1036 return($status_info);
1038 return api_apply_template("status", $type, array('$status' => $status_info));
1047 * Returns extended information of a given user, specified by ID or screen name as per the required id parameter.
1048 * The author's most recent status will be returned inline.
1049 * http://developer.twitter.com/doc/get/users/show
1051 function api_users_show(&$a, $type){
1052 $user_info = api_get_user($a);
1054 $lastwall = q("SELECT `item`.*
1055 FROM `item`, `contact`
1056 WHERE `item`.`uid` = %d AND `verb` = '%s' AND `item`.`contact-id` = %d
1057 AND ((`item`.`author-link` IN ('%s', '%s')) OR (`item`.`owner-link` IN ('%s', '%s')))
1058 AND `contact`.`id`=`item`.`contact-id`
1059 AND `type`!='activity'
1060 AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''
1061 ORDER BY `created` DESC
1064 dbesc(ACTIVITY_POST),
1065 intval($user_info['cid']),
1066 dbesc($user_info['url']),
1067 dbesc(normalise_link($user_info['url'])),
1068 dbesc($user_info['url']),
1069 dbesc(normalise_link($user_info['url']))
1071 if (count($lastwall)>0){
1072 $lastwall = $lastwall[0];
1074 $in_reply_to_status_id = NULL;
1075 $in_reply_to_user_id = NULL;
1076 $in_reply_to_status_id_str = NULL;
1077 $in_reply_to_user_id_str = NULL;
1078 $in_reply_to_screen_name = NULL;
1079 if ($lastwall['parent']!=$lastwall['id']) {
1080 $reply = q("SELECT `item`.`id`, `item`.`contact-id` as `reply_uid`, `contact`.`nick` as `reply_author`, `item`.`author-link` AS `item-author`
1081 FROM `item`,`contact` WHERE `contact`.`id`=`item`.`contact-id` AND `item`.`id` = %d", intval($lastwall['parent']));
1082 if (count($reply)>0) {
1083 $in_reply_to_status_id = intval($lastwall['parent']);
1084 $in_reply_to_status_id_str = (string) intval($lastwall['parent']);
1086 $r = q("SELECT * FROM `unique_contacts` WHERE `url` = '%s'", dbesc(normalise_link($reply[0]['item-author'])));
1088 if ($r[0]['nick'] == "")
1089 $r[0]['nick'] = api_get_nick($r[0]["url"]);
1091 $in_reply_to_screen_name = (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']);
1092 $in_reply_to_user_id = intval($r[0]['id']);
1093 $in_reply_to_user_id_str = (string) intval($r[0]['id']);
1098 $converted = api_convert_item($lastwall);
1100 $user_info['status'] = array(
1101 'text' => $converted["text"],
1102 'truncated' => false,
1103 'created_at' => api_date($lastwall['created']),
1104 'in_reply_to_status_id' => $in_reply_to_status_id,
1105 'in_reply_to_status_id_str' => $in_reply_to_status_id_str,
1106 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
1107 'id' => intval($lastwall['contact-id']),
1108 'id_str' => (string) $lastwall['contact-id'],
1109 'in_reply_to_user_id' => $in_reply_to_user_id,
1110 'in_reply_to_user_id_str' => $in_reply_to_user_id_str,
1111 'in_reply_to_screen_name' => $in_reply_to_screen_name,
1113 'favorited' => $lastwall['starred'] ? true : false,
1114 'statusnet_html' => $converted["html"],
1115 'statusnet_conversation_id' => $lastwall['parent'],
1118 if (count($converted["attachments"]) > 0)
1119 $user_info["status"]["attachments"] = $converted["attachments"];
1121 if (count($converted["entities"]) > 0)
1122 $user_info["status"]["entities"] = $converted["entities"];
1124 if (($lastwall['item_network'] != "") AND ($user_info["status"]["source"] == 'web'))
1125 $user_info["status"]["source"] = network_to_name($lastwall['item_network'], $user_info['url']);
1126 if (($lastwall['item_network'] != "") AND (network_to_name($lastwall['item_network'], $user_info['url']) != $user_info["status"]["source"]))
1127 $user_info["status"]["source"] = trim($user_info["status"]["source"].' ('.network_to_name($lastwall['item_network'], $user_info['url']).')');
1131 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1132 unset($user_info["uid"]);
1133 unset($user_info["self"]);
1135 return api_apply_template("user", $type, array('$user' => $user_info));
1138 api_register_func('api/users/show','api_users_show');
1141 function api_users_search(&$a, $type) {
1142 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1144 $userlist = array();
1146 if (isset($_GET["q"])) {
1147 $r = q("SELECT id FROM `unique_contacts` WHERE `name`='%s'", dbesc($_GET["q"]));
1149 $r = q("SELECT `id` FROM `unique_contacts` WHERE `nick`='%s'", dbesc($_GET["q"]));
1152 foreach ($r AS $user) {
1153 $user_info = api_get_user($a, $user["id"]);
1154 //echo print_r($user_info, true)."\n";
1155 $userdata = api_apply_template("user", $type, array('user' => $user_info));
1156 $userlist[] = $userdata["user"];
1158 $userlist = array("users" => $userlist);
1160 die(api_error($a, $type, t("User not found.")));
1162 die(api_error($a, $type, t("User not found.")));
1167 api_register_func('api/users/search','api_users_search');
1171 * http://developer.twitter.com/doc/get/statuses/home_timeline
1173 * TODO: Optional parameters
1174 * TODO: Add reply info
1176 function api_statuses_home_timeline(&$a, $type){
1177 if (api_user()===false) return false;
1179 unset($_REQUEST["user_id"]);
1180 unset($_GET["user_id"]);
1182 unset($_REQUEST["screen_name"]);
1183 unset($_GET["screen_name"]);
1185 $user_info = api_get_user($a);
1186 // get last newtork messages
1190 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1191 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1192 if ($page<0) $page=0;
1193 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1194 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1195 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1196 $exclude_replies = (x($_REQUEST,'exclude_replies')?1:0);
1197 $conversation_id = (x($_REQUEST,'conversation_id')?$_REQUEST['conversation_id']:0);
1199 $start = $page*$count;
1203 $sql_extra .= ' AND `item`.`id` <= '.intval($max_id);
1204 if ($exclude_replies > 0)
1205 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
1206 if ($conversation_id > 0)
1207 $sql_extra .= ' AND `item`.`parent` = '.intval($conversation_id);
1209 $r = q("SELECT STRAIGHT_JOIN `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1210 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1211 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1212 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1213 FROM `item`, `contact`
1214 WHERE `item`.`uid` = %d AND `verb` = '%s'
1215 AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1216 AND `contact`.`id` = `item`.`contact-id`
1217 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1220 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1222 dbesc(ACTIVITY_POST),
1224 intval($start), intval($count)
1227 $ret = api_format_items($r,$user_info);
1229 // Set all posts from the query above to seen
1231 foreach ($r AS $item)
1232 $idarray[] = intval($item["id"]);
1234 $idlist = implode(",", $idarray);
1237 $r = q("UPDATE `item` SET `unseen` = 0 WHERE `unseen` AND `id` IN (%s)", $idlist);
1240 $data = array('$statuses' => $ret);
1244 $data = api_rss_extra($a, $data, $user_info);
1247 $as = api_format_as($a, $ret, $user_info);
1248 $as['title'] = $a->config['sitename']." Home Timeline";
1249 $as['link']['url'] = $a->get_baseurl()."/".$user_info["screen_name"]."/all";
1254 return api_apply_template("timeline", $type, $data);
1256 api_register_func('api/statuses/home_timeline','api_statuses_home_timeline', true);
1257 api_register_func('api/statuses/friends_timeline','api_statuses_home_timeline', true);
1259 function api_statuses_public_timeline(&$a, $type){
1260 if (api_user()===false) return false;
1262 $user_info = api_get_user($a);
1263 // get last newtork messages
1267 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1268 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1269 if ($page<0) $page=0;
1270 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1271 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1272 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1273 $exclude_replies = (x($_REQUEST,'exclude_replies')?1:0);
1274 $conversation_id = (x($_REQUEST,'conversation_id')?$_REQUEST['conversation_id']:0);
1276 $start = $page*$count;
1279 $sql_extra = 'AND `item`.`id` <= '.intval($max_id);
1280 if ($exclude_replies > 0)
1281 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
1282 if ($conversation_id > 0)
1283 $sql_extra .= ' AND `item`.`parent` = '.intval($conversation_id);
1285 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1286 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1287 `contact`.`network`, `contact`.`thumb`, `contact`.`self`, `contact`.`writable`,
1288 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`,
1289 `user`.`nickname`, `user`.`hidewall`
1290 FROM `item` STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
1291 STRAIGHT_JOIN `user` ON `user`.`uid` = `item`.`uid`
1292 WHERE `verb` = '%s' AND `item`.`visible` = 1 AND `item`.`deleted` = 0 and `item`.`moderated` = 0
1293 AND `item`.`allow_cid` = '' AND `item`.`allow_gid` = ''
1294 AND `item`.`deny_cid` = '' AND `item`.`deny_gid` = ''
1295 AND `item`.`private` = 0 AND `item`.`wall` = 1 AND `user`.`hidewall` = 0
1296 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1299 ORDER BY `item`.`id` DESC LIMIT %d, %d ",
1300 dbesc(ACTIVITY_POST),
1305 $ret = api_format_items($r,$user_info);
1308 $data = array('$statuses' => $ret);
1312 $data = api_rss_extra($a, $data, $user_info);
1315 $as = api_format_as($a, $ret, $user_info);
1316 $as['title'] = $a->config['sitename']." Public Timeline";
1317 $as['link']['url'] = $a->get_baseurl()."/";
1322 return api_apply_template("timeline", $type, $data);
1324 api_register_func('api/statuses/public_timeline','api_statuses_public_timeline', true);
1329 function api_statuses_show(&$a, $type){
1330 if (api_user()===false) return false;
1332 $user_info = api_get_user($a);
1335 $id = intval($a->argv[3]);
1338 $id = intval($_REQUEST["id"]);
1342 $id = intval($a->argv[4]);
1344 logger('API: api_statuses_show: '.$id);
1346 $conversation = (x($_REQUEST,'conversation')?1:0);
1350 $sql_extra .= " AND `item`.`parent` = %d ORDER BY `received` ASC ";
1352 $sql_extra .= " AND `item`.`id` = %d";
1354 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1355 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1356 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1357 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1358 FROM `item`, `contact`
1359 WHERE `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1360 AND `contact`.`id` = `item`.`contact-id` AND `item`.`uid` = %d AND `item`.`verb` = '%s'
1361 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1364 dbesc(ACTIVITY_POST),
1369 die(api_error($a, $type, t("There is no status with this id.")));
1371 $ret = api_format_items($r,$user_info);
1373 if ($conversation) {
1374 $data = array('$statuses' => $ret);
1375 return api_apply_template("timeline", $type, $data);
1377 $data = array('$status' => $ret[0]);
1381 $data = api_rss_extra($a, $data, $user_info);
1383 return api_apply_template("status", $type, $data);
1386 api_register_func('api/statuses/show','api_statuses_show', true);
1392 function api_conversation_show(&$a, $type){
1393 if (api_user()===false) return false;
1395 $user_info = api_get_user($a);
1398 $id = intval($a->argv[3]);
1399 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1400 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1401 if ($page<0) $page=0;
1402 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1403 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1405 $start = $page*$count;
1408 $id = intval($_REQUEST["id"]);
1412 $id = intval($a->argv[4]);
1414 logger('API: api_conversation_show: '.$id);
1416 $r = q("SELECT `parent` FROM `item` WHERE `id` = %d", intval($id));
1418 $id = $r[0]["parent"];
1423 $sql_extra = ' AND `item`.`id` <= '.intval($max_id);
1425 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1426 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1427 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1428 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1429 FROM `item` INNER JOIN (SELECT `uri`,`parent` FROM `item` WHERE `id` = %d) AS `temp1`
1430 ON (`item`.`thr-parent` = `temp1`.`uri` AND `item`.`parent` = `temp1`.`parent`), `contact`
1431 WHERE `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1432 AND `item`.`uid` = %d AND `item`.`verb` = '%s' AND `contact`.`id` = `item`.`contact-id`
1433 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1434 AND `item`.`id`>%d $sql_extra
1435 ORDER BY `item`.`id` DESC LIMIT %d ,%d",
1436 intval($id), intval(api_user()),
1437 dbesc(ACTIVITY_POST),
1439 intval($start), intval($count)
1443 die(api_error($a, $type, t("There is no conversation with this id.")));
1445 $ret = api_format_items($r,$user_info);
1447 $data = array('$statuses' => $ret);
1448 return api_apply_template("timeline", $type, $data);
1450 api_register_func('api/conversation/show','api_conversation_show', true);
1456 function api_statuses_repeat(&$a, $type){
1459 if (api_user()===false) return false;
1461 $user_info = api_get_user($a);
1464 $id = intval($a->argv[3]);
1467 $id = intval($_REQUEST["id"]);
1471 $id = intval($a->argv[4]);
1473 logger('API: api_statuses_repeat: '.$id);
1475 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`, `contact`.`nick` as `reply_author`,
1476 `contact`.`name`, `contact`.`photo` as `reply_photo`, `contact`.`url` as `reply_url`, `contact`.`rel`,
1477 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1478 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1479 FROM `item`, `contact`
1480 WHERE `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1481 AND `contact`.`id` = `item`.`contact-id`
1482 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1484 AND `item`.`id`=%d",
1488 if ($r[0]['body'] != "") {
1489 if (!intval(get_config('system','old_share'))) {
1490 if (strpos($r[0]['body'], "[/share]") !== false) {
1491 $pos = strpos($r[0]['body'], "[share");
1492 $post = substr($r[0]['body'], $pos);
1494 $post = share_header($r[0]['author-name'], $r[0]['author-link'], $r[0]['author-avatar'], $r[0]['guid'], $r[0]['created'], $r[0]['plink']);
1496 $post .= $r[0]['body'];
1497 $post .= "[/share]";
1499 $_REQUEST['body'] = $post;
1501 $_REQUEST['body'] = html_entity_decode("♲ ", ENT_QUOTES, 'UTF-8')."[url=".$r[0]['reply_url']."]".$r[0]['reply_author']."[/url] \n".$r[0]['body'];
1503 $_REQUEST['profile_uid'] = api_user();
1504 $_REQUEST['type'] = 'wall';
1505 $_REQUEST['api_source'] = true;
1507 if (!x($_REQUEST, "source"))
1508 $_REQUEST["source"] = api_source();
1513 // this should output the last post (the one we just posted).
1515 return(api_status_show($a,$type));
1517 api_register_func('api/statuses/retweet','api_statuses_repeat', true);
1522 function api_statuses_destroy(&$a, $type){
1523 if (api_user()===false) return false;
1525 $user_info = api_get_user($a);
1528 $id = intval($a->argv[3]);
1531 $id = intval($_REQUEST["id"]);
1535 $id = intval($a->argv[4]);
1537 logger('API: api_statuses_destroy: '.$id);
1539 $ret = api_statuses_show($a, $type);
1541 drop_item($id, false);
1545 api_register_func('api/statuses/destroy','api_statuses_destroy', true);
1549 * http://developer.twitter.com/doc/get/statuses/mentions
1552 function api_statuses_mentions(&$a, $type){
1553 if (api_user()===false) return false;
1555 unset($_REQUEST["user_id"]);
1556 unset($_GET["user_id"]);
1558 unset($_REQUEST["screen_name"]);
1559 unset($_GET["screen_name"]);
1561 $user_info = api_get_user($a);
1562 // get last newtork messages
1566 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1567 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1568 if ($page<0) $page=0;
1569 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1570 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1571 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1573 $start = $page*$count;
1575 // Ugly code - should be changed
1576 $myurl = $a->get_baseurl() . '/profile/'. $a->user['nickname'];
1577 $myurl = substr($myurl,strpos($myurl,'://')+3);
1578 //$myurl = str_replace(array('www.','.'),array('','\\.'),$myurl);
1579 $myurl = str_replace('www.','',$myurl);
1580 $diasp_url = str_replace('/profile/','/u/',$myurl);
1583 $sql_extra = ' AND `item`.`id` <= '.intval($max_id);
1585 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1586 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1587 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1588 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1589 FROM `item`, `contact`
1590 WHERE `item`.`uid` = %d AND `verb` = '%s'
1591 AND NOT (`item`.`author-link` IN ('https://%s', 'http://%s'))
1592 AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1593 AND `contact`.`id` = `item`.`contact-id`
1594 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1595 AND `item`.`parent` IN (SELECT `iid` from thread where uid = %d AND `mention` AND !`ignored`)
1598 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1600 dbesc(ACTIVITY_POST),
1601 dbesc(protect_sprintf($myurl)),
1602 dbesc(protect_sprintf($myurl)),
1605 intval($start), intval($count)
1608 $ret = api_format_items($r,$user_info);
1611 $data = array('$statuses' => $ret);
1615 $data = api_rss_extra($a, $data, $user_info);
1618 $as = api_format_as($a, $ret, $user_info);
1619 $as["title"] = $a->config['sitename']." Mentions";
1620 $as['link']['url'] = $a->get_baseurl()."/";
1625 return api_apply_template("timeline", $type, $data);
1627 api_register_func('api/statuses/mentions','api_statuses_mentions', true);
1628 api_register_func('api/statuses/replies','api_statuses_mentions', true);
1631 function api_statuses_user_timeline(&$a, $type){
1632 if (api_user()===false) return false;
1634 $user_info = api_get_user($a);
1635 // get last network messages
1637 logger("api_statuses_user_timeline: api_user: ". api_user() .
1638 "\nuser_info: ".print_r($user_info, true) .
1639 "\n_REQUEST: ".print_r($_REQUEST, true),
1643 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1644 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1645 if ($page<0) $page=0;
1646 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1647 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1648 $exclude_replies = (x($_REQUEST,'exclude_replies')?1:0);
1649 $conversation_id = (x($_REQUEST,'conversation_id')?$_REQUEST['conversation_id']:0);
1651 $start = $page*$count;
1654 if ($user_info['self']==1)
1655 $sql_extra .= " AND `item`.`wall` = 1 ";
1657 if ($exclude_replies > 0)
1658 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
1659 if ($conversation_id > 0)
1660 $sql_extra .= ' AND `item`.`parent` = '.intval($conversation_id);
1662 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1663 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1664 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1665 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1666 FROM `item`, `contact`
1667 WHERE `item`.`uid` = %d AND `verb` = '%s'
1668 AND `item`.`contact-id` = %d
1669 AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1670 AND `contact`.`id` = `item`.`contact-id`
1671 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1674 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1676 dbesc(ACTIVITY_POST),
1677 intval($user_info['cid']),
1679 intval($start), intval($count)
1682 $ret = api_format_items($r,$user_info, true);
1684 $data = array('$statuses' => $ret);
1688 $data = api_rss_extra($a, $data, $user_info);
1691 return api_apply_template("timeline", $type, $data);
1694 api_register_func('api/statuses/user_timeline','api_statuses_user_timeline', true);
1698 * Star/unstar an item
1699 * param: id : id of the item
1701 * api v1 : https://web.archive.org/web/20131019055350/https://dev.twitter.com/docs/api/1/post/favorites/create/%3Aid
1703 function api_favorites_create_destroy(&$a, $type){
1704 if (api_user()===false) return false;
1706 # for versioned api.
1707 # TODO: we need a better global soluton
1709 if ($a->argv[1]=="1.1") $action_argv_id=3;
1711 if ($a->argc<=$action_argv_id) die(api_error($a, $type, t("Invalid request.")));
1712 $action = str_replace(".".$type,"",$a->argv[$action_argv_id]);
1713 if ($a->argc==$action_argv_id+2) {
1714 $itemid = intval($a->argv[$action_argv_id+1]);
1716 $itemid = intval($_REQUEST['id']);
1719 $item = q("SELECT * FROM item WHERE id=%d AND uid=%d",
1720 $itemid, api_user());
1722 if ($item===false || count($item)==0) die(api_error($a, $type, t("Invalid item.")));
1726 $item[0]['starred']=1;
1729 $item[0]['starred']=0;
1732 die(api_error($a, $type, t("Invalid action. ".$action)));
1734 $r = q("UPDATE item SET starred=%d WHERE id=%d AND uid=%d",
1735 $item[0]['starred'], $itemid, api_user());
1737 q("UPDATE thread SET starred=%d WHERE iid=%d AND uid=%d",
1738 $item[0]['starred'], $itemid, api_user());
1740 if ($r===false) die(api_error($a, $type, t("DB error")));
1743 $user_info = api_get_user($a);
1744 $rets = api_format_items($item,$user_info);
1747 $data = array('$status' => $ret);
1751 $data = api_rss_extra($a, $data, $user_info);
1754 return api_apply_template("status", $type, $data);
1757 api_register_func('api/favorites/create', 'api_favorites_create_destroy', true);
1758 api_register_func('api/favorites/destroy', 'api_favorites_create_destroy', true);
1760 function api_favorites(&$a, $type){
1763 if (api_user()===false) return false;
1765 $called_api= array();
1767 $user_info = api_get_user($a);
1769 // in friendica starred item are private
1770 // return favorites only for self
1771 logger('api_favorites: self:' . $user_info['self']);
1773 if ($user_info['self']==0) {
1779 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1780 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1781 $count = (x($_GET,'count')?$_GET['count']:20);
1782 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1783 if ($page<0) $page=0;
1785 $start = $page*$count;
1788 $sql_extra .= ' AND `item`.`id` <= '.intval($max_id);
1790 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1791 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1792 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1793 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1794 FROM `item`, `contact`
1795 WHERE `item`.`uid` = %d
1796 AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1797 AND `item`.`starred` = 1
1798 AND `contact`.`id` = `item`.`contact-id`
1799 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1802 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1805 intval($start), intval($count)
1808 $ret = api_format_items($r,$user_info);
1812 $data = array('$statuses' => $ret);
1816 $data = api_rss_extra($a, $data, $user_info);
1819 return api_apply_template("timeline", $type, $data);
1822 api_register_func('api/favorites','api_favorites', true);
1827 function api_format_as($a, $ret, $user_info) {
1830 $as['title'] = $a->config['sitename']." Public Timeline";
1832 foreach ($ret as $item) {
1833 $singleitem["actor"]["displayName"] = $item["user"]["name"];
1834 $singleitem["actor"]["id"] = $item["user"]["contact_url"];
1835 $avatar[0]["url"] = $item["user"]["profile_image_url"];
1836 $avatar[0]["rel"] = "avatar";
1837 $avatar[0]["type"] = "";
1838 $avatar[0]["width"] = 96;
1839 $avatar[0]["height"] = 96;
1840 $avatar[1]["url"] = $item["user"]["profile_image_url"];
1841 $avatar[1]["rel"] = "avatar";
1842 $avatar[1]["type"] = "";
1843 $avatar[1]["width"] = 48;
1844 $avatar[1]["height"] = 48;
1845 $avatar[2]["url"] = $item["user"]["profile_image_url"];
1846 $avatar[2]["rel"] = "avatar";
1847 $avatar[2]["type"] = "";
1848 $avatar[2]["width"] = 24;
1849 $avatar[2]["height"] = 24;
1850 $singleitem["actor"]["avatarLinks"] = $avatar;
1852 $singleitem["actor"]["image"]["url"] = $item["user"]["profile_image_url"];
1853 $singleitem["actor"]["image"]["rel"] = "avatar";
1854 $singleitem["actor"]["image"]["type"] = "";
1855 $singleitem["actor"]["image"]["width"] = 96;
1856 $singleitem["actor"]["image"]["height"] = 96;
1857 $singleitem["actor"]["type"] = "person";
1858 $singleitem["actor"]["url"] = $item["person"]["contact_url"];
1859 $singleitem["actor"]["statusnet:profile_info"]["local_id"] = $item["user"]["id"];
1860 $singleitem["actor"]["statusnet:profile_info"]["following"] = $item["user"]["following"] ? "true" : "false";
1861 $singleitem["actor"]["statusnet:profile_info"]["blocking"] = "false";
1862 $singleitem["actor"]["contact"]["preferredUsername"] = $item["user"]["screen_name"];
1863 $singleitem["actor"]["contact"]["displayName"] = $item["user"]["name"];
1864 $singleitem["actor"]["contact"]["addresses"] = "";
1866 $singleitem["body"] = $item["text"];
1867 $singleitem["object"]["displayName"] = $item["text"];
1868 $singleitem["object"]["id"] = $item["url"];
1869 $singleitem["object"]["type"] = "note";
1870 $singleitem["object"]["url"] = $item["url"];
1871 //$singleitem["context"] =;
1872 $singleitem["postedTime"] = date("c", strtotime($item["published"]));
1873 $singleitem["provider"]["objectType"] = "service";
1874 $singleitem["provider"]["displayName"] = "Test";
1875 $singleitem["provider"]["url"] = "http://test.tld";
1876 $singleitem["title"] = $item["text"];
1877 $singleitem["verb"] = "post";
1878 $singleitem["statusnet:notice_info"]["local_id"] = $item["id"];
1879 $singleitem["statusnet:notice_info"]["source"] = $item["source"];
1880 $singleitem["statusnet:notice_info"]["favorite"] = "false";
1881 $singleitem["statusnet:notice_info"]["repeated"] = "false";
1882 //$singleitem["original"] = $item;
1883 $items[] = $singleitem;
1885 $as['items'] = $items;
1886 $as['link']['url'] = $a->get_baseurl()."/".$user_info["screen_name"]."/all";
1887 $as['link']['rel'] = "alternate";
1888 $as['link']['type'] = "text/html";
1892 function api_format_messages($item, $recipient, $sender) {
1893 // standard meta information
1895 'id' => $item['id'],
1896 'sender_id' => $sender['id'] ,
1898 'recipient_id' => $recipient['id'],
1899 'created_at' => api_date($item['created']),
1900 'sender_screen_name' => $sender['screen_name'],
1901 'recipient_screen_name' => $recipient['screen_name'],
1902 'sender' => $sender,
1903 'recipient' => $recipient,
1906 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1907 unset($ret["sender"]["uid"]);
1908 unset($ret["sender"]["self"]);
1909 unset($ret["recipient"]["uid"]);
1910 unset($ret["recipient"]["self"]);
1912 //don't send title to regular StatusNET requests to avoid confusing these apps
1913 if (x($_GET, 'getText')) {
1914 $ret['title'] = $item['title'] ;
1915 if ($_GET["getText"] == "html") {
1916 $ret['text'] = bbcode($item['body'], false, false);
1918 elseif ($_GET["getText"] == "plain") {
1919 //$ret['text'] = html2plain(bbcode($item['body'], false, false, true), 0);
1920 $ret['text'] = trim(html2plain(bbcode(api_clean_plain_items($item['body']), false, false, 2, true), 0));
1924 $ret['text'] = $item['title']."\n".html2plain(bbcode(api_clean_plain_items($item['body']), false, false, 2, true), 0);
1926 if (isset($_GET["getUserObjects"]) && $_GET["getUserObjects"] == "false") {
1927 unset($ret['sender']);
1928 unset($ret['recipient']);
1934 function api_convert_item($item) {
1936 $body = $item['body'];
1937 $attachments = api_get_attachments($body);
1939 // Workaround for ostatus messages where the title is identically to the body
1940 $html = bbcode(api_clean_plain_items($body), false, false, 2, true);
1941 $statusbody = trim(html2plain($html, 0));
1943 // handle data: images
1944 $statusbody = api_format_items_embeded_images($item,$statusbody);
1946 $statustitle = trim($item['title']);
1948 if (($statustitle != '') and (strpos($statusbody, $statustitle) !== false))
1949 $statustext = trim($statusbody);
1951 $statustext = trim($statustitle."\n\n".$statusbody);
1953 if (($item["network"] == NETWORK_FEED) and (strlen($statustext)> 1000))
1954 $statustext = substr($statustext, 0, 1000)."... \n".$item["plink"];
1956 $statushtml = trim(bbcode($body, false, false));
1958 if ($item['title'] != "")
1959 $statushtml = "<h4>".bbcode($item['title'])."</h4>\n".$statushtml;
1961 $entities = api_get_entitities($statustext, $body);
1963 return(array("text" => $statustext, "html" => $statushtml, "attachments" => $attachments, "entities" => $entities));
1966 function api_get_attachments(&$body) {
1969 $text = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $text);
1971 $URLSearchString = "^\[\]";
1972 $ret = preg_match_all("/\[img\]([$URLSearchString]*)\[\/img\]/ism", $text, $images);
1977 $attachments = array();
1979 foreach ($images[1] AS $image) {
1980 $imagedata = get_photo_info($image);
1983 $attachments[] = array("url" => $image, "mimetype" => $imagedata["mime"], "size" => $imagedata["size"]);
1986 if (strstr($_SERVER['HTTP_USER_AGENT'], "AndStatus"))
1987 foreach ($images[0] AS $orig)
1988 $body = str_replace($orig, "", $body);
1990 return $attachments;
1993 function api_get_entitities(&$text, $bbcode) {
1996 * Links at the first character of the post
2001 $include_entities = strtolower(x($_REQUEST,'include_entities')?$_REQUEST['include_entities']:"false");
2003 if ($include_entities != "true") {
2005 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2007 foreach ($images[1] AS $image) {
2008 $replace = proxy_url($image);
2009 $text = str_replace($image, $replace, $text);
2014 $bbcode = bb_CleanPictureLinks($bbcode);
2016 // Change pure links in text to bbcode uris
2017 $bbcode = preg_replace("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", '$1[url=$2]$2[/url]', $bbcode);
2019 $entities = array();
2020 $entities["hashtags"] = array();
2021 $entities["symbols"] = array();
2022 $entities["urls"] = array();
2023 $entities["user_mentions"] = array();
2025 $URLSearchString = "^\[\]";
2027 $bbcode = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'#$2',$bbcode);
2029 $bbcode = preg_replace("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism",'[url=$1]$2[/url]',$bbcode);
2030 //$bbcode = preg_replace("/\[url\](.*?)\[\/url\]/ism",'[url=$1]$1[/url]',$bbcode);
2031 $bbcode = preg_replace("/\[video\](.*?)\[\/video\]/ism",'[url=$1]$1[/url]',$bbcode);
2033 $bbcode = preg_replace("/\[youtube\]([A-Za-z0-9\-_=]+)(.*?)\[\/youtube\]/ism",
2034 '[url=https://www.youtube.com/watch?v=$1]https://www.youtube.com/watch?v=$1[/url]', $bbcode);
2035 $bbcode = preg_replace("/\[youtube\](.*?)\[\/youtube\]/ism",'[url=$1]$1[/url]',$bbcode);
2037 $bbcode = preg_replace("/\[vimeo\]([0-9]+)(.*?)\[\/vimeo\]/ism",
2038 '[url=https://vimeo.com/$1]https://vimeo.com/$1[/url]', $bbcode);
2039 $bbcode = preg_replace("/\[vimeo\](.*?)\[\/vimeo\]/ism",'[url=$1]$1[/url]',$bbcode);
2041 $bbcode = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $bbcode);
2043 //preg_match_all("/\[url\]([$URLSearchString]*)\[\/url\]/ism", $bbcode, $urls1);
2044 preg_match_all("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $bbcode, $urls);
2046 $ordered_urls = array();
2047 foreach ($urls[1] AS $id=>$url) {
2048 //$start = strpos($text, $url, $offset);
2049 $start = iconv_strpos($text, $url, 0, "UTF-8");
2050 if (!($start === false))
2051 $ordered_urls[$start] = array("url" => $url, "title" => $urls[2][$id]);
2054 ksort($ordered_urls);
2057 //foreach ($urls[1] AS $id=>$url) {
2058 foreach ($ordered_urls AS $url) {
2059 if ((substr($url["title"], 0, 7) != "http://") AND (substr($url["title"], 0, 8) != "https://") AND
2060 !strpos($url["title"], "http://") AND !strpos($url["title"], "https://"))
2061 $display_url = $url["title"];
2063 $display_url = str_replace(array("http://www.", "https://www."), array("", ""), $url["url"]);
2064 $display_url = str_replace(array("http://", "https://"), array("", ""), $display_url);
2066 if (strlen($display_url) > 26)
2067 $display_url = substr($display_url, 0, 25)."…";
2070 //$start = strpos($text, $url, $offset);
2071 $start = iconv_strpos($text, $url["url"], $offset, "UTF-8");
2072 if (!($start === false)) {
2073 $entities["urls"][] = array("url" => $url["url"],
2074 "expanded_url" => $url["url"],
2075 "display_url" => $display_url,
2076 "indices" => array($start, $start+strlen($url["url"])));
2077 $offset = $start + 1;
2081 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
2082 $ordered_images = array();
2083 foreach ($images[1] AS $image) {
2084 //$start = strpos($text, $url, $offset);
2085 $start = iconv_strpos($text, $image, 0, "UTF-8");
2086 if (!($start === false))
2087 $ordered_images[$start] = $image;
2089 //$entities["media"] = array();
2092 foreach ($ordered_images AS $url) {
2093 $display_url = str_replace(array("http://www.", "https://www."), array("", ""), $url);
2094 $display_url = str_replace(array("http://", "https://"), array("", ""), $display_url);
2096 if (strlen($display_url) > 26)
2097 $display_url = substr($display_url, 0, 25)."…";
2099 $start = iconv_strpos($text, $url, $offset, "UTF-8");
2100 if (!($start === false)) {
2101 $image = get_photo_info($url);
2103 // If image cache is activated, then use the following sizes:
2104 // thumb (150), small (340), medium (600) and large (1024)
2105 if (!get_config("system", "proxy_disabled")) {
2106 $media_url = proxy_url($url);
2109 $scale = scale_image($image[0], $image[1], 150);
2110 $sizes["thumb"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2112 if (($image[0] > 150) OR ($image[1] > 150)) {
2113 $scale = scale_image($image[0], $image[1], 340);
2114 $sizes["small"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2117 $scale = scale_image($image[0], $image[1], 600);
2118 $sizes["medium"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2120 if (($image[0] > 600) OR ($image[1] > 600)) {
2121 $scale = scale_image($image[0], $image[1], 1024);
2122 $sizes["large"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
2126 $sizes["medium"] = array("w" => $image[0], "h" => $image[1], "resize" => "fit");
2129 $entities["media"][] = array(
2131 "id_str" => (string)$start+1,
2132 "indices" => array($start, $start+strlen($url)),
2133 "media_url" => normalise_link($media_url),
2134 "media_url_https" => $media_url,
2136 "display_url" => $display_url,
2137 "expanded_url" => $url,
2141 $offset = $start + 1;
2147 function api_format_items_embeded_images($item, $text){
2149 $text = preg_replace_callback(
2150 "|data:image/([^;]+)[^=]+=*|m",
2151 function($match) use ($a, $item) {
2152 return $a->get_baseurl()."/display/".$item['guid'];
2158 function api_format_items($r,$user_info, $filter_user = false) {
2163 foreach($r as $item) {
2164 api_share_as_retweet($item);
2166 localize_item($item);
2167 $status_user = api_item_get_user($a,$item);
2169 // Look if the posts are matching if they should be filtered by user id
2170 if ($filter_user AND ($status_user["id"] != $user_info["id"]))
2173 if ($item['thr-parent'] != $item['uri']) {
2174 $r = q("SELECT id FROM item WHERE uid=%d AND uri='%s' LIMIT 1",
2176 dbesc($item['thr-parent']));
2178 $in_reply_to_status_id = intval($r[0]['id']);
2180 $in_reply_to_status_id = intval($item['parent']);
2182 $in_reply_to_status_id_str = (string) intval($item['parent']);
2184 $in_reply_to_screen_name = NULL;
2185 $in_reply_to_user_id = NULL;
2186 $in_reply_to_user_id_str = NULL;
2188 $r = q("SELECT `author-link` FROM item WHERE uid=%d AND id=%d LIMIT 1",
2190 intval($in_reply_to_status_id));
2192 $r = q("SELECT * FROM `unique_contacts` WHERE `url` = '%s'", dbesc(normalise_link($r[0]['author-link'])));
2195 if ($r[0]['nick'] == "")
2196 $r[0]['nick'] = api_get_nick($r[0]["url"]);
2198 $in_reply_to_screen_name = (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']);
2199 $in_reply_to_user_id = intval($r[0]['id']);
2200 $in_reply_to_user_id_str = (string) intval($r[0]['id']);
2204 $in_reply_to_screen_name = NULL;
2205 $in_reply_to_user_id = NULL;
2206 $in_reply_to_status_id = NULL;
2207 $in_reply_to_user_id_str = NULL;
2208 $in_reply_to_status_id_str = NULL;
2211 $converted = api_convert_item($item);
2214 'text' => $converted["text"],
2215 'truncated' => False,
2216 'created_at'=> api_date($item['created']),
2217 'in_reply_to_status_id' => $in_reply_to_status_id,
2218 'in_reply_to_status_id_str' => $in_reply_to_status_id_str,
2219 'source' => (($item['app']) ? $item['app'] : 'web'),
2220 'id' => intval($item['id']),
2221 'id_str' => (string) intval($item['id']),
2222 'in_reply_to_user_id' => $in_reply_to_user_id,
2223 'in_reply_to_user_id_str' => $in_reply_to_user_id_str,
2224 'in_reply_to_screen_name' => $in_reply_to_screen_name,
2226 'favorited' => $item['starred'] ? true : false,
2227 'user' => $status_user ,
2228 //'entities' => NULL,
2229 'statusnet_html' => $converted["html"],
2230 'statusnet_conversation_id' => $item['parent'],
2233 if (count($converted["attachments"]) > 0)
2234 $status["attachments"] = $converted["attachments"];
2236 if (count($converted["entities"]) > 0)
2237 $status["entities"] = $converted["entities"];
2239 if (($item['item_network'] != "") AND ($status["source"] == 'web'))
2240 $status["source"] = network_to_name($item['item_network'], $user_info['url']);
2241 else if (($item['item_network'] != "") AND (network_to_name($item['item_network'], $user_info['url']) != $status["source"]))
2242 $status["source"] = trim($status["source"].' ('.network_to_name($item['item_network'], $user_info['url']).')');
2245 // Retweets are only valid for top postings
2246 // It doesn't work reliable with the link if its a feed
2247 $IsRetweet = ($item['owner-link'] != $item['author-link']);
2249 $IsRetweet = (($item['owner-name'] != $item['author-name']) OR ($item['owner-avatar'] != $item['author-avatar']));
2251 if ($IsRetweet AND ($item["id"] == $item["parent"])) {
2252 $retweeted_status = $status;
2253 $retweeted_status["user"] = api_get_user($a,$item["author-link"]);
2255 $status["retweeted_status"] = $retweeted_status;
2258 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2259 unset($status["user"]["uid"]);
2260 unset($status["user"]["self"]);
2262 if ($item["coord"] != "") {
2263 $coords = explode(' ',$item["coord"]);
2264 if (count($coords) == 2) {
2265 $status["geo"] = array('type' => 'Point',
2266 'coordinates' => array((float) $coords[0],
2267 (float) $coords[1]));
2277 function api_account_rate_limit_status(&$a,$type) {
2280 'reset_time_in_seconds' => strtotime('now + 1 hour'),
2281 'remaining_hits' => (string) 150,
2282 'hourly_limit' => (string) 150,
2283 'reset_time' => api_date(datetime_convert('UTC','UTC','now + 1 hour',ATOM_TIME)),
2286 $hash['resettime_in_seconds'] = $hash['reset_time_in_seconds'];
2288 return api_apply_template('ratelimit', $type, array('$hash' => $hash));
2291 api_register_func('api/account/rate_limit_status','api_account_rate_limit_status',true);
2293 function api_help_test(&$a,$type) {
2300 return api_apply_template('test', $type, array("$ok" => $ok));
2303 api_register_func('api/help/test','api_help_test',false);
2305 function api_lists(&$a,$type) {
2310 api_register_func('api/lists','api_lists',true);
2312 function api_lists_list(&$a,$type) {
2317 api_register_func('api/lists/list','api_lists_list',true);
2320 * https://dev.twitter.com/docs/api/1/get/statuses/friends
2321 * This function is deprecated by Twitter
2322 * returns: json, xml
2324 function api_statuses_f(&$a, $type, $qtype) {
2325 if (api_user()===false) return false;
2326 $user_info = api_get_user($a);
2328 if (x($_GET,'cursor') && $_GET['cursor']=='undefined'){
2329 /* this is to stop Hotot to load friends multiple times
2330 * I'm not sure if I'm missing return something or
2331 * is a bug in hotot. Workaround, meantime
2335 return array('$users' => $ret);*/
2339 if($qtype == 'friends')
2340 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
2341 if($qtype == 'followers')
2342 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
2344 // friends and followers only for self
2345 if ($user_info['self'] == 0)
2346 $sql_extra = " AND false ";
2348 $r = q("SELECT `nurl` FROM `contact` WHERE `uid` = %d AND `self` = 0 AND `blocked` = 0 AND `pending` = 0 $sql_extra",
2353 foreach($r as $cid){
2354 $user = api_get_user($a, $cid['nurl']);
2355 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2356 unset($user["uid"]);
2357 unset($user["self"]);
2363 return array('$users' => $ret);
2366 function api_statuses_friends(&$a, $type){
2367 $data = api_statuses_f($a,$type,"friends");
2368 if ($data===false) return false;
2369 return api_apply_template("friends", $type, $data);
2371 function api_statuses_followers(&$a, $type){
2372 $data = api_statuses_f($a,$type,"followers");
2373 if ($data===false) return false;
2374 return api_apply_template("friends", $type, $data);
2376 api_register_func('api/statuses/friends','api_statuses_friends',true);
2377 api_register_func('api/statuses/followers','api_statuses_followers',true);
2384 function api_statusnet_config(&$a,$type) {
2385 $name = $a->config['sitename'];
2386 $server = $a->get_hostname();
2387 $logo = $a->get_baseurl() . '/images/friendica-64.png';
2388 $email = $a->config['admin_email'];
2389 $closed = (($a->config['register_policy'] == REGISTER_CLOSED) ? 'true' : 'false');
2390 $private = (($a->config['system']['block_public']) ? 'true' : 'false');
2391 $textlimit = (string) (($a->config['max_import_size']) ? $a->config['max_import_size'] : 200000);
2392 if($a->config['api_import_size'])
2393 $texlimit = string($a->config['api_import_size']);
2394 $ssl = (($a->config['system']['have_ssl']) ? 'true' : 'false');
2395 $sslserver = (($ssl === 'true') ? str_replace('http:','https:',$a->get_baseurl()) : '');
2398 'site' => array('name' => $name,'server' => $server, 'theme' => 'default', 'path' => '',
2399 'logo' => $logo, 'fancy' => true, 'language' => 'en', 'email' => $email, 'broughtby' => '',
2400 'broughtbyurl' => '', 'timezone' => 'UTC', 'closed' => $closed, 'inviteonly' => false,
2401 'private' => $private, 'textlimit' => $textlimit, 'sslserver' => $sslserver, 'ssl' => $ssl,
2402 'shorturllength' => '30',
2403 'friendica' => array(
2404 'FRIENDICA_PLATFORM' => FRIENDICA_PLATFORM,
2405 'FRIENDICA_VERSION' => FRIENDICA_VERSION,
2406 'DFRN_PROTOCOL_VERSION' => DFRN_PROTOCOL_VERSION,
2407 'DB_UPDATE_VERSION' => DB_UPDATE_VERSION
2412 return api_apply_template('config', $type, array('$config' => $config));
2415 api_register_func('api/statusnet/config','api_statusnet_config',false);
2417 function api_statusnet_version(&$a,$type) {
2421 if($type === 'xml') {
2422 header("Content-type: application/xml");
2423 echo '<?xml version="1.0" encoding="UTF-8"?>' . "\r\n" . '<version>0.9.7</version>' . "\r\n";
2426 elseif($type === 'json') {
2427 header("Content-type: application/json");
2432 api_register_func('api/statusnet/version','api_statusnet_version',false);
2435 function api_ff_ids(&$a,$type,$qtype) {
2439 $user_info = api_get_user($a);
2441 if($qtype == 'friends')
2442 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
2443 if($qtype == 'followers')
2444 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
2446 if (!$user_info["self"])
2447 $sql_extra = " AND false ";
2449 $stringify_ids = (x($_REQUEST,'stringify_ids')?$_REQUEST['stringify_ids']:false);
2451 $r = q("SELECT `unique_contact`.`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",
2457 if($type === 'xml') {
2458 header("Content-type: application/xml");
2459 echo '<?xml version="1.0" encoding="UTF-8"?>' . "\r\n" . '<ids>' . "\r\n";
2461 echo '<id>' . $rr['id'] . '</id>' . "\r\n";
2462 echo '</ids>' . "\r\n";
2465 elseif($type === 'json') {
2467 header("Content-type: application/json");
2472 $ret[] = intval($rr['id']);
2474 echo json_encode($ret);
2480 function api_friends_ids(&$a,$type) {
2481 api_ff_ids($a,$type,'friends');
2483 function api_followers_ids(&$a,$type) {
2484 api_ff_ids($a,$type,'followers');
2486 api_register_func('api/friends/ids','api_friends_ids',true);
2487 api_register_func('api/followers/ids','api_followers_ids',true);
2490 function api_direct_messages_new(&$a, $type) {
2491 if (api_user()===false) return false;
2493 if (!x($_POST, "text") OR (!x($_POST,"screen_name") AND !x($_POST,"user_id"))) return;
2495 $sender = api_get_user($a);
2497 if ($_POST['screen_name']) {
2498 $r = q("SELECT `id`, `nurl`, `network` FROM `contact` WHERE `uid`=%d AND `nick`='%s'",
2500 dbesc($_POST['screen_name']));
2502 // Selecting the id by priority, friendica first
2503 api_best_nickname($r);
2505 $recipient = api_get_user($a, $r[0]['nurl']);
2507 $recipient = api_get_user($a, $_POST['user_id']);
2511 if (x($_REQUEST,'replyto')) {
2512 $r = q('SELECT `parent-uri`, `title` FROM `mail` WHERE `uid`=%d AND `id`=%d',
2514 intval($_REQUEST['replyto']));
2515 $replyto = $r[0]['parent-uri'];
2516 $sub = $r[0]['title'];
2519 if (x($_REQUEST,'title')) {
2520 $sub = $_REQUEST['title'];
2523 $sub = ((strlen($_POST['text'])>10)?substr($_POST['text'],0,10)."...":$_POST['text']);
2527 $id = send_message($recipient['cid'], $_POST['text'], $sub, $replyto);
2530 $r = q("SELECT * FROM `mail` WHERE id=%d", intval($id));
2531 $ret = api_format_messages($r[0], $recipient, $sender);
2534 $ret = array("error"=>$id);
2537 $data = Array('$messages'=>$ret);
2542 $data = api_rss_extra($a, $data, $user_info);
2545 return api_apply_template("direct_messages", $type, $data);
2548 api_register_func('api/direct_messages/new','api_direct_messages_new',true);
2550 function api_direct_messages_box(&$a, $type, $box) {
2551 if (api_user()===false) return false;
2555 $count = (x($_GET,'count')?$_GET['count']:20);
2556 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
2557 if ($page<0) $page=0;
2559 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
2560 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
2562 $user_id = (x($_REQUEST,'user_id')?$_REQUEST['user_id']:"");
2563 $screen_name = (x($_REQUEST,'screen_name')?$_REQUEST['screen_name']:"");
2566 unset($_REQUEST["user_id"]);
2567 unset($_GET["user_id"]);
2569 unset($_REQUEST["screen_name"]);
2570 unset($_GET["screen_name"]);
2572 $user_info = api_get_user($a);
2573 //$profile_url = $a->get_baseurl() . '/profile/' . $a->user['nickname'];
2574 $profile_url = $user_info["url"];
2578 $start = $page*$count;
2581 if ($box=="sentbox") {
2582 $sql_extra = "`mail`.`from-url`='".dbesc( $profile_url )."'";
2584 elseif ($box=="conversation") {
2585 $sql_extra = "`mail`.`parent-uri`='".dbesc( $_GET["uri"] ) ."'";
2587 elseif ($box=="all") {
2588 $sql_extra = "true";
2590 elseif ($box=="inbox") {
2591 $sql_extra = "`mail`.`from-url`!='".dbesc( $profile_url )."'";
2595 $sql_extra .= ' AND `mail`.`id` <= '.intval($max_id);
2597 if ($user_id !="") {
2598 $sql_extra .= ' AND `mail`.`contact-id` = ' . intval($user_id);
2600 elseif($screen_name !=""){
2601 $sql_extra .= " AND `contact`.`nick` = '" . dbesc($screen_name). "'";
2604 $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",
2607 intval($start), intval($count)
2612 foreach($r as $item) {
2613 if ($box == "inbox" || $item['from-url'] != $profile_url){
2614 $recipient = $user_info;
2615 $sender = api_get_user($a,normalise_link($item['contact-url']));
2617 elseif ($box == "sentbox" || $item['from-url'] == $profile_url){
2618 $recipient = api_get_user($a,normalise_link($item['contact-url']));
2619 $sender = $user_info;
2622 $ret[]=api_format_messages($item, $recipient, $sender);
2626 $data = array('$messages' => $ret);
2630 $data = api_rss_extra($a, $data, $user_info);
2633 return api_apply_template("direct_messages", $type, $data);
2637 function api_direct_messages_sentbox(&$a, $type){
2638 return api_direct_messages_box($a, $type, "sentbox");
2640 function api_direct_messages_inbox(&$a, $type){
2641 return api_direct_messages_box($a, $type, "inbox");
2643 function api_direct_messages_all(&$a, $type){
2644 return api_direct_messages_box($a, $type, "all");
2646 function api_direct_messages_conversation(&$a, $type){
2647 return api_direct_messages_box($a, $type, "conversation");
2649 api_register_func('api/direct_messages/conversation','api_direct_messages_conversation',true);
2650 api_register_func('api/direct_messages/all','api_direct_messages_all',true);
2651 api_register_func('api/direct_messages/sent','api_direct_messages_sentbox',true);
2652 api_register_func('api/direct_messages','api_direct_messages_inbox',true);
2656 function api_oauth_request_token(&$a, $type){
2658 $oauth = new FKOAuth1();
2659 $r = $oauth->fetch_request_token(OAuthRequest::from_request());
2660 }catch(Exception $e){
2661 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage()); killme();
2666 function api_oauth_access_token(&$a, $type){
2668 $oauth = new FKOAuth1();
2669 $r = $oauth->fetch_access_token(OAuthRequest::from_request());
2670 }catch(Exception $e){
2671 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage()); killme();
2677 api_register_func('api/oauth/request_token', 'api_oauth_request_token', false);
2678 api_register_func('api/oauth/access_token', 'api_oauth_access_token', false);
2681 function api_fr_photos_list(&$a,$type) {
2682 if (api_user()===false) return false;
2683 $r = q("select distinct `resource-id` from photo where uid = %d and album != 'Contact Photos' ",
2684 intval(local_user())
2689 $ret[] = $rr['resource-id'];
2690 header("Content-type: application/json");
2691 echo json_encode($ret);
2696 function api_fr_photo_detail(&$a,$type) {
2697 if (api_user()===false) return false;
2698 if(! $_REQUEST['photo_id']) return false;
2699 $scale = ((array_key_exists('scale',$_REQUEST)) ? intval($_REQUEST['scale']) : 0);
2700 $r = q("select * from photo where uid = %d and `resource-id` = '%s' and scale = %d limit 1",
2701 intval(local_user()),
2702 dbesc($_REQUEST['photo_id']),
2706 header("Content-type: application/json");
2707 $r[0]['data'] = base64_encode($r[0]['data']);
2708 echo json_encode($r[0]);
2714 api_register_func('api/friendica/photos/list', 'api_fr_photos_list', true);
2715 api_register_func('api/friendica/photo', 'api_fr_photo_detail', true);
2720 * similar as /mod/redir.php
2721 * redirect to 'url' after dfrn auth
2723 * why this when there is mod/redir.php already?
2724 * This use api_user() and api_login()
2727 * c_url: url of remote contact to auth to
2728 * url: string, url to redirect after auth
2730 function api_friendica_remoteauth(&$a) {
2731 $url = ((x($_GET,'url')) ? $_GET['url'] : '');
2732 $c_url = ((x($_GET,'c_url')) ? $_GET['c_url'] : '');
2734 if ($url === '' || $c_url === '')
2735 die((api_error($a, 'json', "Wrong parameters")));
2737 $c_url = normalise_link($c_url);
2741 $r = q("SELECT * FROM `contact` WHERE `id` = %d AND `nurl` = '%s' LIMIT 1",
2746 if ((! count($r)) || ($r[0]['network'] !== NETWORK_DFRN))
2747 die((api_error($a, 'json', "Unknown contact")));
2751 $dfrn_id = $orig_id = (($r[0]['issued-id']) ? $r[0]['issued-id'] : $r[0]['dfrn-id']);
2753 if($r[0]['duplex'] && $r[0]['issued-id']) {
2754 $orig_id = $r[0]['issued-id'];
2755 $dfrn_id = '1:' . $orig_id;
2757 if($r[0]['duplex'] && $r[0]['dfrn-id']) {
2758 $orig_id = $r[0]['dfrn-id'];
2759 $dfrn_id = '0:' . $orig_id;
2762 $sec = random_string();
2764 q("INSERT INTO `profile_check` ( `uid`, `cid`, `dfrn_id`, `sec`, `expire`)
2765 VALUES( %d, %s, '%s', '%s', %d )",
2773 logger($r[0]['name'] . ' ' . $sec, LOGGER_DEBUG);
2774 $dest = (($url) ? '&destination_url=' . $url : '');
2775 goaway ($r[0]['poll'] . '?dfrn_id=' . $dfrn_id
2776 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
2777 . '&type=profile&sec=' . $sec . $dest . $quiet );
2779 api_register_func('api/friendica/remoteauth', 'api_friendica_remoteauth', true);
2783 function api_share_as_retweet(&$item) {
2784 $body = trim($item["body"]);
2786 // Skip if it isn't a pure repeated messages
2787 // Does it start with a share?
2788 if (strpos($body, "[share") > 0)
2791 // Does it end with a share?
2792 if (strlen($body) > (strrpos($body, "[/share]") + 8))
2795 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$1",$body);
2796 // Skip if there is no shared message in there
2797 if ($body == $attributes)
2801 preg_match("/author='(.*?)'/ism", $attributes, $matches);
2802 if ($matches[1] != "")
2803 $author = html_entity_decode($matches[1],ENT_QUOTES,'UTF-8');
2805 preg_match('/author="(.*?)"/ism', $attributes, $matches);
2806 if ($matches[1] != "")
2807 $author = $matches[1];
2810 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
2811 if ($matches[1] != "")
2812 $profile = $matches[1];
2814 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
2815 if ($matches[1] != "")
2816 $profile = $matches[1];
2819 preg_match("/avatar='(.*?)'/ism", $attributes, $matches);
2820 if ($matches[1] != "")
2821 $avatar = $matches[1];
2823 preg_match('/avatar="(.*?)"/ism', $attributes, $matches);
2824 if ($matches[1] != "")
2825 $avatar = $matches[1];
2828 preg_match("/link='(.*?)'/ism", $attributes, $matches);
2829 if ($matches[1] != "")
2830 $link = $matches[1];
2832 preg_match('/link="(.*?)"/ism', $attributes, $matches);
2833 if ($matches[1] != "")
2834 $link = $matches[1];
2836 $shared_body = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$2",$body);
2838 if (($shared_body == "") OR ($profile == "") OR ($author == "") OR ($avatar == ""))
2841 $item["body"] = $shared_body;
2842 $item["author-name"] = $author;
2843 $item["author-link"] = $profile;
2844 $item["author-avatar"] = $avatar;
2845 $item["plink"] = $link;
2851 function api_get_nick($profile) {
2853 - remove trailing junk from profile url
2854 - pump.io check has to check the website
2859 $r = q("SELECT `nick` FROM `gcontact` WHERE `nurl` = '%s'",
2860 dbesc(normalise_link($profile)));
2862 $nick = $r[0]["nick"];
2865 $r = q("SELECT `nick` FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s'",
2866 dbesc(normalise_link($profile)));
2868 $nick = $r[0]["nick"];
2872 $friendica = preg_replace("=https?://(.*)/profile/(.*)=ism", "$2", $profile);
2873 if ($friendica != $profile)
2878 $diaspora = preg_replace("=https?://(.*)/u/(.*)=ism", "$2", $profile);
2879 if ($diaspora != $profile)
2884 $twitter = preg_replace("=https?://twitter.com/(.*)=ism", "$1", $profile);
2885 if ($twitter != $profile)
2891 $StatusnetHost = preg_replace("=https?://(.*)/user/(.*)=ism", "$1", $profile);
2892 if ($StatusnetHost != $profile) {
2893 $StatusnetUser = preg_replace("=https?://(.*)/user/(.*)=ism", "$2", $profile);
2894 if ($StatusnetUser != $profile) {
2895 $UserData = fetch_url("http://".$StatusnetHost."/api/users/show.json?user_id=".$StatusnetUser);
2896 $user = json_decode($UserData);
2898 $nick = $user->screen_name;
2903 // To-Do: look at the page if its really a pumpio site
2904 //if (!$nick == "") {
2905 // $pumpio = preg_replace("=https?://(.*)/(.*)/=ism", "$2", $profile."/");
2906 // if ($pumpio != $profile)
2908 // <div class="media" id="profile-block" data-profile-id="acct:kabniel@microca.st">
2913 q("UPDATE `unique_contacts` SET `nick` = '%s' WHERE `nick` != '%s' AND url = '%s'",
2914 dbesc($nick), dbesc($nick), dbesc(normalise_link($profile)));
2921 function api_clean_plain_items($Text) {
2922 $include_entities = strtolower(x($_REQUEST,'include_entities')?$_REQUEST['include_entities']:"false");
2924 $Text = bb_CleanPictureLinks($Text);
2926 $URLSearchString = "^\[\]";
2928 $Text = preg_replace("/([!#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'$1$3',$Text);
2930 if ($include_entities == "true") {
2931 $Text = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'[url=$1]$1[/url]',$Text);
2934 $Text = preg_replace_callback("((.*?)\[class=(.*?)\](.*?)\[\/class\])ism","api_cleanup_share",$Text);
2938 function api_cleanup_share($shared) {
2939 if ($shared[2] != "type-link")
2942 if (!preg_match_all("/\[bookmark\=([^\]]*)\](.*?)\[\/bookmark\]/ism",$shared[3], $bookmark))
2948 if (isset($bookmark[2][0]))
2949 $title = $bookmark[2][0];
2951 if (isset($bookmark[1][0]))
2952 $link = $bookmark[1][0];
2954 if (strpos($shared[1],$title) !== false)
2957 if (strpos($shared[1],$link) !== false)
2960 $text = trim($shared[1]);
2962 //if (strlen($text) < strlen($title))
2963 if (($text == "") AND ($title != ""))
2964 $text .= "\n\n".trim($title);
2967 $text .= "\n".trim($link);
2969 return(trim($text));
2972 function api_best_nickname(&$contacts) {
2973 $best_contact = array();
2975 if (count($contact) == 0)
2978 foreach ($contacts AS $contact)
2979 if ($contact["network"] == "") {
2980 $contact["network"] = "dfrn";
2981 $best_contact = array($contact);
2984 if (sizeof($best_contact) == 0)
2985 foreach ($contacts AS $contact)
2986 if ($contact["network"] == "dfrn")
2987 $best_contact = array($contact);
2989 if (sizeof($best_contact) == 0)
2990 foreach ($contacts AS $contact)
2991 if ($contact["network"] == "dspr")
2992 $best_contact = array($contact);
2994 if (sizeof($best_contact) == 0)
2995 foreach ($contacts AS $contact)
2996 if ($contact["network"] == "stat")
2997 $best_contact = array($contact);
2999 if (sizeof($best_contact) == 0)
3000 foreach ($contacts AS $contact)
3001 if ($contact["network"] == "pump")
3002 $best_contact = array($contact);
3004 if (sizeof($best_contact) == 0)
3005 foreach ($contacts AS $contact)
3006 if ($contact["network"] == "twit")
3007 $best_contact = array($contact);
3009 if (sizeof($best_contact) == 1)
3010 $contacts = $best_contact;
3012 $contacts = array($contacts[0]);
3018 [pagename] => api/1.1/statuses/lookup.json
3019 [id] => 605138389168451584
3020 [include_cards] => true
3021 [cards_platform] => Android-12
3022 [include_entities] => true
3023 [include_my_retweet] => 1
3025 [include_reply_count] => true
3026 [include_descendent_reply_count] => true
3030 Not implemented by now:
3031 statuses/retweets_of_me
3036 account/update_location
3037 account/update_profile_background_image
3038 account/update_profile_image
3042 Not implemented in status.net:
3043 statuses/retweeted_to_me
3044 statuses/retweeted_by_me
3045 direct_messages/destroy
3047 account/update_delivery_device
3048 notifications/follow